Skip to content
Verified contractExactMIT

Pepi

Address0x3103cd1602d5fa8f4b9283f9d5a7fa2290795d51
Balance

0 ETH

 

Transactions

2,298

 

Compiler

solc 0.8.33

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.33+commit.64118f21
Language
solidity
Optimization
Yes, 1 runs
EVM version
osaka
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
24,579,501
Creation transaction
0x445cc7f39d…760bc81212

project/contracts/token/Pepi.sol

//https://twitter.com/Pepi_ERC20i
//https://t.me/pepe_ERC20i
//https://pepe-erc20i.vip/

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

import "./Erc20.sol";
import "./PoolCreatableErc20i.sol";
import "./IHasItemsWithRoe.sol";
import "../Generator.sol";

library ExtraSeedLibrary {
    function extra(
        address account,
        uint extraSeed
    ) internal pure returns (uint256) {
        return uint(keccak256(abi.encodePacked(account, extraSeed)));
    }
}

abstract contract HasItemsWithRoe is PoolCreatableErc20i, IHasItemsWithRoe {
    using ExtraSeedLibrary for address;

    error ItemNotFound();
    error TransferFromZero();
    error TransferToZero();
    error TransferAmountExceedsBalance();
    error UnknownValue();
    error NotOwnerOfItems();
    error ItemValueMismatch();
    error NotStarted();
    error MaxBuyLimit();

    uint internal constant _VALUE_LVL_1 = 1;
    uint internal constant _VALUE_LVL_2 = 2;
    uint internal constant _VALUE_LVL_3 = 4;
    uint internal constant _VALUE_LVL_4 = 6;
    uint internal constant _VALUE_LVL_5 = 8;
    /// @dev Max new items minted per incoming transfer from source; remainder becomes roe.
    uint internal constant _MAX_NEW_ITEMS_PER_INCOMING = 1000;
    uint8 internal constant _BURN_REASON_TO_SOURCE = 1;
    uint8 internal constant _BURN_REASON_INVARIANT = 2;
    uint8 internal constant _BURN_REASON_SOURCE_SANITIZE = 3;
    uint8 internal constant _BURN_REASON_PARTIAL_ROE = 4;

    mapping(address owner => uint) _itemCounts;
    mapping(address owner => mapping(uint index => uint itemId)) _ownedTokenIds;
    mapping(address owner => mapping(uint itemId => uint index))
        _ownedTokenIndexes;
    mapping(address owner => mapping(uint itemId => SeedData seed_data))
        _ownedTokens;
    mapping(address owner => mapping(uint itemId => bool)) _owns;
    mapping(address owner => mapping(uint value => uint[] itemIds))
        _ownedValueItemIds;
    mapping(address owner => mapping(uint itemId => uint valueIndex))
        _ownedValueItemIndexes;
    mapping(address owner => uint totalValue) _itemValueTotals;
    mapping(address owner => SeedData roe_data) _roe;

    mapping(uint index => address user) _holderList;
    mapping(address user => uint index) _holderListIndexes;
    mapping(address user => bool exists) _holderExists;
    mapping(address addr => bool isItemSource) _itemSources;

    uint _itemsTotalCount;
    uint _holdersCount;
    uint _roeTotalCount;
    uint _nextItemId = 1;
    uint _random_nonce;

    constructor() PoolCreatableErc20i("PEPi", "PEPI", msg.sender) {}

    function tokenUnit() external pure returns (uint256) {
        return _tokenUnit();
    }

    function isItemSource(address addr) public view returns (bool) {
        return _isItemSource(addr);
    }

    function isSeedSource(address addr) public view returns (bool) {
        return isItemSource(addr);
    }

    function _isItemSource(address addr) internal virtual view returns (bool) {
        return _itemSources[addr];
    }

    function _setItemSource(address addr, bool value) internal {
        _itemSources[addr] = value;
        if (value) {
            _sanitizeSourceAccount(addr);
        } else {
            _syncRoe(addr);
            _syncHolder(addr);
        }
    }

    function _sanitizeSourceAccount(address account) internal {
        _burnAllItems(account, _BURN_REASON_SOURCE_SANITIZE);
        _syncRoe(account);
        _syncHolder(account);
    }

    function _handleTransferState(
        address from,
        address to,
        uint256 amount,
        uint roeFrom,
        bool mintFromSource
    ) internal {
        if (from == address(this)) {
            return;
        }

        if (amount > roeFrom) {
            uint needToFreeRaw = amount - roeFrom;
            uint itemIdExact = _tryExactValueItem(from, amount);
            if (itemIdExact != 0) {
                // Special rule for value=1: when transferring 1 token between non-sources
                // we treat it as pure roe instead of a separate lvl1 item — the item is burned
                // and the receiver gets roe=1.
                if (amount == _tokenUnit() * _VALUE_LVL_1) {
                    SeedData memory burned = _removeItemFromOwner(from, itemIdExact);
                    emit OnItemBurn(from, itemIdExact, burned.value, _BURN_REASON_PARTIAL_ROE);
                } else {
                    // For other values (2, 4, 6, 8), the exact amount moves one item (LIFO within the value bucket).
                    _moveOneItem(from, to, itemIdExact);
                }
            } else {
                _freeItemsFromEndOfList(from, to, needToFreeRaw);
            }
        }

        if (
            mintFromSource &&
            to != address(0) &&
            !_isItemSource(to) &&
            amount >= _tokenUnit()
        ) {
            _mintItemsFromIncoming(to, amount / _tokenUnit());
        }

        _enforceInvariant(from);
        _enforceInvariant(to);
    }

    /// @dev If amountRaw equals a constant value (V * tokenUnit) and owner has such item, returns item id from end of that value bucket; else 0.
    function _tryExactValueItem(
        address owner,
        uint amountRaw
    ) internal view returns (uint) {
        uint unit = _tokenUnit();
        if (amountRaw == unit * _VALUE_LVL_1) return _getLastOwnerItemIdByValue(owner, _VALUE_LVL_1);
        if (amountRaw == unit * _VALUE_LVL_2) return _getLastOwnerItemIdByValue(owner, _VALUE_LVL_2);
        if (amountRaw == unit * _VALUE_LVL_3) return _getLastOwnerItemIdByValue(owner, _VALUE_LVL_3);
        if (amountRaw == unit * _VALUE_LVL_4) return _getLastOwnerItemIdByValue(owner, _VALUE_LVL_4);
        if (amountRaw == unit * _VALUE_LVL_5) return _getLastOwnerItemIdByValue(owner, _VALUE_LVL_5);
        return 0;
    }

    function _moveOneItem(address from, address to, uint itemId) internal {
        SeedData memory moved = _removeItemFromOwner(from, itemId);
        if (_isItemSource(to) || to == address(0)) {
            emit OnItemBurn(from, itemId, moved.value, _BURN_REASON_TO_SOURCE);
        } else {
            _addItemToOwnerWithId(to, moved, itemId);
            emit OnItemTransfer(from, to, itemId, moved);
        }
    }

    /// @dev Free needToFreeRaw (raw units) by moving or burning items from the end of owner's index list.
    function _freeItemsFromEndOfList(
        address from,
        address to,
        uint needToFreeRaw
    ) internal {
        uint unit = _tokenUnit();
        while (needToFreeRaw > 0 && _itemCounts[from] > 0) {
            uint index = _itemCounts[from] - 1;
            uint itemId = _ownedTokenIds[from][index];
            SeedData memory data = _ownedTokens[from][itemId];
            uint V = data.value;
            uint V_raw = V * unit;

            _removeItemFromOwner(from, itemId);

            if (V_raw <= needToFreeRaw) {
                needToFreeRaw -= V_raw;
                if (_isItemSource(to) || to == address(0)) {
                    emit OnItemBurn(from, itemId, V, _BURN_REASON_TO_SOURCE);
                } else {
                    _addItemToOwnerWithId(to, data, itemId);
                    emit OnItemTransfer(from, to, itemId, data);
                }
            } else {
                emit OnItemBurn(from, itemId, V, _BURN_REASON_PARTIAL_ROE);
                needToFreeRaw = 0;
            }
        }
    }

    function _mintItemsFromIncoming(address account, uint incoming) internal {
        if (incoming == 0 || _isItemSource(account)) return;
        uint remains = incoming;
        uint before = _itemCounts[account];
        unchecked {
            for (uint v = 5; v >= 1; --v) {
                uint val = v == 5 ? _VALUE_LVL_5 : v == 4 ? _VALUE_LVL_4 : v == 3 ? _VALUE_LVL_3 : v == 2 ? _VALUE_LVL_2 : _VALUE_LVL_1;
                if (remains < val) continue;
                uint n = _itemCounts[account] - before;
                if (n >= _MAX_NEW_ITEMS_PER_INCOMING) break;
                uint count = remains / val;
                if (val <= _VALUE_LVL_2) {
                    if (n != 0) break;
                    if (val == _VALUE_LVL_1 && count > 1) count = 1;
                } else {
                    uint cap = _MAX_NEW_ITEMS_PER_INCOMING - n;
                    if (count > cap) count = cap;
                }
                for (uint i = 0; i < count; ++i) _mintItem(account, val);
                remains -= count * val;
            }
        }
    }

    /// @dev Maps item value (1/2/4/6/8) to generator level 1-5. Same as former Generator lvl1Value..lvl5Value logic.
    function _valueToItemLvl(uint value) internal pure returns (uint8) {
        if (value == _VALUE_LVL_1) return 1;
        if (value == _VALUE_LVL_2) return 2;
        if (value == _VALUE_LVL_3) return 3;
        if (value == _VALUE_LVL_4) return 4;
        if (value == _VALUE_LVL_5) return 5;
        return 0;
    }

    function _mintItem(address to, uint value) internal {
        if (_isItemSource(to)) return;
        SeedData memory data = SeedData({
            lvl: _valueToItemLvl(value),
            value: value,
            seed1: RandLib.random_value(++_random_nonce),
            seed2: to.extra(++_random_nonce)
        });
        uint itemId = _nextItemId++;
        _addItemToOwnerWithId(to, data, itemId);
        emit OnItemMint(to, itemId, value, data);
    }

    function _tokenUnit() internal pure returns (uint) {
        return 10 ** uint(_decimals);
    }

    function _enforceInvariant(address account) internal {
        if (account == address(0) || account == address(this)) return;
        if (_isItemSource(account)) {
            _sanitizeSourceAccount(account);
            return;
        }

        uint balanceRaw = _balances[account];
        uint itemTotalRaw = _itemValueTotals[account] * _tokenUnit();
        while (itemTotalRaw > balanceRaw) {
            uint itemId = _selectItemIdForInvariantBurn(account);
            if (itemId == 0) break;
            SeedData memory burned = _removeItemFromOwner(account, itemId);
            emit OnItemBurn(
                account,
                itemId,
                burned.value,
                _BURN_REASON_INVARIANT
            );
        }
        _syncRoe(account);
        _syncHolder(account);
    }

    function _selectItemIdForInvariantBurn(
        address owner
    ) internal view returns (uint) {
        if (_itemCounts[owner] == 0) return 0;
        return _ownedTokenIds[owner][_itemCounts[owner] - 1];
    }

    function _targetRoe(address account) internal view returns (uint) {
        if (account == address(0) || account == address(this) || _isItemSource(account))
            return 0;
        uint balanceRaw = _balances[account];
        uint itemTotalRaw = _itemValueTotals[account] * _tokenUnit();
        if (balanceRaw <= itemTotalRaw) return 0;
        return balanceRaw - itemTotalRaw;
    }

    function _syncRoe(address account) internal {
        if (account == address(0) || account == address(this)) return;
        uint oldRoe = _roe[account].value;
        uint newRoe = _targetRoe(account);
        if (oldRoe == newRoe) return;

        if (oldRoe == 0 && newRoe > 0) ++_roeTotalCount;
        if (oldRoe > 0 && newRoe == 0 && _roeTotalCount > 0) --_roeTotalCount;

        _roe[account].lvl = 0;
        _roe[account].value = newRoe;
        _roe[account].seed1 = RandLib.random_value(++_random_nonce);
        _roe[account].seed2 = account.extra(++_random_nonce);

        if (newRoe > oldRoe) {
            emit OnRoeGrow(account, _roe[account]);
        } else {
            emit OnRoeShrink(account, _roe[account]);
        }
    }

    function _isHolder(address account) internal view returns (bool) {
        if (
            account == address(0) || account == address(this) || _isItemSource(account)
        ) return false;
        return _itemCounts[account] > 0 || _roe[account].value > 0;
    }

    function _syncHolder(address account) internal {
        if (account == address(0) || account == address(this)) return;
        bool shouldHold = _isHolder(account);
        bool exists = _holderExists[account];
        if (shouldHold && !exists) {
            _holderExists[account] = true;
            _holderList[_holdersCount] = account;
            _holderListIndexes[account] = _holdersCount;
            ++_holdersCount;
            return;
        }

        if (!shouldHold && exists) {
            uint removingIndex = _holderListIndexes[account];
            uint lastIndex = _holdersCount - 1;
            if (removingIndex != lastIndex) {
                address lastHolder = _holderList[lastIndex];
                _holderList[removingIndex] = lastHolder;
                _holderListIndexes[lastHolder] = removingIndex;
            }
            delete _holderList[lastIndex];
            delete _holderListIndexes[account];
            _holderExists[account] = false;
            --_holdersCount;
        }
    }

    function _addItemToOwnerWithId(
        address to,
        SeedData memory data,
        uint itemId
    ) internal {
        if (_isItemSource(to)) return;
        uint length = _itemCounts[to];
        _ownedTokenIds[to][length] = itemId;
        _ownedTokenIndexes[to][itemId] = length;
        _ownedTokens[to][itemId] = data;
        _owns[to][itemId] = true;
        _ownedValueItemIndexes[to][itemId] = _ownedValueItemIds[to][data.value]
            .length;
        _ownedValueItemIds[to][data.value].push(itemId);
        _itemValueTotals[to] += data.value;
        ++_itemCounts[to];
        ++_itemsTotalCount;
    }

    function _removeItemFromOwner(
        address owner,
        uint itemId
    ) internal returns (SeedData memory data) {
        data = _ownedTokens[owner][itemId];
        if (data.value == 0) revert ItemNotFound();

        uint tokenIndex = _ownedTokenIndexes[owner][itemId];
        uint lastTokenIndex = _itemCounts[owner] - 1;
        uint lastItemId = _ownedTokenIds[owner][lastTokenIndex];
        if (tokenIndex != lastTokenIndex) {
            _ownedTokenIds[owner][tokenIndex] = lastItemId;
            _ownedTokenIndexes[owner][lastItemId] = tokenIndex;
        }
        delete _ownedTokenIds[owner][lastTokenIndex];
        delete _ownedTokenIndexes[owner][itemId];
        delete _ownedTokens[owner][itemId];
        _owns[owner][itemId] = false;

        _removeOwnedValueItemId(owner, data.value, itemId);
        _itemValueTotals[owner] -= data.value;
        --_itemCounts[owner];
        if (_itemsTotalCount > 0) --_itemsTotalCount;
    }

    function _burnAllItems(address owner, uint8 reason) internal {
        while (_itemCounts[owner] > 0) {
            uint itemId = _ownedTokenIds[owner][_itemCounts[owner] - 1];
            SeedData memory burned = _removeItemFromOwner(owner, itemId);
            emit OnItemBurn(owner, itemId, burned.value, reason);
        }
    }

    function _removeOwnedValueItemId(
        address owner,
        uint value,
        uint itemId
    ) internal {
        uint[] storage ids = _ownedValueItemIds[owner][value];
        if (ids.length == 0) return;
        uint removingIndex = _ownedValueItemIndexes[owner][itemId];
        uint lastIndex = ids.length - 1;
        if (removingIndex != lastIndex) {
            uint lastId = ids[lastIndex];
            ids[removingIndex] = lastId;
            _ownedValueItemIndexes[owner][lastId] = removingIndex;
        }
        ids.pop();
        delete _ownedValueItemIndexes[owner][itemId];
    }

    function _getLastOwnerItemIdByValue(
        address owner,
        uint value
    ) internal view returns (uint) {
        uint[] storage ids = _ownedValueItemIds[owner][value];
        if (ids.length == 0) return 0;
        return ids[ids.length - 1];
    }

    function transferItem(address to, uint itemId) external returns (bool) {
        return _transferItem(msg.sender, to, itemId);
    }

    function transfer_item(address to, uint itemId) external returns (bool) {
        return _transferItem(msg.sender, to, itemId);
    }

    function _transferItem(
        address from,
        address to,
        uint itemId
    ) internal returns (bool) {
        if (from == address(0)) revert TransferFromZero();
        if (to == address(0)) revert TransferToZero();
        SeedData memory data = _ownedTokens[from][itemId];
        if (data.value == 0) return false;

        uint amount = data.value * _tokenUnit();
        if (_balances[from] < amount) revert TransferAmountExceedsBalance();
        _removeItemFromOwner(from, itemId);

        unchecked {
            _balances[from] -= amount;
            _balances[to] += amount;
        }
        emit Transfer(from, to, amount);

        if (_isItemSource(to)) {
            emit OnItemBurn(from, itemId, data.value, _BURN_REASON_TO_SOURCE);
        } else {
            _addItemToOwnerWithId(to, data, itemId);
            emit OnItemTransfer(from, to, itemId, data);
        }

        _enforceInvariant(from);
        _enforceInvariant(to);
        return true;
    }

    function isOwnerOf(address owner, uint item_id) external view returns (bool) {
        return _owns[owner][item_id];
    }

    function roeDegree(
        address owner
    ) external view returns (SeedData memory roe_data) {
        return _roe[owner];
    }

    function sporesDegree(
        address owner
    ) external view returns (SeedData memory roe_data) {
        return _roe[owner];
    }

    function itemCount(address owner) external view returns (uint) {
        return _itemCounts[owner];
    }

    function mushroomCount(address owner) external view returns (uint) {
        return _itemCounts[owner];
    }

    function itemsTotalCount() external view returns (uint) {
        return _itemsTotalCount;
    }

    function mushroomsTotalCount() external view returns (uint) {
        return _itemsTotalCount;
    }

    function holdersCount() external view returns (uint) {
        return _holdersCount;
    }

    function roeTotalCount() external view returns (uint) {
        return _roeTotalCount;
    }

    function sporesTotalCount() external view returns (uint) {
        return _roeTotalCount;
    }

    function getHolderIndex(address account) external view returns (uint) {
        return _holderListIndexes[account];
    }

    function getHoldersPage(
        uint startIndex,
        uint count
    ) external view returns (address[] memory holders, uint total) {
        total = _holdersCount;
        if (startIndex >= total || count == 0) {
            return (new address[](0), total);
        }
        uint n = count;
        if (n > total - startIndex) {
            n = total - startIndex;
        }
        holders = new address[](n);
        for (uint i = 0; i < n; ++i) {
            holders[i] = _holderList[startIndex + i];
        }
    }

    function getOwnerItemsPage(
        address owner,
        uint startIndex,
        uint count
    )
        external
        view
        returns (uint[] memory itemIds, SeedData[] memory items, uint total)
    {
        total = _itemCounts[owner];
        if (startIndex >= total || count == 0) {
            return (new uint[](0), new SeedData[](0), total);
        }
        uint n = count;
        if (n > total - startIndex) {
            n = total - startIndex;
        }
        itemIds = new uint[](n);
        items = new SeedData[](n);
        for (uint i = 0; i < n; ++i) {
            uint idx = startIndex + i;
            uint itemId = _ownedTokenIds[owner][idx];
            itemIds[i] = itemId;
            items[i] = _ownedTokens[owner][itemId];
        }
    }

    function _isKnownValue(uint value) internal pure returns (bool) {
        return value == _VALUE_LVL_1 || value == _VALUE_LVL_2 ||
            value == _VALUE_LVL_3 || value == _VALUE_LVL_4 || value == _VALUE_LVL_5;
    }

    function itemIdsByValue(
        address owner,
        uint value,
        uint offset,
        uint limit
    ) external view returns (uint[] memory itemIds, uint total) {
        if (!_isKnownValue(value)) {
            return (new uint[](0), 0);
        }
        uint[] storage ids = _ownedValueItemIds[owner][value];
        total = ids.length;
        if (offset >= total || limit == 0) {
            return (new uint[](0), total);
        }
        uint n = limit;
        if (n > total - offset) {
            n = total - offset;
        }
        itemIds = new uint[](n);
        for (uint i = 0; i < n; ++i) {
            itemIds[i] = ids[offset + i];
        }
    }

    function reorderItemsByValue(
        uint value,
        uint itemIdA,
        uint itemIdB
    ) external {
        address owner = msg.sender;
        if (!_isKnownValue(value)) revert UnknownValue();
        if (!_owns[owner][itemIdA] || !_owns[owner][itemIdB]) revert NotOwnerOfItems();
        if (_ownedTokens[owner][itemIdA].value != value) revert ItemValueMismatch();
        if (_ownedTokens[owner][itemIdB].value != value) revert ItemValueMismatch();
        if (itemIdA == itemIdB) return;

        uint[] storage ids = _ownedValueItemIds[owner][value];
        uint idxA = _ownedValueItemIndexes[owner][itemIdA];
        uint idxB = _ownedValueItemIndexes[owner][itemIdB];
        (ids[idxA], ids[idxB]) = (ids[idxB], ids[idxA]);
        _ownedValueItemIndexes[owner][itemIdA] = idxB;
        _ownedValueItemIndexes[owner][itemIdB] = idxA;
    }
}

