Skip to content
Verified contractPartialMIT

ProductToken

Address0x375ad110e028a45c426e844a74eb3893e2c80cb7
Balance

0 ETH

 

Transactions

2

 

Compiler

solc 0.8.26

 

Same code

1 more contract

 

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
26,323,071
Creation transaction
0xb084fac927…51545fb73e

src/ProductToken.sol

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

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {AllowlistRegistry} from "./AllowlistRegistry.sol";

/// @dev The one Safe view the token relies on: any Safe owner may pause alone.
interface ISafeOwners {
    function isOwner(address owner) external view returns (bool);
}

/// @dev What the token asks the series directory: which escrow serves this token now, and where stray
///      tokens go.
interface IDirectory {
    function escrowOf(address token) external view returns (address);
    function quarantine() external view returns (address);
}

/// @notice One issue of units to a holder: how many of it are left, when it was issued and on what terms.
///         The terms travel with the units — a transfer moves lots, a redemption consumes them oldest
///         first — so a change of the terms by governance never reaches a unit already issued.
struct Lot {
    uint128 units;
    uint64 issuedAt;
    uint16 lockDays;
    uint16 penaltyBps;
    /// @dev The fee ledger's cohort the units were issued into: their basis for the performance fee travels
    ///      with them under this number, whatever the second they were issued in (review of 28.09.2026, M-22).
    ///      Zero is the floor; `MIGRATED_COHORT` marks units a reissue carried over from a replaced token,
    ///      which the ledger keeps apart until governance seeds them (L-15).
    uint32 cohort;
}

/// @title ProductToken (xCUP) — the tracker certificate
/// @notice An ERC-20 whose every transfer is checked against the AllowlistRegistry. Units are
///         minted only by the series' escrow, in the transaction that allocates the money they are
///         issued against, within a per-call cap (one mint) and a 24-hour cap; and burned only from the
///         operations Safe's own balance after redemption. Nobody — not the operations Safe, not
///         governance — can mint a unit no money stands behind. The one exception is a migration: while
///         the token has never issued anything, governance may reissue, through the timelock, what a
///         replaced token's holders held — in as many calls as it takes, each continuing where the last
///         stopped, and closed by `finishReissue`, which states the totals and names the replaced token:
///         paused, with exactly the units reissued as its supply (audit of 13.10.2026, E-1); until then the
///         escrow cannot issue, and after it nothing is ever reissued again (review of 03.10.2026, B-04).
///         No price, no oracle, no owner, no upgrade, no funds. Pausing is easy (one Safe owner
///         or the sentinel); resuming is hard (governance through the timelock).
/// @notice Lock-up (owner, 25.09.2026): units cannot be redeemed for `lockDays` after they were issued
///         unless the holder accepts an early-exit penalty of `penaltyBps` of the gross, which stays in
///         the series for the holders who remain. Both are set by governance through the timelock, within
///         the bounds below, and apply to units issued from then on: every issue is a lot that keeps the
///         terms of its day. The queue reads the lots; the token only keeps them.
/// @dev What the token tells the fee ledger: every issue, every burn, and what a reissue carried over.
interface IFeeLedger {
    function noteIssued(uint256 units, uint256 priceMicro) external returns (uint32 cohort);
    function noteBurned(Lot[] calldata lots) external;
    function noteMigrated(uint256[] calldata units, uint256[] calldata basis) external returns (uint32[] memory);
}

/// @notice One lot of a migration: who held it on the replaced token, how many units, when they were first
///         issued, the lock-up terms they carried, and the basis they stood at for the performance fee there
///         (zero for units at that token's mark).
struct Carry {
    address to;
    uint128 units;
    uint64 issuedAt;
    uint16 lockDays;
    uint16 penaltyBps;
    uint128 basisMicro;
}

/// @dev What a migration asks of the token it carries over: that it is paused, and how many units it has.
interface IReplacedToken {
    function paused() external view returns (bool);
    function totalSupply() external view returns (uint256);
}