contract Pepi is HasItemsWithRoe, Generator {
    uint constant _startTotalSupply = 13370 * (10 ** _decimals);
    uint constant _startMaxBuyCount = (_startTotalSupply * 5) / 10000;
    uint constant _addMaxBuyPercentPerSec = 5; // 100%=_addMaxBuyPrecesion add 0.005%/second
    uint constant _addMaxBuyPrecesion = 100000;

    constructor() {
        _mint(msg.sender, _startTotalSupply);
    }

    modifier maxBuyLimit(uint256 amount) {
        if (amount > maxBuy()) revert MaxBuyLimit();
        _;
    }

    function setItemSource(address addr, bool value) external onlyOwner {
        _setItemSource(addr, value);
    }

    function _isItemSource(address addr) internal override view returns (bool) {
        return addr == _pool || super._isItemSource(addr);
    }

    function maxBuy() public view returns (uint256) {
        if (!isStarted()) return _startTotalSupply;
        uint256 count = _startMaxBuyCount +
            (_startTotalSupply *
                (block.timestamp - _startTime) *
                _addMaxBuyPercentPerSec) /
            _addMaxBuyPrecesion;
        if (count > _startTotalSupply) count = _startTotalSupply;
        return count;
    }

    function _transfer(
        address from,
        address to,
        uint256 amount
    ) internal override {
        bool started = isStarted();
        bool mintFromSource;
        uint roeFrom = 0;

        if (started && from != address(this)) {
            mintFromSource = isItemSource(from);
            if (!mintFromSource && to != address(0)) {
                roeFrom = _targetRoe(from);
            }
        }

        if (isStarted()) {
            // logic is handled after token balance changes
        } else {
            if (from != _owner && to != _owner) revert NotStarted();
        }

        // allow burning
        if (to == address(0)) {
            _burn(from, amount);
            if (started) _handleTransferState(from, to, amount, roeFrom, false);
            return;
        }

        // system transfers
        if (from == address(this)) {
            super._transfer(from, to, amount);
            if (started) _enforceInvariant(to);
            return;
        }

        if (_feeLocked) {
            super._transfer(from, to, amount);
        } else {
            if (isItemSource(from)) {
                _transferFromPool(from, to, amount);
            } else {
                super._transfer(from, to, amount);
            }
        }

        if (started) {
            _handleTransferState(from, to, amount, roeFrom, mintFromSource);
        }
    }

    function _transferFromPool(
        address from,
        address to,
        uint256 amount
    ) private maxBuyLimit(amount) lockFee {
        super._transfer(from, to, amount);
    }

    function burnCount() public view returns (uint256) {
        return _startTotalSupply - totalSupply();
    }

    /// @dev Override: normalize roe value (raw) to whole units for lvl when value > 8 (roe uses raw units).
    function getItemData(
        SeedData calldata seed_data
    ) external view override returns (ItemData memory) {
        uint effectiveValue = seed_data.value <= 8
            ? seed_data.value
            : seed_data.value / _tokenUnit();
        SeedData memory normalized = SeedData({
            lvl: seed_data.lvl,
            value: effectiveValue,
            seed1: seed_data.seed1,
            seed2: seed_data.seed2
        });
        return _buildItemDataFromSeed(normalized);
    }
}

npm/@openzeppelin/[email protected]/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

npm/@openzeppelin/[email protected]/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity >=0.6.2;

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

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

npm/@openzeppelin/[email protected]/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

project/contracts/Generator.sol

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

import "./lib/Ownable.sol";

uint constant levelsCount = 6;
uint constant bcgroundsCount = 6;
uint8 constant pixelsCount = 32;
string constant description = "";
string constant web = "https://pepe-erc20i.vip/";

struct ItemData {
    uint lvl; // starts 1
    string background;
    uint body; // number or 0
    string bodyColor;
    uint cloth; // number or 0
    uint eyes; // number or 0
    uint mouth; // number or 0
    uint accessory; // number or 0
    uint hat; // number or 0
    uint ears; // number or 0
}

struct Rect {
    uint8 x;
    uint8 y;
    uint8 width;
    uint8 height;
}

struct RectColored {
    uint8 x;
    uint8 y;
    uint8 width;
    uint8 height;
    uint24 color;
}

struct FileData {
    uint lvl;
    uint file;
    Rect[] rects;
}

struct FileDataColored {
    uint lvl;
    uint file;
    RectColored[] rects;
}

struct ColorsData {
    string[] lvl0;
    string[] lvl1;
    string[] lvl2;
    string[] lvl3;
    string[] lvl4;
}