contract ProductToken is ERC20 {
    using SafeERC20 for IERC20;

    AllowlistRegistry public immutable registry;
    /// @notice The Operations Safe.
    address public immutable ops;
    /// @notice Governance (the Governance Safe behind the 48 h timelock).
    address public immutable governance;

    /// @notice The series directory: it names this token's escrow and the quarantine.
    IDirectory public immutable directory;

    /// @notice The series' escrow — the only minter — is whichever escrow the directory names for this
    ///         token. Governance may move it through the timelock, so a blacklisted or compromised escrow
    ///         can be replaced without touching the token.
    function minter() public view returns (address) {
        return directory.escrowOf(address(this));
    }
    /// @notice The series as the attestation anchor names it: keccak256 of the series name.
    bytes32 public immutable series;
    /// @notice A migration's state: 0 none, 1 begun and not finished (the escrow cannot issue), 2 finished.
    uint8 public reissueState;
    /// @notice How many lots, and how many units, the reissue has carried over so far.
    uint256 public reissuedCount;
    uint256 public reissuedUnits;
    /// @notice The token the migration carried over, named when it was closed: paused, with exactly the units
    ///         reissued here as its supply. Zero until `finishReissue`; zero for ever on a token that never
    ///         migrated. A reissue is bound to its source on chain, so a migration is the one way units come
    ///         into being without money, and only as many as a paused token already had (audit of 13.10.2026, E-1).
    address public reissuedSource;
    /// @notice Set by the first ordinary issue: from then on nothing can be reissued.
    bool public everIssued;

    /// @notice The one key that may live on a server. It can only pause.
    address public sentinel;
    bool public paused;

    uint256 public mintCapPerTx;
    uint256 public mintCapPerWindow;
    /// @dev The 24-hour cap is an allowance that refills evenly over `WINDOW`: what has been issued counts
    ///      against it and wears off at `mintCapPerWindow` per 24 hours. A fixed window let two caps through
    ///      in two seconds at its edge (review of 03.10.2026, B-06); here no moment allows more than one cap,
    ///      and the next cap takes a day to come back.
    uint256 private _minted;
    uint64 private _mintedAt;
    uint64 public constant WINDOW = 24 hours;

    bool private _forced;

    /// @notice Lock-up terms for units issued from now on, in days and in basis points of the gross.
    uint16 public lockDays;
    uint16 public penaltyBps;
    uint16 public constant MAX_LOCK_DAYS = 365;
    uint16 public constant MAX_PENALTY_BPS = 1000;
    /// @dev Lots per holder, in no particular order: what is consumed is always the oldest by `issuedAt`.
    ///      The redemption sink keeps none — the queue takes a request's lots before it pulls the units and
    ///      gives them back before it returns them — and neither does the operations Safe for what it burns.
    /// @dev A holder's lots, oldest first from `_head[holder]`; what lies before the head is spent. Kept sorted on
    ///      every push, so taking the oldest is a read at the head and never a scan (review of 27.09.2026, M-01).
    /// @dev Lots by holder and generation. A generation is one storage array; when a holder's list is emptied or
    ///      rewritten the generation moves on and the old array is simply left behind, never walked or zeroed:
    ///      clearing costs one write whatever the history. Spent lots before the head are zeroed one by one as
    ///      they are consumed, so no path is ever linear in how many lots a holder has had (review of 28.09.2026,
    ///      M-10: `delete` of the whole array walked every spent slot, and a holder with a long history could no
    ///      longer redeem in full, cancel or receive under the per-transaction gas cap).
    mapping(address => mapping(uint256 => Lot[])) private _lotsByGen;
    mapping(address => uint256) private _gen;
    mapping(address => uint256) private _head;
    /// @notice Lots a holder has in open redemption requests: they count towards `MAX_LOTS` with the ones he
    ///         holds, so a cancel can never bring him past the limit (review of 27.09.2026, E-03).
    mapping(address => uint256) public reservedLots;
    /// @dev The most lots a holder may hold. With the list sorted, every operation is linear in this number and
    ///      stays under the per-transaction gas cap of EIP-7825 (16 777 216) with room: a request, its cancel,
    ///      its settlement, a transfer. Identical lots merge, so only distinct days or terms count; a holder at
    ///      the limit redeems before he can be issued to or receive more (review of 27.09.2026, N-04). It was
    ///      400 until the review of 03.10.2026 measured a settlement of 400 lots, each closing a cohort of its
    ///      own, at 16.0 M — under the cap by less than the Safe's own overhead (B-19); at 300 it leaves a third.
    uint16 public constant MAX_LOTS = 300;
    /// @notice A transfer between holders may not take the recipient past this many lots, and what it opens
    ///         at the recipient costs units: a transfer under `MIN_NEW_LOT` opens no new lot there, a larger
    ///         one at most one per `MIN_NEW_LOT` moved and one more. A holder cannot fill another's list with
    ///         dust and shut him out of his own issues (review of 02.10.2026, A-04), and a holder whose
    ///         oldest lot is a fraction can still move his units (audit of 05.10.2026, P-01).
    uint16 public constant TRANSFER_MAX_LOTS = 250;
    uint128 public constant MIN_NEW_LOT = 1e6;
    /// @notice The cohort number of units a reissue carried over: never one the ledger gives.
    uint32 public constant MIGRATED_COHORT = type(uint32).max;
    /// @notice The fee ledger every burn is reported to (M-19). Set once.
    address public feeLedger;
    address private immutable _deployer;
    uint64 private immutable _deployerUntil;
    /// @dev The fee cohort and the lock-up terms of the units being minted, set around the mint.
    uint32 private _mintCohort;
    uint16 private _mintLock;
    uint16 private _mintPenalty;
    /// @dev Set by `reissue` around each mint, so carried-over units keep the day they were first issued.
    uint64 private _reissueAt;

    event Minted(address indexed to, uint256 amount, bytes32 indexed batchId);
    event FeeLedgerSet(address ledger);
    event LockupSet(uint16 lockDays, uint16 penaltyBps);
    event Reissued(address indexed to, uint256 amount, bytes32 indexed ref);
    /// @notice The migration is closed: this many lots and units, carried over from `source` (E-1).
    event ReissueFinished(uint256 lots, uint256 units, address indexed source);
    event Burned(uint256 amount, bytes32 indexed batchId);
    event Paused(address indexed by);
    event Unpaused();
    event ForcedTransfer(address indexed from, address indexed to, uint256 amount, bytes32 indexed legalRef);
    event CapsSet(uint256 perTx, uint256 perWindow);
    event SentinelSet(address indexed sentinel);
    /// @notice A token that reached this contract's address by mistake, moved to quarantine.
    event Rescued(address indexed token, uint256 amount, address indexed to, address indexed by);

    error NotOps();
    error NotMinter();
    error NotGovernance();
    error NotPauser();
    error AlreadyIssued();
    error LengthMismatch();
    error IsPaused();
    error NotAllowedRecipient(address to);
    error TransferNotAllowed(address from, address to);
    error CapPerTxExceeded(uint256 amount, uint256 cap);
    error CapPerWindowExceeded(uint256 amount, uint256 remaining);
    error ZeroAddress();
    error ZeroAmount();
    error LedgerSet();
    error NoLedger();
    error LotsMismatch(uint256 amount, uint256 lots);
    error SendToSinkOnlyByRequest(address sink);
    error LockupTooLong(uint16 lockDays);
    error PenaltyTooHigh(uint16 penaltyBps);
    error NotSink();
    error IssuedInFuture(uint64 issuedAt);
    error TooLarge();
    error SinkNotForceable();
    error TooManyLots(address holder);
    error NoQuarantine();
    error NothingToRescue();
    error OwnUnits();
    error ReissueOpen();
    error ReissueOffset(uint256 offset, uint256 expected);
    error ReissueTotals(uint256 lots, uint256 units);
    error NotAHolder(address to);
    error DustLot(address holder);
    error ReissueSource(address source);
    error SourceNotPaused(address source);
    error SourceSupply(uint256 units, uint256 sourceSupply);

    modifier onlyOps() {
        if (msg.sender != ops) revert NotOps();
        _;
    }

    modifier onlyGovernance() {
        if (msg.sender != governance) revert NotGovernance();
        _;
    }

    modifier whenNotPaused() {
        if (paused) revert IsPaused();
        _;
    }

    constructor(
        string memory name_,
        string memory symbol_,
        AllowlistRegistry registry_,
        IDirectory directory_,
        address ops_,
        address governance_,
        address sentinel_,
        uint256 mintCapPerTx_,
        uint256 mintCapPerWindow_,
        bytes32 series_
    ) ERC20(name_, symbol_) {
        _deployer = msg.sender;
        _deployerUntil = uint64(block.timestamp + 1 days);
        if (address(registry_) == address(0) || ops_ == address(0) || governance_ == address(0)) revert ZeroAddress();
        if (series_ == bytes32(0) || address(directory_) == address(0)) revert ZeroAddress();
        registry = registry_;
        directory = directory_;
        ops = ops_;
        governance = governance_;
        series = series_;
        sentinel = sentinel_;
        mintCapPerTx = mintCapPerTx_;
        mintCapPerWindow = mintCapPerWindow_;
        emit CapsSet(mintCapPerTx_, mintCapPerWindow_);
        emit SentinelSet(sentinel_);
        // no lock-up until governance sets one (owner, 30.09.2026): the terms start at nought
        emit LockupSet(0, 0);
    }

    function decimals() public pure override returns (uint8) {
        return 6;
    }

    // ── Operations ──────────────────────────────────────────────────────────────────────────

    /// @notice Issue units at allocation. Only the escrow, only to an allowed address, within both caps.
    ///         `priceMicro` is the price they are issued at: the token tells the fee ledger, which names the
    ///         cohort the lot carries. `lockDays_` and `penaltyBps_` are the lock-up terms in force when the
    ///         money was placed in escrow; the lot takes the lighter of those and of the terms in force now,
    ///         so a lock-up raised while the money waited does not reach it (review of 03.10.2026, B-01).
    function mint(address to, uint256 amount, uint256 priceMicro, uint16 lockDays_, uint16 penaltyBps_, bytes32 batchId)
        external
        whenNotPaused
    {
        if (msg.sender == address(0) || msg.sender != minter()) revert NotMinter();
        if (reissueState == 1) revert ReissueOpen();
        if (amount == 0) revert ZeroAmount();
        if (!registry.isAllowed(to)) revert NotAllowedRecipient(to);
        if (amount > mintCapPerTx) revert CapPerTxExceeded(amount, mintCapPerTx);
        // a cap lowered below what stands against it leaves nothing, not a panic
        uint256 used = mintedInWindow();
        uint256 remaining = mintCapPerWindow > used ? mintCapPerWindow - used : 0;
        if (amount > remaining) revert CapPerWindowExceeded(amount, remaining);
        _minted = used + amount;
        _mintedAt = uint64(block.timestamp);
        everIssued = true;
        if (feeLedger == address(0)) revert NoLedger();
        _mintCohort = IFeeLedger(feeLedger).noteIssued(amount, priceMicro);
        _mintLock = lockDays_ < lockDays ? lockDays_ : lockDays;
        _mintPenalty = penaltyBps_ < penaltyBps ? penaltyBps_ : penaltyBps;
        _mint(to, amount);
        _mintCohort = 0;
        emit Minted(to, amount, batchId);
    }

    /// @notice What stands against the 24-hour cap right now: what was issued, less what has worn off.
    function mintedInWindow() public view returns (uint256) {
        uint256 back = (mintCapPerWindow * (block.timestamp - _mintedAt)) / WINDOW;
        return _minted > back ? _minted - back : 0;
    }

    /// @notice A migration: what the holders of a replaced token held, issued again here, lot by lot.
    ///         Governance only, through the timelock, so it is public two days before it happens; only while
    ///         the escrow has never issued anything. It may take several calls: each names the number of
    ///         lots already carried over (`offset`), so a call can neither be repeated nor skipped, and
    ///         `finishReissue` closes the migration against the totals. Caps do not apply, the registry does:
    ///         every recipient must be allowed, and must be a holder — never a queue, current or past, nor
    ///         the operations Safe, whose units nothing would move again (review of 03.10.2026, B-08).
    ///         A lot keeps the day it was first issued, so its lock-up and its fee age continue rather than
    ///         restart; the lock-up terms it carried (review of 27.09.2026, M-09); and the basis it stood at
    ///         for the performance fee, so nobody is charged for a rise he did not have (the audit of
    ///         04.10.2026, EX-01).
    function reissue(uint256 offset, Carry[] calldata lots, bytes32 ref) external onlyGovernance whenNotPaused {
        if (reissueState == 2 || everIssued) revert AlreadyIssued();
        // the ledger has to be named first, or the carried-over units could never be seeded (review of
        // 28.09.2026, L-16): the order of a migration is setFeeLedger, reissue, finishReissue, seed, addSeries
        if (feeLedger == address(0)) revert NoLedger();
        if (offset != reissuedCount) revert ReissueOffset(offset, reissuedCount);
        reissueState = 1;
        // the ledger keeps the carried-over units apart, uncharged, until governance seeds them (L-15)
        uint32[] memory cohorts = _noteCarried(lots);
        uint256 total;
        for (uint256 i = 0; i < lots.length; i++) {
            _carry(lots[i], cohorts[i], ref);
            total += lots[i].units;
        }
        _reissueAt = 0;
        _mintCohort = 0;
        reissuedCount += lots.length;
        reissuedUnits += total;
    }

    /// @dev The ledger is told the units and the basis of every lot of a batch, and names their cohorts.
    function _noteCarried(Carry[] calldata lots) private returns (uint32[] memory) {
        uint256[] memory units = new uint256[](lots.length);
        uint256[] memory basis = new uint256[](lots.length);
        for (uint256 i = 0; i < lots.length; i++) {
            units[i] = lots[i].units;
            basis[i] = lots[i].basisMicro;
        }
        return IFeeLedger(feeLedger).noteMigrated(units, basis);
    }

    /// @dev One lot of a migration, issued to its holder with the day and terms it carried.
    function _carry(Carry calldata c, uint32 cohort, bytes32 ref) private {
        if (c.units == 0 || c.issuedAt == 0) revert ZeroAmount();
        if (!registry.isAllowed(c.to)) revert NotAllowedRecipient(c.to);
        if (registry.wasRedemptionSink(c.to) || c.to == ops) revert NotAHolder(c.to);
        if (c.issuedAt > block.timestamp) revert IssuedInFuture(c.issuedAt);
        if (c.lockDays > MAX_LOCK_DAYS) revert LockupTooLong(c.lockDays);
        if (c.penaltyBps > MAX_PENALTY_BPS) revert PenaltyTooHigh(c.penaltyBps);
        _reissueAt = c.issuedAt;
        _mintLock = c.lockDays;
        _mintPenalty = c.penaltyBps;
        _mintCohort = cohort;
        _mint(c.to, c.units);
        // said twice on purpose: as an issue, so every reader of issues sees it, and as what it is
        emit Minted(c.to, c.units, ref);
        emit Reissued(c.to, c.units, ref);
    }

    /// @notice Close the migration: the lots and units carried over are the ones stated, and from here on the
    ///         token issues through its escrow alone. Governance, through the timelock. The migration is bound
    ///         to its source here: `source` is the token whose holders were carried over — of this set or of
    ///         an earlier one, on chain either way — and it must be paused, so its positions cannot have moved
    ///         since they were read, with exactly `units` as its supply, so nothing was carried over that was
    ///         not held. The source is kept, and the directory holds a replacement to it (`replaceToken`).
    ///         Who got which units, and at what basis, is the migration manifest's to show; the sum, and the
    ///         token it came from, is what the contract holds it to (audit of 13.10.2026, E-1).
    function finishReissue(uint256 lots, uint256 units, IERC20 source) external onlyGovernance {
        if (reissueState != 1) revert AlreadyIssued();
        if (lots != reissuedCount || units != reissuedUnits) revert ReissueTotals(reissuedCount, reissuedUnits);
        // never this token itself — its supply is the reissue by construction — and never nothing
        if (address(source) == address(0) || address(source) == address(this)) revert ReissueSource(address(source));
        if (!IReplacedToken(address(source)).paused()) revert SourceNotPaused(address(source));
        uint256 supply = source.totalSupply();
        if (units != supply) revert SourceSupply(units, supply);
        reissuedSource = address(source);
        reissueState = 2;
        emit ReissueFinished(lots, units, address(source));
    }

    /// @notice Retire units the operations Safe holds itself — there is no way to burn anyone else's tokens.
    ///         Settled units never pass through the Safe any more: the queue burns them (`burnSettled`).
    function burn(uint256 amount, bytes32 batchId) external onlyOps whenNotPaused {
        if (amount == 0) revert ZeroAmount();
        _burn(ops, amount); // the lots that leave are reported from `_moveLots`
        emit Burned(amount, batchId);
    }

    /// @notice The redemption queue retires the units it has just settled, from its own balance, inside the
    ///         settlement. A settled unit is gone in the same call it was paid in (review of 27.09.2026).
    function burnSettled(uint256 amount, Lot[] calldata lots, bytes32 batchId) external onlySink whenNotPaused {
        if (amount == 0) revert ZeroAmount();
        uint256 sum;
        for (uint256 i = 0; i < lots.length; i++) {
            sum += lots[i].units;
        }
        if (sum != amount) revert LotsMismatch(amount, sum);
        _burn(msg.sender, amount); // the sink keeps no lots: the queue says which left
        _reportBurn(lots);
        emit Burned(amount, batchId);
    }

    /// @dev Every burn, by whichever path, is told to the fee ledger in the same call as the lots that left, so
    ///      the gain owed is that of exactly those units (review of 28.09.2026, M-19, M-21).
    function _reportBurn(Lot[] memory lots) private {
        if (feeLedger != address(0) && lots.length != 0) IFeeLedger(feeLedger).noteBurned(lots);
    }

    /// @notice Name the fee ledger, once: the deployer within a day of deployment, else governance.
    function setFeeLedger(address ledger) external {
        if (msg.sender != governance && !(msg.sender == _deployer && block.timestamp <= _deployerUntil)) {
            revert NotGovernance();
        }
        if (ledger == address(0)) revert ZeroAddress();
        if (feeLedger != address(0)) revert LedgerSet();
        feeLedger = ledger;
        emit FeeLedgerSet(ledger);
    }

    /// @notice Move a token sent to this contract's address — USDC mistaken for a deposit, typically — to the
    ///         quarantine the redemption queue names, where compliance decides. The contract holds nothing of
    ///         its own; its own units cannot be here (no transfer to it passes the registry) and are refused.
    function rescue(IERC20 stray) external onlyOps {
        if (address(stray) == address(this)) revert OwnUnits();
        address to = directory.quarantine();
        if (to == address(0)) revert NoQuarantine();
        uint256 amount = stray.balanceOf(address(this));
        if (amount == 0) revert NothingToRescue();
        stray.safeTransfer(to, amount);
        emit Rescued(address(stray), amount, to, msg.sender);
    }

    // ── Pause: easy to set, hard to lift ────────────────────────────────────────────────────

    function pause() external {
        bool allowed = msg.sender == sentinel || msg.sender == ops || msg.sender == governance;
        if (!allowed) {
            // Any single owner of the operations Safe may stop the token without waiting for a quorum.
            (bool ok, bytes memory data) = ops.staticcall(abi.encodeCall(ISafeOwners.isOwner, (msg.sender)));
            allowed = ok && data.length >= 32 && abi.decode(data, (bool));
        }
        if (!allowed) revert NotPauser();
        paused = true;
        emit Paused(msg.sender);
    }

    function unpause() external onlyGovernance {
        paused = false;
        emit Unpaused();
    }

    // ── Governance (through the timelock) ───────────────────────────────────────────────────

    function setCaps(uint256 perTx, uint256 perWindow) external onlyGovernance {
        mintCapPerTx = perTx;
        mintCapPerWindow = perWindow;
        emit CapsSet(perTx, perWindow);
    }

    function setSentinel(address sentinel_) external onlyGovernance {
        sentinel = sentinel_;
        emit SentinelSet(sentinel_);
    }

    /// @notice The lock-up for units issued from now on. Within the bounds; lots already issued keep theirs.
    function setLockup(uint16 lockDays_, uint16 penaltyBps_) external onlyGovernance {
        _setLockup(lockDays_, penaltyBps_);
    }

    function _setLockup(uint16 lockDays_, uint16 penaltyBps_) private {
        if (lockDays_ > MAX_LOCK_DAYS) revert LockupTooLong(lockDays_);
        if (penaltyBps_ > MAX_PENALTY_BPS) revert PenaltyTooHigh(penaltyBps_);
        lockDays = lockDays_;
        penaltyBps = penaltyBps_;
        emit LockupSet(lockDays_, penaltyBps_);
    }

    // ── Lots: the terms every unit carries ──────────────────────────────────────────────────

    /// @notice A holder's lots, in no particular order.
    function lotsOf(address holder) external view returns (Lot[] memory out) {
        Lot[] storage L = _lots(holder);
        uint256 h = _head[holder];
        out = new Lot[](L.length - h);
        for (uint256 i = h; i < L.length; i++) {
            out[i - h] = L[i];
        }
    }

    /// @notice Is a lot still inside its lock-up right now?
    function isLocked(Lot memory lot) public view returns (bool) {
        return block.timestamp < uint256(lot.issuedAt) + uint256(lot.lockDays) * 1 days;
    }

    /// @notice Units of `holder` still inside their lock-up.
    function lockedUnits(address holder) public view returns (uint256 locked) {
        Lot[] storage L = _lots(holder);
        // sorted by issue day, not by the day the lock ends: each lot is asked
        for (uint256 i = _head[holder]; i < L.length; i++) {
            if (isLocked(L[i])) locked += L[i].units;
        }
    }

    /// @notice Units of `holder` that may be redeemed today without a penalty.
    function unlockedUnits(address holder) external view returns (uint256) {
        return balanceOf(holder) - lockedUnits(holder);
    }

    modifier onlySink() {
        if (msg.sender == address(0) || msg.sender != registry.redemptionSink()) revert NotSink();
        _;
    }

    /// @notice The redemption queue takes the lots behind `units` — oldest first — before it pulls the units
    ///         for a request, and keeps them with the request: they say what is locked and at what penalty.
    function takeLots(address holder, uint256 units) external onlySink returns (Lot[] memory taken) {
        taken = _take(holder, units);
        reservedLots[holder] += taken.length;
    }

    /// @notice The queue takes `units` of `holder`'s lots that are past their lock-up, oldest first, leaving
    ///         the locked ones in place — so a holder redeems what is free even when an older lot is still
    ///         locked (a shortened lock-up leaves old lots locked behind newer free ones; review F-01).
    ///         Returns fewer units than asked when fewer are free; the queue decides what that means.
    function takeUnlockedLots(address holder, uint256 units) external onlySink returns (Lot[] memory taken) {
        taken = _takeUnlocked(holder, units);
        reservedLots[holder] += taken.length;
    }

    /// @notice The queue has settled `count` whole lots of `holder`'s request: they are no longer reserved.
    function releaseLots(address holder, uint256 count) external onlySink {
        reservedLots[holder] -= count;
    }

    /// @notice The queue gives a cancelled request's lots back to their owner, exactly as they were, before
    ///         it returns the units: his reservation ends with them. Both lists are sorted — the request's
    ///         as they were taken, the holder's as kept — so they are merged in one pass and the holder's
    ///         list written once: linear, never a shift per lot (review of 27.09.2026, N-04). A lot equal in
    ///         day and terms to its neighbour merges into it.
    function returnLots(address holder, Lot[] calldata lots) external onlySink {
        reservedLots[holder] -= lots.length; // his own lots back: the reservation they held ends
        _mergeInto(holder, lots, type(uint256).max);
    }

    /// @notice The queue credits lots to someone they were not taken from — a governance recovery — before
    ///         it sends the units: the recipient's own reservations are not his business and stay as they
    ///         are (review of 28.09.2026, M-12). The limit holds for him as for anyone receiving lots.
    function creditLots(address holder, Lot[] calldata lots) external onlySink {
        uint256 before = _lots(holder).length - _head[holder];
        _mergeInto(holder, lots, type(uint256).max);
        uint256 held = _lots(holder).length - _head[holder];
        // the limit binds on new keys only, as for a transfer (L-07): lots merging into keys already held are
        // never refused
        if (held > before && held + reservedLots[holder] > MAX_LOTS) revert TooManyLots(holder);
    }

    /// @dev The holder's current list.
    function _lots(address holder) private view returns (Lot[] storage) {
        return _lotsByGen[holder][_gen[holder]];
    }

    /// @dev Forget the holder's list in one write: the next generation is an empty array. Called only when
    ///      every lot of the list is spent, so what is left behind is an array of zeroed slots and its length.
    function _clear(address holder) private {
        _gen[holder]++;
        _head[holder] = 0;
    }

    /// @dev Merge a sorted list of lots into a holder's sorted list in one pass, rewriting the holder's active
    ///      lots in place: linear in the two lengths, however the days interleave (review of 27.09.2026, L-06 for
    ///      transfers, N-04 for cancels). Equal lots merge. A lot of `lots` that opens a new entry — it merges
    ///      into nothing the holder has — counts against `maxNew`, the new entries this merge may open (A-04).
    function _mergeInto(address holder, Lot[] memory lots, uint256 maxNew) private {
        Lot[] storage L = _lots(holder);
        uint256 h = _head[holder];
        uint256 n = L.length - h;
        Lot[] memory mine = new Lot[](n);
        for (uint256 i = 0; i < n; i++) {
            mine[i] = L[h + i];
        }
        Lot[] memory out = new Lot[](n + lots.length);
        uint256 k;
        uint256 a;
        uint256 b;
        uint256 opened;
        while (a < n || b < lots.length) {
            // equal lots: the holder's own first, so an arriving lot of the same day and terms merges into it
            if (b >= lots.length || (a < n && !_after(mine[a], lots[b]))) {
                k = _put(out, k, mine[a++]);
            } else {
                uint256 grown = _put(out, k, lots[b]);
                // an arriving lot that opened a new entry
                if (grown != k && ++opened > maxNew) revert DustLot(holder);
                k = grown;
                b++;
            }
        }
        _rewrite(holder, out, k);
    }

    /// @dev Append a lot to a sorted list being built, merging it into the last entry when equal; the new length.
    function _put(Lot[] memory out, uint256 k, Lot memory next) private pure returns (uint256) {
        if (next.units == 0) return k;
        if (k != 0 && _same(out[k - 1], next)) {
            out[k - 1].units += next.units;
            return k;
        }
        out[k] = next;
        return k + 1;
    }

    /// @dev Write `k` lots over the holder's active region, from the head on: the slots the list already
    ///      holds are reused, the tail beyond them is popped, and a list that ends empty is forgotten in one
    ///      write. What lies before the head is never touched, so nothing here is linear in the holder's
    ///      history (review of 28.09.2026, M-10: clearing the whole array walked every spent slot).
    function _rewrite(address holder, Lot[] memory list, uint256 k) private {
        Lot[] storage L = _lots(holder);
        uint256 h = _head[holder];
        for (uint256 i = 0; i < k; i++) {
            if (h + i < L.length) L[h + i] = list[i];
            else L.push(list[i]);
        }
        while (L.length > h + k) {
            L.pop();
        }
        if (k == 0) _clear(holder);
    }

    /// @dev The order of lots: by day, then lock-up, then penalty. `a` after `b` strictly.
    function _after(Lot memory a, Lot memory b) private pure returns (bool) {
        if (a.issuedAt != b.issuedAt) return a.issuedAt > b.issuedAt;
        if (a.lockDays != b.lockDays) return a.lockDays > b.lockDays;
        if (a.penaltyBps != b.penaltyBps) return a.penaltyBps > b.penaltyBps;
        return a.cohort > b.cohort;
    }

    /// @dev The same lot in every term: one entry, whatever the units.
    function _same(Lot memory a, Lot memory b) private pure returns (bool) {
        return
            a.issuedAt == b.issuedAt && a.lockDays == b.lockDays && a.penaltyBps == b.penaltyBps && a.cohort == b.cohort;
    }

    /// @dev Add a lot to a holder in issue order: an issue goes at the end, a lot that arrives by transfer or
    ///      comes back from a cancelled request is inserted where its day belongs, and a lot equal in day and
    ///      terms to one already held is merged into it. The shifting is paid by whoever pushes — the sender
    ///      of a transfer, the holder who cancels — never by the one who later redeems.
    function _push(address holder, Lot memory lot) private {
        Lot[] storage L = _lots(holder);
        uint256 h = _head[holder];
        uint256 i = L.length;
        // the one order every list keeps: by day, then lock-up, then penalty — so lots equal in all three are
        // always neighbours and merge, whatever order they arrive in (review of 27.09.2026, N-05)
        while (i > h && _after(L[i - 1], lot)) {
            i--;
        }
        if (i > h && _same(L[i - 1], lot)) {
            L[i - 1].units += lot.units;
            return;
        }
        if (L.length - h + reservedLots[holder] >= MAX_LOTS) revert TooManyLots(holder);
        L.push(lot);
        for (uint256 j = L.length - 1; j > i; j--) {
            L[j] = L[j - 1];
        }
        L[i] = lot;
    }

    /// @dev Consume up to `units` of `holder`'s unlocked lots, oldest first. Locked lots are stepped over: the
    ///      active lots are rewritten once without the lots consumed (linear in their number), the fast
    ///      head-walk of `_take` is not possible when a locked lot sits in front of a free one.
    function _takeUnlocked(address holder, uint256 units) private returns (Lot[] memory taken) {
        Lot[] storage L = _lots(holder);
        uint256 h = _head[holder];
        uint256 n = L.length - h;
        Lot[] memory mine = new Lot[](n);
        for (uint256 i = 0; i < n; i++) {
            mine[i] = L[h + i];
        }
        Lot[] memory buf = new Lot[](n);
        uint256 m;
        uint256 left = units;
        for (uint256 i = 0; i < n && left != 0; i++) {
            if (isLocked(mine[i])) continue;
            uint256 take = mine[i].units < left ? mine[i].units : left;
            buf[m++] = Lot(uint128(take), mine[i].issuedAt, mine[i].lockDays, mine[i].penaltyBps, mine[i].cohort);
            mine[i].units -= uint128(take);
            left -= take;
        }
        if (m == 0) return taken;
        uint256 k;
        for (uint256 i = 0; i < n; i++) {
            if (mine[i].units != 0) mine[k++] = mine[i];
        }
        _rewrite(holder, mine, k);
        taken = new Lot[](m);
        for (uint256 i = 0; i < m; i++) {
            taken[i] = buf[i];
        }
    }

    /// @dev Consume `units` of `holder`'s lots, oldest first, and return what was taken.
    function _take(address holder, uint256 units) private returns (Lot[] memory taken) {
        Lot[] storage L = _lots(holder);
        uint256 h = _head[holder];
        Lot[] memory buf = new Lot[](L.length - h);
        uint256 n;
        uint256 left = units;
        while (left != 0 && h < L.length) {
            Lot storage lot = L[h];
            uint256 take = lot.units < left ? lot.units : left;
            buf[n++] = Lot(uint128(take), lot.issuedAt, lot.lockDays, lot.penaltyBps, lot.cohort);
            left -= take;
            if (take == lot.units) {
                delete L[h];
                h++;
            } else {
                lot.units -= uint128(take);
            }
        }
        if (h == L.length) {
            _clear(holder);
            return _copy(buf, n);
        }
        _head[holder] = h;
        taken = _copy(buf, n);
    }

    /// @dev The first `n` of a buffer.
    function _copy(Lot[] memory buf, uint256 n) private pure returns (Lot[] memory out) {
        out = new Lot[](n);
        for (uint256 i = 0; i < n; i++) {
            out[i] = buf[i];
        }
    }

    /// @notice Court order or documented key loss only. Public event, 48 h notice via the timelock.
    ///         The destination still has to be an allowed address: a recovery never leaves the registry.
    function forcedTransfer(address from, address to, uint256 amount, bytes32 legalRef) external onlyGovernance {
        if (!registry.isAllowed(to)) revert NotAllowedRecipient(to);
        // never through the queue: its balance is other holders' open requests, and units leaving it would
        // carry no lots — a recovery of a request changes the request, not the queue's balance (27.09.2026)
        address sink = registry.redemptionSink();
        if (from == sink || to == sink) revert SinkNotForceable();
        _forced = true;
        _transfer(from, to, amount);
        _forced = false;
        emit ForcedTransfer(from, to, amount, legalRef);
    }

    // ── Transfer rule ───────────────────────────────────────────────────────────────────────

    /// @dev Mint and burn are guarded by their functions; every holder-to-holder move goes
    ///      through the registry, and nothing moves while paused.
    function _update(address from, address to, uint256 value) internal override {
        if (from != address(0) && to != address(0)) {
            if (paused) revert IsPaused();
            if (!_forced && !registry.canTransfer(from, to)) revert TransferNotAllowed(from, to);
            // whoever moves units under an allowance is held to the registry as well: a frozen address could
            // otherwise go on moving a holder's units on an approval given before the freeze (the audit's G05)
            if (!_forced && msg.sender != from && !registry.isAllowed(msg.sender)) {
                revert TransferNotAllowed(from, to);
            }
            // Units reach the redemption sink only when the sink pulls them (`request`): a holder pushing
            // them there with a plain transfer would leave units nobody can settle or cancel.
            if (!_forced && to == registry.redemptionSink() && msg.sender != to) revert SendToSinkOnlyByRequest(to);
        }
        super._update(from, to, value);
        _moveLots(from, to, value);
    }

    /// @dev The lots follow the units: an issue opens one, a burn closes what the burner holds, a transfer
    ///      between holders moves the oldest ones. Nothing happens at the redemption sink's side: the queue
    ///      takes a request's lots itself and gives them back itself, and what it passes on is burned.
    function _moveLots(address from, address to, uint256 value) private {
        address sink = registry.redemptionSink();
        if (from == address(0)) {
            if (value > type(uint128).max) revert TooLarge();
            if (to != sink) {
                _push(
                    to,
                    Lot(
                        uint128(value),
                        _reissueAt != 0 ? _reissueAt : uint64(block.timestamp),
                        _mintLock,
                        _mintPenalty,
                        _mintCohort
                    )
                );
            }
        } else if (to == address(0)) {
            if (from != sink) _reportBurn(_take(from, value));
        } else if (from != sink && to != sink) {
            Lot[] memory moved = _take(from, value);
            uint256 before = _lots(to).length - _head[to];
            // a forced transfer is a recovery, not a holder's doing: neither limit of A-04 binds it
            // a transfer under one unit opens nothing new; one of `value` opens at most one entry per whole
            // unit and one more — the sender's oldest lot may be a fraction left by a part redemption, and
            // the last one taken is cut to fit (audit of 05.10.2026, P-01)
            _mergeInto(to, moved, _forced ? type(uint256).max : (value < MIN_NEW_LOT ? 0 : 1 + value / MIN_NEW_LOT));
            uint256 held = _lots(to).length - _head[to];
            // the limit bounds new keys: a lot merging into one the holder already has adds nothing to walk, so
            // it is never refused, however many fragments of his own he has in requests (27.09.2026, L-07)
            if (held > before && held + reservedLots[to] > (_forced ? MAX_LOTS : TRANSFER_MAX_LOTS)) {
                revert TooManyLots(to);
            }
        }
    }
}

lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)

pragma solidity ^0.8.20;

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

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../utils/introspection/IERC165.sol";

lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)

pragma solidity ^0.8.20;

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

lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;

/**
 * @dev Standard ERC-20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC-721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC-1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}

lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC-20
 * applications.
 */
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
    mapping(address account => uint256) private _balances;

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

    uint256 private _totalSupply;

    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 returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual 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 view virtual returns (uint8) {
        return 18;
    }

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

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual 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 `value`.
     */
    function transfer(address to, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, value);
        return true;
    }

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

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` 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 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Skips emitting an {Approval} event indicating an allowance update. This is not
     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
     *
     * 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 `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` 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.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            _totalSupply += value;
        } else {
            uint256 fromBalance = _balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                _balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                _totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                _balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` 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.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
     * true using the following override:
     *
     * ```solidity
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, value, true);
     * }
     * ```
     *
     * Requirements are the same as {_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
        if (owner == address(0)) {
            revert ERC20InvalidApprover(address(0));
        }
        if (spender == address(0)) {
            revert ERC20InvalidSpender(address(0));
        }
        _allowances[owner][spender] = value;
        if (emitEvent) {
            emit Approval(owner, spender, value);
        }
    }

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

lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

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

pragma solidity ^0.8.20;