/**
 * @notice Seed data for an item or roe: identifies the item and drives deterministic SVG generation.
 * @dev Immutable per item_id: same (value, seed1, seed2) always yields the same SVG.
 */
struct SeedData {
    /// @dev Item level: 0 - roe, or item level 1-5
    uint8 lvl;
    /// @dev Item value (1/2/4/6/8) or roe amount in raw units (raw); for roe, value&gt;8 is raw, getItemData normalizes for lvl
    uint value;
    /// @dev First PRNG stream (e.g. RandLib.random_value)
    uint seed1;
    /// @dev Second PRNG stream (e.g. ExtraSeedLibrary.extra)
    uint seed2;
}

struct Rand {
    /// @dev Same as SeedData.value (item value 1/2/4/6/8 or dust); used in next()
    uint value;
    uint seed1;
    uint seed2;
    uint nonce;
    uint nonce2;
}

library RandLib {
    function next(Rand memory rnd) internal pure returns (uint) {
        return
            uint(
                keccak256(abi.encodePacked(rnd.value + rnd.nonce++, rnd.seed2))
            );
    }

    function next2(Rand memory rnd) internal pure returns (uint) {
        return uint(keccak256(abi.encodePacked(rnd.seed1 + rnd.nonce2++ - 1)));
    }

    function random_value(uint nonce) internal view returns (uint) {
        return
            uint256(
                keccak256(
                    abi.encodePacked(
                        block.timestamp,
                        msg.sender,
                        nonce,
                        block.number
                    )
                )
            );
    }

    function random(
        string[] memory data,
        Rand memory rnd
    ) internal pure returns (string memory) {
        return data[randomIndex(data, rnd)];
    }

    function random2(
        string[] memory data,
        Rand memory rnd
    ) internal pure returns (string memory) {
        return data[randomIndex2(data, rnd)];
    }

    function randomIndex(
        string[] memory data,
        Rand memory rnd
    ) internal pure returns (uint) {
        return next(rnd) % data.length;
    }

    function randomIndex2(
        string[] memory data,
        Rand memory rnd
    ) internal pure returns (uint) {
        return next2(rnd) % data.length;
    }
}

library ColorConvert {
    function toSvgColor(uint24 value) internal pure returns (string memory) {
        return string(abi.encodePacked("#", toHex(value)));
    }

    function toHex(uint24 value) internal pure returns (bytes memory) {
        bytes memory buffer = new bytes(6);
        for (uint i = 0; i < 3; ++i) {
            buffer[5 - i * 2] = hexChar(uint8(value) & 0x0f);
            buffer[4 - i * 2] = hexChar((uint8(value) >> 4) & 0x0f);
            value >>= 8;
        }
        return buffer;
    }

    function hexChar(uint8 value) internal pure returns (bytes1) {
        if (value < 10) return bytes1(uint8(48 + (uint(value) % 10)));
        return bytes1(uint8(65 + uint256((value - 10) % 6)));
    }
}

library LayersLib {
    function setLayers(
        mapping(uint => mapping(uint => Rect[])) storage rects,
        FileData[] calldata data,
        uint8[levelsCount] storage counts
    ) internal {
        for (uint i = 0; i < data.length; ++i) {
            setFile(rects, data[i], counts);
        }
    }

    function setLayers(
        mapping(uint => mapping(uint => RectColored[])) storage rects,
        FileDataColored[] calldata data,
        uint8[levelsCount] storage counts
    ) internal {
        for (uint i = 0; i < data.length; ++i) {
            setFile(rects, data[i], counts);
        }
    }

    function setFile(
        mapping(uint => mapping(uint => Rect[])) storage rects,
        FileData calldata input,
        uint8[levelsCount] storage counts
    ) internal {
        Rect[] storage storageFile = rects[input.lvl - 1][input.file - 1];
        if (storageFile.length > 0) delete rects[input.lvl - 1][input.file - 1];
        else ++counts[input.lvl - 1];
        for (uint i = 0; i < input.rects.length; ++i) {
            storageFile.push(input.rects[i]);
        }
    }

    function setFile(
        mapping(uint => mapping(uint => RectColored[])) storage rects,
        FileDataColored calldata input,
        uint8[levelsCount] storage counts
    ) internal {
        RectColored[] storage storageFile = rects[input.lvl - 1][
            input.file - 1
        ];
        if (storageFile.length > 0) delete rects[input.lvl - 1][input.file - 1];
        else ++counts[input.lvl - 1];
        for (uint i = 0; i < input.rects.length; ++i) {
            storageFile.push(input.rects[i]);
        }
    }

    function getLvl(
        mapping(uint => mapping(uint => Rect[])) storage rects,
        uint lvl
    ) internal view returns (mapping(uint => Rect[]) storage) {
        return rects[lvl];
    }

    function to_lvl_1(uint l) internal pure returns (uint) {
        if (l > 0) --l;
        return l;
    }
}

library Converter {
    function toString(uint value) internal pure returns (string memory) {
        if (value == 0) {
            return "0";
        }
        uint temp = value;
        uint 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);
    }
}

library RectLib {
    using RectLib for Rect;
    using RectLib for RectColored;
    using RandLib for Rand;
    using RandLib for string[];
    using Converter for uint8;
    using ColorConvert for uint24;

    function toSvg(
        Rect memory r,
        string memory color
    ) internal pure returns (string memory) {
        return
            string(
                abi.encodePacked(
                    "<rect x='",
                    r.x.toString(),
                    "' y='",
                    r.y.toString(),
                    "' width='",
                    r.width.toString(),
                    "' height='",
                    r.height.toString(),
                    "' fill='",
                    color,
                    "'/>"
                )
            );
    }

    function toSvg(RectColored memory r) internal pure returns (string memory) {
        return toSvg(Rect(r.x, r.y, r.width, r.height), r.color.toSvgColor());
    }

    function toSvg(
        Rect[] storage rects,
        string[] storage colors,
        Rand memory rnd
    ) internal view returns (string memory) {
        string memory res;
        for (uint i = 0; i < rects.length; ++i) {
            res = string(
                abi.encodePacked(res, rects[i].toSvg(colors.random(rnd)))
            );
        }
        return res;
    }

    function toSvg(
        Rect[] storage rects,
        string memory color
    ) internal view returns (string memory) {
        string memory res;
        for (uint i = 0; i < rects.length; ++i) {
            res = string(abi.encodePacked(res, rects[i].toSvg(color)));
        }
        return res;
    }

    function toSvg(
        RectColored[] storage rects
    ) internal view returns (string memory) {
        string memory res;
        for (uint i = 0; i < rects.length; ++i) {
            res = string(abi.encodePacked(res, rects[i].toSvg()));
        }
        return res;
    }
}