/**
 * @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);
}

lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol

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

pragma solidity ^0.8.20;

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);
}

lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {Address} from "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

lib/openzeppelin-contracts/contracts/utils/Address.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {Errors.FailedCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
     * of an unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {Errors.FailedCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            assembly ("memory-safe") {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert Errors.FailedCall();
        }
    }
}

lib/openzeppelin-contracts/contracts/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;
    }
}

lib/openzeppelin-contracts/contracts/utils/Errors.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

src/AllowlistRegistry.sol

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

/// @title AllowlistRegistry — the PPM whitelist
/// @notice Every transfer of the product token is checked here. Immutable code, mutable state:
///         the operations Safe adds, removes and freezes addresses; the governance timelock sets
///         the transfer mode and the redemption sink. No owner, no upgrade path.
/// @dev `canTransfer(from, to)` has the ERC-3643 shape so institutional custodians recognise it.
contract AllowlistRegistry {
    enum Status {
        None,
        Allowed,
        Frozen
    }

    /// @notice RedemptionOnly — holders may only send to the redemption sink (SA §7.1); the sink may send
    ///         back (a cancelled request) or on to operations (a settled one).
    ///         WithinAllowlist — holders may send to any allowed address (PPM whitelist transfers).
    enum TransferMode {
        RedemptionOnly,
        WithinAllowlist
    }

    /// @notice The Operations Safe. day-to-day registry changes.
    address public immutable ops;
    /// @notice Governance (the Governance Safe behind a 48 h timelock): rule changes.
    address public immutable governance;

    mapping(address => Status) private _status;
    /// @notice Every address that has ever been the redemption sink: a replaced queue is still no place for a
    ///         holder's units (review of 28.09.2026, L-12).
    mapping(address => bool) public wasRedemptionSink;
    TransferMode public transferMode;
    /// @notice The address holders send tokens to when redeeming (the operations Safe on launch).
    address public redemptionSink;

    event Allowed(address indexed account, bytes32 reason);
    event Removed(address indexed account, bytes32 reason);
    event Frozen(address indexed account, bytes32 reason);
    event Unfrozen(address indexed account, bytes32 reason);
    event TransferModeSet(TransferMode mode);
    event RedemptionSinkSet(address indexed sink);

    error NotOps();
    error NotGovernance();
    error ZeroAddress();
    error SinkNotAllowed(address sink);
    error SinkBusy(address sink, uint256 openUnits);
    error SinkOwes(address sink, uint256 feesDue);
    error SinkUnreadable(address sink);
    error Protected(address account);
    error NotFrozen(address account);

    modifier onlyOps() {
        if (msg.sender != ops) revert NotOps();
        _;
    }

    modifier onlyGovernance() {
        if (msg.sender != governance) revert NotGovernance();
        _;
    }

    /// @param initialMode the transfer mode the series starts in; afterwards only governance changes it.
    constructor(address ops_, address governance_, address redemptionSink_, TransferMode initialMode) {
        if (ops_ == address(0) || governance_ == address(0) || redemptionSink_ == address(0)) revert ZeroAddress();
        ops = ops_;
        governance = governance_;
        redemptionSink = redemptionSink_;
        wasRedemptionSink[redemptionSink_] = true;
        // The sink receives redemptions; operations receives the units a settlement retires.
        _status[redemptionSink_] = Status.Allowed;
        _status[ops_] = Status.Allowed;
        transferMode = initialMode;
        emit Allowed(redemptionSink_, "REDEMPTION_SINK");
        emit Allowed(ops_, "OPERATIONS");
        emit RedemptionSinkSet(redemptionSink_);
        emit TransferModeSet(initialMode);
    }

    // ── Operations ──────────────────────────────────────────────────────────────────────────

    function allow(address[] calldata accounts, bytes32 reason) external onlyOps {
        for (uint256 i = 0; i < accounts.length; i++) {
            if (accounts[i] == address(0)) revert ZeroAddress();
            // a replaced queue never comes back as a holder: units sent to it could not be moved again (B-07)
            if (wasRedemptionSink[accounts[i]] && accounts[i] != redemptionSink) revert Protected(accounts[i]);
            _status[accounts[i]] = Status.Allowed;
            emit Allowed(accounts[i], reason);
        }
    }

    function remove(address[] calldata accounts, bytes32 reason) external onlyOps {
        for (uint256 i = 0; i < accounts.length; i++) {
            if (accounts[i] == ops || accounts[i] == redemptionSink) revert Protected(accounts[i]);
            _status[accounts[i]] = Status.None;
            emit Removed(accounts[i], reason);
        }
    }

    /// @notice A frozen address stays in the registry but its tokens do not move in either direction —
    ///         the shape of a sanctions freeze.
    function freeze(address[] calldata accounts, bytes32 reason) external onlyOps {
        for (uint256 i = 0; i < accounts.length; i++) {
            // the passage and the operations Safe stay open, or every holder's pending units are locked
            if (accounts[i] == ops || accounts[i] == redemptionSink) revert Protected(accounts[i]);
            _status[accounts[i]] = Status.Frozen;
            emit Frozen(accounts[i], reason);
        }
    }

    function unfreeze(address[] calldata accounts, bytes32 reason) external onlyOps {
        for (uint256 i = 0; i < accounts.length; i++) {
            if (_status[accounts[i]] != Status.Frozen) revert NotFrozen(accounts[i]); // never an admission by the back door
            _status[accounts[i]] = Status.Allowed;
            emit Unfrozen(accounts[i], reason);
        }
    }

    // ── Governance (through the timelock) ───────────────────────────────────────────────────

    function setTransferMode(TransferMode mode) external onlyGovernance {
        transferMode = mode;
        emit TransferModeSet(mode);
    }

    /// @notice The new sink is admitted here, in the same act, and must not have been admitted before: an
    ///         address that is Allowed but not yet the sink could be sent units nothing can move again
    ///         (review of 03.10.2026, B-07). The sink it replaces leaves the registry for the same reason.
    ///         It must owe nothing: no open request (`openUnits`, M-03) and no fee deferred for the treasury
    ///         (`totalFeesDue`): a deferred fee is paid from a custody's approval of the old queue, which the
    ///         rotation withdraws, and would otherwise be stranded in the custody (audit of 13.10.2026, E-3).
    function setRedemptionSink(address sink) external onlyGovernance {
        if (sink == address(0)) revert ZeroAddress();
        if (_status[sink] != Status.None || wasRedemptionSink[sink] || sink == ops) revert SinkNotAllowed(sink);
        // the queue being replaced must owe nothing: every request settled or cancelled first (M-03), every
        // deferred fee paid (E-3)
        address old = redemptionSink;
        if (old != address(0) && old.code.length != 0) {
            // a deployed sink is a queue and says what it owes; one that cannot is not replaced blindly
            uint256 open = _owed(old, "openUnits()");
            if (open != 0) revert SinkBusy(old, open);
            uint256 fees = _owed(old, "totalFeesDue()");
            if (fees != 0) revert SinkOwes(old, fees);
        }
        _status[old] = Status.None;
        emit Removed(old, "REDEMPTION_SINK_REPLACED");
        _status[sink] = Status.Allowed;
        emit Allowed(sink, "REDEMPTION_SINK");
        redemptionSink = sink;
        wasRedemptionSink[sink] = true;
        emit RedemptionSinkSet(sink);
    }

    /// @dev One figure the old sink owes, by the name of its view; a sink that cannot answer is not replaced.
    function _owed(address sink, string memory view_) private view returns (uint256) {
        (bool ok, bytes memory ret) = sink.staticcall(abi.encodeWithSignature(view_));
        if (!ok || ret.length != 32) revert SinkUnreadable(sink);
        return abi.decode(ret, (uint256));
    }

    // ── Views ───────────────────────────────────────────────────────────────────────────────

    function statusOf(address account) external view returns (Status) {
        return _status[account];
    }

    function isAllowed(address account) public view returns (bool) {
        return _status[account] == Status.Allowed;
    }

    /// @notice May `from` send to `to` right now? Both must be Allowed (not Frozen); in
    ///         RedemptionOnly mode one side must be the redemption sink.
    function canTransfer(address from, address to) external view returns (bool) {
        if (!isAllowed(from) || !isAllowed(to)) return false;
        if (transferMode == TransferMode.RedemptionOnly) return to == redemptionSink || from == redemptionSink;
        return true;
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/=lib/openzeppelin-contracts/",
    "forge-std/=lib/forge-std/src/",
    "ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.