contract Generator is Ownable {
    using LayersLib for mapping(uint => mapping(uint => Rect[]));
    using LayersLib for mapping(uint => mapping(uint => RectColored[]));
    using LayersLib for mapping(uint => string[]);
    using LayersLib for uint;
    using RectLib for Rect;
    using RectLib for Rect[];
    using RectLib for RectColored;
    using RectLib for RectColored[];
    using RandLib for Rand;
    using RandLib for string[];
    using Converter for uint;
    using Converter for uint8;
    using ColorConvert for uint24;

    uint8[levelsCount] bodyLevelCounts;
    uint8[levelsCount] clothLevelCounts;
    uint8[levelsCount] eyesLevelCounts;
    uint8[levelsCount] mouthLevelCounts;
    uint8[levelsCount] accessoryLevelCounts;
    uint8[levelsCount] hatLevelCounts;
    uint8[levelsCount] earsLevelCounts;

    mapping(uint => mapping(uint => Rect[])) bodies;
    mapping(uint => mapping(uint => RectColored[])) cloths;
    mapping(uint => mapping(uint => RectColored[])) eyes;
    mapping(uint => mapping(uint => RectColored[])) mouths;
    mapping(uint => mapping(uint => RectColored[])) accessories;
    mapping(uint => mapping(uint => RectColored[])) hats;
    mapping(uint => mapping(uint => RectColored[])) ears;

    string[] private backgroundColors = [
        "#c37100",
        "#db4161",
        "#9aeb00",
        "#9241f3",
        "#5182ff",
        "#a2a2a2",
        "#fff392"
    ];

    // Dust (lvl 0): muted, greyish tones for "dust"
    string[] private dustBackgroundColors = [
        "#b0a090",
        "#9a8f82",
        "#c4b8a8",
        "#8c8478",
        "#a69b8f",
        "#d0c4b8",
        "#7a7268"
    ];

    string[] private skin_colors = [
        // Greens
        "#538234",
        "#49a269",
        "#67d487",
        "#4b9540",
        "#538234",
        "#49a269",
        "#67d487",
        "#4b9540",
        "#538234",
        "#49a269",
        "#67d487",
        "#4b9540",
        "#538234",
        "#49a269",
        "#67d487",
        "#4b9540",
        "#538234",
        "#49a269",
        "#67d487",
        "#4b9540",
        "#538234",
        "#49a269",
        "#67d487",
        "#4b9540",
        "#538234",
        "#49a269",
        "#67d487",
        "#4b9540",
        // Browns and Yellows
        "#794100",
        "#8a8a00",
        "#b6a41d",
        "#dcc724",
        // Blues
        "#4192c3",
        "#61a2ff",
        "#61d3e3",
        "#a271ff",
        // Reds, Oranges, and Pinks
        "#d44f06",
        "#cf458c",
        "#d4a37c",
        "#FFC0CB",
        "#800080",
        "#8F00FF"
    ];

    constructor() {}

    function setBodies(FileData[] calldata data) external onlyOwner {
        bodies.setLayers(data, bodyLevelCounts);
    }

    function setCloths(FileDataColored[] calldata data) external onlyOwner {
        cloths.setLayers(data, clothLevelCounts);
    }

    function setEyes(FileDataColored[] calldata data) external onlyOwner {
        eyes.setLayers(data, eyesLevelCounts);
    }

    function setMouths(FileDataColored[] calldata data) external onlyOwner {
        mouths.setLayers(data, mouthLevelCounts);
    }

    function setAccessories(
        FileDataColored[] calldata data
    ) external onlyOwner {
        accessories.setLayers(data, accessoryLevelCounts);
    }

    function setHats(FileDataColored[] calldata data) external onlyOwner {
        hats.setLayers(data, hatLevelCounts);
    }

    function setEars(FileDataColored[] calldata data) external onlyOwner {
        ears.setLayers(data, earsLevelCounts);
    }

    // DATA

    function getItemData(
        SeedData calldata seed_data
    ) external view virtual returns (ItemData memory) {
        return _buildItemDataFromSeed(seed_data);
    }

    function _buildItemDataFromSeed(
        SeedData memory seed_data
    ) internal view returns (ItemData memory) {
        Rand memory rnd = Rand(
            seed_data.value,
            seed_data.seed1,
            seed_data.seed2,
            0,
            0
        );
        ItemData memory data;
        data.lvl = seed_data.lvl;
        setBcGround(data, rnd);
        setBody(data, rnd);
        if (data.lvl > 0) {
            setCloth(data, rnd);
            setEyes(data, rnd);
            setMouth(data, rnd);
            setAccessory(data, rnd);
            setHat(data, rnd);
            setEars(data, rnd);
        }

        // limits
        if (data.lvl == 1) {
            if (data.mouth == 9) {
                if (data.accessory >= 7 && data.accessory <= 9)
                    data.accessory = 0;
            }
            if (data.eyes == 5) {
                if ((data.accessory >= 10 && data.accessory <= 13))
                    data.accessory = 0;
            }
        }
        if (data.lvl == 2) {
            if (data.hat >= 25 && data.hat <= 28) data.ears = 0;
        }
        if (data.lvl == 3) {
            if (data.mouth == 9) {
                if (data.accessory == 1 || data.accessory == 2)
                    data.accessory = 0;
            }
            if (data.eyes == 5) {
                if (
                    data.accessory == 3 ||
                    data.accessory == 6 ||
                    (data.accessory >= 15 && data.accessory <= 20)
                ) data.accessory = 0;
            }
            if (data.hat >= 44 && data.hat <= 47) data.ears = 0;
        }
        if (data.lvl == 4) {
            if (data.eyes == 5) {
                if (
                    data.accessory == 1 ||
                    data.accessory == 5 ||
                    (data.accessory >= 8 && data.accessory <= 13) ||
                    (data.accessory >= 14 && data.accessory <= 19) ||
                    (data.accessory >= 20 && data.accessory <= 25)
                ) data.accessory = 0;
            }
            if (data.accessory == 5) {
                if (
                    data.eyes == 5 ||
                    data.accessory == 9 ||
                    data.accessory == 10
                ) data.eyes = 0;
            }
            if (data.hat >= 54 && data.hat <= 57) data.ears = 0;
        }
        if (data.lvl == 5) {
            if (data.mouth == 9) {
                if (
                    data.accessory == 44 ||
                    (data.accessory >= 20 && data.accessory <= 25)
                ) data.accessory = 0;
            }
            if (data.eyes == 5) {
                if (
                    (data.accessory >= 8 && data.accessory <= 13) ||
                    (data.accessory >= 14 && data.accessory <= 19) ||
                    (data.accessory >= 26 && data.accessory <= 31) ||
                    (data.accessory >= 32 && data.accessory <= 37)
                ) data.accessory = 0;
            }
            if (data.hat == 49) {
                if (
                    data.accessory == 2 ||
                    data.accessory == 5 ||
                    data.accessory == 6 ||
                    data.accessory == 44 ||
                    (data.accessory >= 20 && data.accessory <= 25) ||
                    (data.accessory >= 38 && data.accessory <= 43)
                ) data.accessory = 0;
            }
            if (data.hat >= 70 && data.hat <= 73) data.ears = 0;
        }
        if (data.lvl == 6) {
            if (data.mouth == 6) {
                if (
                    (data.accessory >= 63 && data.accessory <= 65) ||
                    (data.accessory >= 69 && data.accessory <= 71)
                ) data.accessory = 0;
            }
            if (data.mouth == 9) {
                if (
                    data.accessory == 3 ||
                    data.accessory == 48 ||
                    data.accessory == 55 ||
                    (data.accessory >= 30 && data.accessory <= 35) ||
                    (data.accessory >= 36 && data.accessory <= 41) ||
                    (data.accessory >= 49 && data.accessory <= 54) ||
                    (data.accessory >= 57 && data.accessory <= 59) ||
                    (data.accessory >= 63 && data.accessory <= 65) ||
                    (data.accessory >= 69 && data.accessory <= 71) ||
                    (data.accessory >= 75 && data.accessory <= 77)
                ) data.accessory = 0;
            }
            if (data.mouth == 10) {
                if (
                    (data.accessory >= 69 && data.accessory <= 71) ||
                    (data.accessory >= 75 && data.accessory <= 77)
                ) data.accessory = 0;
            }
            if (data.eyes == 5) {
                if (
                    data.accessory == 17 ||
                    (data.accessory >= 5 && data.accessory <= 10) ||
                    (data.accessory >= 11 && data.accessory <= 16) ||
                    (data.accessory >= 18 && data.accessory <= 23) ||
                    (data.accessory >= 42 && data.accessory <= 47) ||
                    (data.accessory >= 72 && data.accessory <= 74) ||
                    (data.accessory >= 69 && data.accessory <= 71) ||
                    (data.accessory >= 63 && data.accessory <= 65)
                ) data.accessory = 0;
            }
            if (data.hat == 50) {
                if (
                    data.accessory == 2 ||
                    data.accessory == 17 ||
                    data.accessory == 48 ||
                    data.accessory == 55 ||
                    (data.accessory >= 24 && data.accessory <= 29) ||
                    (data.accessory >= 30 && data.accessory <= 35) ||
                    (data.accessory >= 36 && data.accessory <= 41)
                ) data.accessory = 0;
            }
            if (data.hat >= 72 && data.hat <= 72) data.ears = 0;
        }
        if (data.eyes == 12) {
            if (data.lvl == 2) {
                if (data.accessory >= 10 && data.accessory <= 13)
                    data.accessory = 0;
            }
            if (data.lvl == 3) {
                if (
                    data.accessory >= 6 ||
                    (data.accessory >= 15 && data.accessory <= 20)
                ) data.accessory = 0;
            }
            if (data.lvl == 4) {
                if (
                    data.accessory >= 5 ||
                    (data.accessory >= 8 && data.accessory <= 19)
                ) data.accessory = 0;
            }
            if (data.lvl == 5) {
                if (
                    (data.accessory >= 26 && data.accessory <= 31) ||
                    (data.accessory >= 14 && data.accessory <= 19)
                ) data.accessory = 0;
            }
            if (data.lvl == 6) {
                if (
                    (data.accessory >= 11 && data.accessory <= 23) ||
                    (data.accessory >= 42 && data.accessory <= 47)
                ) data.accessory = 0;
            }
        }

        return data;
    }

    function setBcGround(ItemData memory data, Rand memory rnd) private view {
        if (data.lvl == 0) {
            data.background = dustBackgroundColors.random2(rnd);
        } else {
            data.background = backgroundColors.random2(rnd);
        }
    }

    function _randomPartIndex(
        uint count,
        Rand memory rnd
    ) private pure returns (uint) {
        if (count == 0) return 0;
        return 1 + (rnd.next() % count);
    }

    function _randomPartIndexWithProb(
        uint count,
        uint probPct,
        Rand memory rnd
    ) private pure returns (uint) {
        if (count == 0) return 0;
        if (!(rnd.next() % 100 < probPct)) return 0;
        return 1 + (rnd.next() % count);
    }

    function setBody(ItemData memory data, Rand memory rnd) private view {
        uint count = bodyLevelCounts[data.lvl];
        if (count == 0) return;
        data.body = 1 + (rnd.next() % count);
        data.bodyColor = skin_colors.random2(rnd);
    }

    function setCloth(ItemData memory data, Rand memory rnd) private view {
        data.cloth = _randomPartIndexWithProb(
            clothLevelCounts[data.lvl],
            60,
            rnd
        );
    }

    function setEyes(ItemData memory data, Rand memory rnd) private view {
        data.eyes = _randomPartIndex(eyesLevelCounts[data.lvl], rnd);
    }

    function setMouth(ItemData memory data, Rand memory rnd) private view {
        data.mouth = _randomPartIndex(mouthLevelCounts[data.lvl], rnd);
    }

    function setAccessory(ItemData memory data, Rand memory rnd) private view {
        data.accessory = _randomPartIndexWithProb(
            accessoryLevelCounts[data.lvl],
            37,
            rnd
        );
    }

    function setHat(ItemData memory data, Rand memory rnd) private view {
        data.hat = _randomPartIndexWithProb(hatLevelCounts[data.lvl], 37, rnd);
    }

    function setEars(ItemData memory data, Rand memory rnd) private view {
        data.ears = _randomPartIndexWithProb(earsLevelCounts[data.lvl], 3, rnd);
    }

    // META

    function _metaNum(
        string memory key,
        uint value
    ) private pure returns (bytes memory) {
        return abi.encodePacked(',"', key, '":', value.toString());
    }

    function _metaStr(
        string memory key,
        string memory value
    ) private pure returns (bytes memory) {
        return abi.encodePacked(',"', key, '":"', value, '"');
    }

    function getMeta(
        SeedData calldata seed_data
    ) external view returns (string memory) {
        ItemData memory data = this.getItemData(seed_data);
        bytes memory lvl = abi.encodePacked('"level":', data.lvl.toString());

        return
            string(
                abi.encodePacked(
                    "{",
                    lvl,
                    _metaStr("background", data.background),
                    _metaStr("bodyColor", data.bodyColor),
                    _metaNum("clothes", data.cloth),
                    _metaNum("eyes", data.eyes),
                    _metaNum("mouth", data.mouth),
                    _metaNum("accessory", data.accessory),
                    _metaNum("Head Item", data.hat),
                    _metaNum("ears", data.ears),
                    _metaStr("web", web),
                    _metaStr("description", description),
                    "}"
                )
            );
    }

    // SVG

    function getSvg(
        SeedData calldata seed_data
    ) external view returns (string memory) {
        return toSvg(this.getItemData(seed_data));
    }

    function toSvg(ItemData memory data) private view returns (string memory) {
        bytes memory svgStart = abi.encodePacked(
            "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0",
            " ",
            pixelsCount.toString(),
            " ",
            pixelsCount.toString(),
            "'>"
        );
        /*if (data.lvl == 0) {
            return
                string(
                    abi.encodePacked(
                        svgStart,
                        backgroundSvg(data),
                        bodySvg(data),
                        "</svg>"
                    )
                );
        }*/
        return
            string(
                abi.encodePacked(
                    svgStart,
                    backgroundSvg(data),
                    bodySvg(data),
                    clothSvg(data),
                    earsSvg(data),
                    mouthSvg(data),
                    eyesSvg(data),
                    accessorySvg(data),
                    hatSvg(data),
                    "</svg>"
                )
            );
    }

    function backgroundSvg(
        ItemData memory data
    ) private pure returns (string memory) {
        Rect memory r = Rect(0, 0, pixelsCount, pixelsCount);
        return r.toSvg(data.background);
    }

    function _rectColoredPartSvg(
        RectColored[] storage rects,
        uint index
    ) private view returns (string memory) {
        if (index == 0) return "";
        return rects.toSvg();
    }

    function bodySvg(
        ItemData memory data
    ) private view returns (string memory) {
        if (data.body == 0) return "";
        return bodies[data.lvl][data.body - 1].toSvg(data.bodyColor);
    }

    function clothSvg(
        ItemData memory data
    ) private view returns (string memory) {
        if (data.cloth == 0) return "";
        return
            _rectColoredPartSvg(cloths[data.lvl][data.cloth - 1], data.cloth);
    }

    function eyesSvg(
        ItemData memory data
    ) private view returns (string memory) {
        if (data.eyes == 0) return "";
        return _rectColoredPartSvg(eyes[data.lvl][data.eyes - 1], data.eyes);
    }

    function mouthSvg(
        ItemData memory data
    ) private view returns (string memory) {
        if (data.mouth == 0) return "";
        return
            _rectColoredPartSvg(mouths[data.lvl][data.mouth - 1], data.mouth);
    }

    function accessorySvg(
        ItemData memory data
    ) private view returns (string memory) {
        if (data.accessory == 0) return "";
        return
            _rectColoredPartSvg(
                accessories[data.lvl][data.accessory - 1],
                data.accessory
            );
    }

    function hatSvg(ItemData memory data) private view returns (string memory) {
        if (data.hat == 0) return "";
        return _rectColoredPartSvg(hats[data.lvl][data.hat - 1], data.hat);
    }

    function earsSvg(
        ItemData memory data
    ) private view returns (string memory) {
        if (data.ears == 0) return "";
        return _rectColoredPartSvg(ears[data.lvl][data.ears - 1], data.ears);
    }
}

project/contracts/lib/Ownable.sol

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

contract Ownable {
    address _owner;

    error OnlyOwner();

    event RenounceOwnership();

    constructor() {
        _owner = msg.sender;
    }

    modifier onlyOwner() {
        if (_owner != msg.sender) revert OnlyOwner();
        _;
    }

    function owner() external view virtual returns (address) {
        return _owner;
    }

    function ownerRenounce() public onlyOwner {
        _owner = address(0);
        emit RenounceOwnership();
    }

    function transferOwnership(address newOwner) external onlyOwner {
        _owner = newOwner;
    }
}

project/contracts/test/TestTokenWraper.sol

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

import "../token/Pepi.sol";

contract TestTokenWraper is Pepi {
    function mint(uint256 count) external {
        _mint(msg.sender, count);
    }

    function mintTo(address account, uint256 count) external {
        _mint(account, count);
    }
}

project/contracts/token/Erc20.sol

pragma solidity ^0.8.20;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/utils/Context.sol";

contract ERC20 is Context, IERC20, IERC20Metadata {
    mapping(address => uint256) internal _balances;

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 internal _totalSupply;
    uint8 internal constant _decimals = 9;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public pure returns (uint8) {
        return _decimals;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(
        address account
    ) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(
        address to,
        uint256 amount
    ) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(
        address owner,
        address spender
    ) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(
        address spender,
        uint256 amount
    ) public virtual override returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(
        address spender,
        uint256 addedValue
    ) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, allowance(owner, spender) + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(
        address spender,
        uint256 subtractedValue
    ) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = allowance(owner, spender);
        require(
            currentAllowance >= subtractedValue,
            "ERC20: decreased allowance below zero"
        );
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");

        uint256 fromBalance = _balances[from];
        require(
            fromBalance >= amount,
            "ERC20: transfer amount exceeds balance"
        );
        unchecked {
            _balances[from] = fromBalance - amount;
            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
            // decrementing then incrementing.
            _balances[to] += amount;
        }

        emit Transfer(from, to, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _totalSupply += amount;
        unchecked {
            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
            _balances[account] += amount;
        }
        emit Transfer(address(0), account, amount);
    }

    /**
     * @dev Erases `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
            // Overflow not possible: amount <= accountBalance <= totalSupply.
            _totalSupply -= amount;
        }

        emit Transfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
     *
     * Does not update the allowance amount in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Might emit an {Approval} event.
     */
    function _spendAllowance(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(
                currentAllowance >= amount,
                "ERC20: insufficient allowance"
            );
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }
}

project/contracts/token/IHasItemsWithRoe.sol

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

import "../Generator.sol";

/**
 * @title IHasItemsWithRoe
 * @notice Public interface for the ERC-20i extension: items (with unique IDs and value),
 *         roe (remainder of balance not backing items), and item sources (addresses
 *         from which incoming transfers mint new items).
 * @dev Implementations maintain the invariant: balance >= sum(item values) per account;
 *      roe = balance (in whole units) - sum(item values). Items are minted only when
 *      tokens are received from an item source (e.g. pool, airdrop).
 *      On ERC20 transfer when sender has insufficient roe: if transfer amount (whole units)
 *      equals a constant item value and sender has such item, one item is taken from the end
 *      of the corresponding value bucket and transferred (or burned if recipient is a source).
 *      Otherwise items are taken from the end of the owner's index list; if the last item's
 *      value exceeds the amount still needed, that item is burned and the remainder becomes roe.
 */
interface IHasItemsWithRoe {
    // -------------------------------------------------------------------------
    // Events
    // -------------------------------------------------------------------------

    /// @notice Emitted when an item is transferred from one owner to another (by value or by item_id).
    /// @param from Previous owner address
    /// @param to New owner address
    /// @param item_id Unique item identifier (unchanged across transfers)
    /// @param seed_data Item data (value, seed1, seed2) used for SVG generation; invariant per item_id
    event OnItemTransfer(
        address indexed from,
        address indexed to,
        uint indexed item_id,
        SeedData seed_data
    );

    /// @notice Emitted when a new item is minted to an account (incoming transfer from an item source).
    /// @param owner Account that received the tokens and the new item
    /// @param item_id New unique item identifier
    /// @param value Token value backing the item (1, 2, 4, 6, or 8 whole units)
    /// @param seed_data Full seed data for the new item
    event OnItemMint(
        address indexed owner,
        uint indexed item_id,
        uint value,
        SeedData seed_data
    );

    /// @notice Emitted when an item is burned (sent to an item source, invariant burn, source sanitization, or partial roe).
    /// @param owner Account that lost the item
    /// @param item_id Item identifier that was burned
    /// @param value Token value that was backing the item
    /// @param reason 1 = transfer to source, 2 = invariant, 3 = source sanitize, 4 = partial roe (item destroyed to free value for transfer; remainder becomes roe)
    event OnItemBurn(
        address indexed owner,
        uint indexed item_id,
        uint value,
        uint8 reason
    );

    /// @notice Emitted when roe (remainder) on an account increases (e.g. after receiving tokens without a matching item transfer).
    /// @param holder Account whose roe increased
    /// @param roe_data New roe seed data (value = roe amount in raw units, seed1, seed2 for display)
    event OnRoeGrow(address indexed holder, SeedData roe_data);

    /// @notice Emitted when roe on an account decreases (e.g. after sending tokens or losing balance).
    /// @param holder Account whose roe decreased
    /// @param roe_data New roe seed data
    event OnRoeShrink(address indexed holder, SeedData roe_data);

    // -------------------------------------------------------------------------
    // Item sources and token unit
    // -------------------------------------------------------------------------

    /// @notice Returns the smallest token unit (10^decimals). Used to convert between raw balance and whole units.
    /// @return Amount of wei per one whole token
    function tokenUnit() external pure returns (uint256);

    /// @notice Returns whether the given address is an item source. Transfers *from* an item source mint new items to the recipient.
    /// @param addr Address to check (e.g. pool, airdrop)
    /// @return true if tokens received from this address cause item/roe minting
    function isItemSource(address addr) external view returns (bool);

    /// @notice Alias for isItemSource (legacy naming: "seed source").
    /// @param addr Address to check
    /// @return Same as isItemSource(addr)
    function isSeedSource(address addr) external view returns (bool);

    // -------------------------------------------------------------------------
    // Item transfer by ID
    // -------------------------------------------------------------------------

    /// @notice Transfers a specific item by its ID from msg.sender to the given address. Moves (item value) tokens and the item together.
    /// @param to Recipient address. If this is an item source, the item is burned and only tokens are credited.
    /// @param itemId Unique item ID that msg.sender must own
    /// @return true if the transfer (or burn) was performed
    function transferItem(address to, uint itemId) external returns (bool);

    /// @notice Same as transferItem (snake_case alias for compatibility).
    /// @param to Recipient address
    /// @param itemId Item ID to transfer
    /// @return true if the transfer was performed
    function transfer_item(address to, uint itemId) external returns (bool);

    // -------------------------------------------------------------------------
    // Ownership and item data by owner/index
    // -------------------------------------------------------------------------

    /// @notice Returns whether the given account owns the given item ID.
    /// @param owner Account address
    /// @param item_id Item ID
    /// @return true if owner currently owns the item
    function isOwnerOf(address owner, uint item_id) external view returns (bool);

    /// @notice Returns roe (remainder) data for the account: value = roe amount in raw units (as balanceOf), seed1 and seed2 for generator.
    /// @param owner Account address
    /// @return roe_data Struct { value, seed1, seed2 }
    function roeDegree(address owner) external view returns (SeedData memory roe_data);

    /// @notice Alias for roeDegree (legacy: "spores").
    /// @param owner Account address
    /// @return roe_data Same as roeDegree(owner)
    function sporesDegree(address owner) external view returns (SeedData memory roe_data);

    /// @notice Returns the number of items owned by the account.
    /// @param owner Account address
    /// @return Number of items (each with a unique item_id and value 1, 2, 4, 6, or 8)
    function itemCount(address owner) external view returns (uint);

    /// @notice Alias for itemCount (legacy: "mushroom" count).
    /// @param owner Account address
    /// @return Same as itemCount(owner)
    function mushroomCount(address owner) external view returns (uint);

    // -------------------------------------------------------------------------
    // Global counts
    // -------------------------------------------------------------------------

    /// @notice Total number of items that exist (across all accounts). Decreases when items are burned.
    /// @return Total item count
    function itemsTotalCount() external view returns (uint);

    /// @notice Alias for itemsTotalCount (legacy).
    /// @return Same as itemsTotalCount()
    function mushroomsTotalCount() external view returns (uint);

    /// @notice Number of accounts that currently have at least one item or non-zero roe (holders list length).
    /// @return Number of holder addresses tracked
    function holdersCount() external view returns (uint);

    /// @notice Number of accounts that currently have non-zero roe.
    /// @return Count of accounts with roe > 0
    function roeTotalCount() external view returns (uint);

    /// @notice Alias for roeTotalCount (legacy: "spores").
    /// @return Same as roeTotalCount()
    function sporesTotalCount() external view returns (uint);

    // -------------------------------------------------------------------------
    // Holders list enumeration
    // -------------------------------------------------------------------------

    /// @notice Returns the index of the account in the holders list. Revert or invalid value if not a holder.
    /// @param account Address to look up
    /// @return Index in the list (0 .. holdersCount()-1)
    function getHolderIndex(address account) external view returns (uint);

    /// @notice Returns paginated holders list.
    /// @dev Result length can be smaller than `count` near the end. Returns total count for pagination.
    /// @param startIndex Zero-based start index in holders list.
    /// @param count Requested page size.
    /// @return holders Page of holder addresses.
    /// @return total Total holders count at call time.
    function getHoldersPage(
        uint startIndex,
        uint count
    ) external view returns (address[] memory holders, uint total);

    /// @notice Returns paginated items for a holder (item IDs and seed data).
    /// @dev Result length can be smaller than `count` near the end.
    /// @param owner Holder address.
    /// @param startIndex Zero-based start index in owner's items.
    /// @param count Requested page size.
    /// @return itemIds Item IDs page.
    /// @return items Item seed data page (value, seed1, seed2).
    /// @return total Total items count for owner at call time.
    function getOwnerItemsPage(
        address owner,
        uint startIndex,
        uint count
    )
        external
        view
        returns (uint[] memory itemIds, SeedData[] memory items, uint total);

    // -------------------------------------------------------------------------
    // Items by value (value buckets) and reorder
    // -------------------------------------------------------------------------

    /// @notice Returns item IDs for the owner that have the given value (constant: 1, 2, 4, 6, or 8), with pagination.
    /// @dev Use to enumerate items in a value bucket. Order in the bucket determines which item is sent first when transferring that exact amount (last in array = first sent).
    /// @param owner Account address
    /// @param value One of the constant item values (1, 2, 4, 6, 8)
    /// @param offset Zero-based start index in the bucket
    /// @param limit Max number of item IDs to return
    /// @return itemIds Slice of item IDs with the given value
    /// @return total Total number of items with this value for the owner (0 if value is not a constant)
    function itemIdsByValue(
        address owner,
        uint value,
        uint offset,
        uint limit
    ) external view returns (uint[] memory itemIds, uint total);

    /// @notice Swaps positions of two items in the same value bucket for msg.sender. Affects which item is sent first when transferring that exact value (last in bucket is sent first).
    /// @param value Constant item value (1, 2, 4, 6, or 8); both items must have this value
    /// @param itemIdA First item ID (must be owned by msg.sender with the given value)
    /// @param itemIdB Second item ID (must be owned by msg.sender with the given value)
    function reorderItemsByValue(
        uint value,
        uint itemIdA,
        uint itemIdB
    ) external;
}

project/contracts/token/PoolCreatableErc20i.sol

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

import "./Erc20.sol";

abstract contract PoolCreatableErc20i is ERC20 {
    address internal _pool;
    uint256 internal _startTime;
    bool internal _feeLocked;
    address immutable _pairCreator;

    constructor(
        string memory name_,
        string memory symbol_,
        address pairCreator
    ) ERC20(name_, symbol_) {
        _pairCreator = pairCreator;
    }

    modifier lockFee() {
        _feeLocked = true;
        _;
        _feeLocked = false;
    }

    function launch(address poolAddress) external payable {
        require(msg.sender == _pairCreator);
        require(!isStarted());
        _pool = poolAddress;
        _startTime = block.timestamp;
    }

    function isPool(address poolAddress) internal view returns (bool) {
        return _pool == poolAddress;
    }

    function isStarted() internal view returns (bool) {
        return _pool != address(0);
    }

    function pool() external view returns (address) {
        return _pool;
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "optimizer": {
    "runs": 1,
    "enabled": true
  },
  "evmVersion": "osaka",
  "remappings": [
    "project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/",
    "project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/",
    "project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.