Verified contractPartialMIT
SubscriptionEscrow
Address0x4d34eb9296bb1aa140b17a6691da4e2a8124830b
- Balance
0 ETH
- Transactions
1
- 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,073
- Creation transaction
- 0x8508bf9bac…c39ac36e2a
- Main copy (most transactions)
- 0x81fcaa24…b32591c5
16 files
- src/SubscriptionEscrow.solmain39.8 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol192 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol181 B
- lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol6.54 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol10.9 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol684 B
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol9.44 KB
- lib/openzeppelin-contracts/contracts/utils/Address.sol6.03 KB
- lib/openzeppelin-contracts/contracts/utils/Context.sol963 B
- lib/openzeppelin-contracts/contracts/utils/Errors.sol896 B
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol870 B
- src/AllowlistRegistry.sol8.99 KB
- src/AttestationAnchor.sol29.81 KB
- src/ProductToken.sol43.9 KB
src/SubscriptionEscrow.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {AllowlistRegistry} from "./AllowlistRegistry.sol";
import {AttestationAnchor} from "./AttestationAnchor.sol";
import {ProductToken} from "./ProductToken.sol";
/// @dev What the escrow asks the series directory: where the contour's fees go, where swept money goes,
/// where the tariffs live, which escrow serves a token now, and who governs.
interface ISeriesDirectory {
function feeRecipient() external view returns (address);
function quarantine() external view returns (address);
function parameters() external view returns (address);
function escrowOf(address token) external view returns (address);
function governance() external view returns (address);
}
/// @dev The one tariff the escrow needs.
interface IEntryFee {
function entryBpsOf(address token) external view returns (uint16);
}
/// @title SubscriptionEscrow — pre-allocation funds, held for the investor until ALCUM allocates or returns them
/// @notice Continuous: an allowed investor may place USDC at any time. From then on a recorded deposit has
/// exactly three ways out, each to a fixed place: allocation to `destination` (the custodian, fixed
/// at deployment) with units issued to the investor, on the operations Safe's decision; a return to
/// the investor's own address (`release`) — the operations Safe's for an investor in good standing,
/// governance's for one the registry no longer allows; and, under a legal order, a seizure to the
/// directory's quarantine (`seize`), governance's through the timelock, for an investor the registry no
/// longer allows. The investor cannot pull the money back on their own — a subscription is a
/// commitment, and a return is asked of ALCUM (owner, 25.09.2026). A deposit under a legal hold
/// (`hold`, set at once by the operations Safe — or by governance through the timelock — and lifted only by governance) can be
/// neither returned nor allocated; only a seizure moves it (review of 30.09.2026, Q-01).
/// Allocation may take part of a deposit today and the rest tomorrow. The order deposits are
/// allocated in (first in, first out) is the dealing rule, applied off chain and visible here in
/// the order of the Deposited and Allocated logs. No ether is accepted; USDC leaves by these three
/// ways and by the sweep of what nobody deposited; any other token only to the quarantine.
/// @notice Allocation issues the units: the escrow reads the dealing price of the latest anchored day
/// from the AttestationAnchor, takes the entry fee off each amount, sends the rest to `destination`
/// and mints exactly net ÷ price to the investor, in the same call. The operations Safe chooses whom
/// to allocate and how much; it cannot choose the price, the fee or the number of units.
/// @notice Every amount placed is a tranche that keeps what was true when it arrived (owner, 04.10.2026):
/// - the dealing day it first takes part in — the day whose cut-off it was placed before. It deals at
/// the price of that day or of a later one, never of an earlier one, whenever the record is
/// written (reviews of 02.10.2026, A-02, and the audit's G08);
/// - the entry fee and the lock-up terms in force then. It is charged the lower of that fee and the
/// one in force at allocation, and its units take the lighter of the two lock-ups: a tariff raised
/// while the money waited does not reach it (review of 03.10.2026, B-01).
/// @notice Money may also arrive from the redemption queue, when a holder redeems another series and asks
/// to subscribe here instead of being paid out (a switch). It lands in that holder's name, takes
/// part in this series' dealing of the same day the redemption was settled at, and pays no entry
/// fee: the switch fee was the price of the move. Such money is not meant to be returned; if the
/// operations Safe returns it all the same, the difference between the exit fee and the switch fee
/// it paid is withheld for the treasury, so a switch and a return is never a cheaper exit (the
/// audit's G06).
/// @dev USDC sent here by a plain transfer, around `deposit`, is not recorded against anyone: it is not a
/// subscription, and nobody can be credited for it. The operations Safe may sweep exactly that
/// excess — the balance above what depositors are owed — to the directory's quarantine address, where
/// compliance decides; the arithmetic keeps it off every depositor's money. Deposits can be closed
/// (by the operations Safe or the sentinel) while a replacement escrow goes through the timelock;
/// returns never close — the old escrow can always give the money back.
contract SubscriptionEscrow {
using SafeERC20 for IERC20;
/// @notice One amount an investor placed, with what was true when it arrived.
struct Tranche {
uint128 amount;
/// @dev The number of the first dealing day it takes part in (days since 1970-01-01).
uint32 dealDay;
/// @dev The entry fee and the lock-up terms in force when it was placed.
uint16 entryBps;
uint16 lockDays;
uint16 penaltyBps;
/// @dev Proceeds of a switch: no entry fee, and `topUp` withheld if it is returned instead of allocated.
bool switched;
uint128 topUp;
}
IERC20 public immutable usdc;
AllowlistRegistry public immutable registry;
/// @notice Where allocated funds go: the custodian, or the operations Safe until there is one.
address public immutable destination;
/// @notice The Operations Safe.
address public immutable ops;
/// @notice The series directory: it names this series' escrow, the treasury, the quarantine and governance.
ISeriesDirectory public immutable directory;
/// @notice Where the day's price comes from.
AttestationAnchor public immutable anchor;
/// @notice The series' units, minted here and nowhere else.
ProductToken public immutable token;
/// @notice The highest entry fee the escrow would ever apply, whatever the parameters say (5 %).
uint16 public constant MAX_FEE_BPS = 500;
/// @notice The most tranches one investor may have waiting: amounts placed for the same dealing day on
/// the same terms are one tranche, so this is days of unallocated money, not deposits.
uint256 public constant MAX_TRANCHES = 16;
/// @notice How long money must have waited — past the cut-off of its first dealing day, so at least this
/// long since it was placed — before the operations Safe may return it once a price it deals at is
/// public: seven calendar days, the queue's `OPS_CANCEL_AFTER` (audit of 13.10.2026, E-2).
uint256 public constant OPS_RELEASE_AFTER = 7 days;
mapping(address => uint256) public deposited;
/// @dev An investor's tranches, oldest first; a spent tranche is removed.
mapping(address => Tranche[]) private _tranches;
/// @notice Deposits under a legal hold: neither returned nor allocated until governance lifts the hold;
/// a seizure still moves them. Easy to set, hard to lift — the shape of the pause.
mapping(address => bool) public held;
/// @notice Everything waiting for allocation, across investors.
uint256 public totalDeposited;
/// @notice Fees taken that could not be paid to the treasury when they fell due — its address refused
/// by the stablecoin, say. They wait here, off every depositor's money and off the sweep, until
/// `payFees` (review of 03.10.2026, B-10: one refused transfer used to stop every allocation).
uint256 public feesDue;
/// @notice Whether new deposits are accepted. Returns (`release`) are always possible.
bool public depositsOpen = true;
event Deposited(address indexed investor, uint256 amount);
/// @notice The dealing day an amount first takes part in, and whether it came by a switch.
event TrancheNoted(address indexed investor, uint256 amount, uint32 dealDay, bool switched);
event Allocated(address indexed investor, uint256 amount, bytes32 indexed batchId);
/// @notice One dealing of this series: the day and price it used, what it took and what it issued.
event Dealt(
uint32 indexed day, uint256 priceMicro, uint256 allocated, uint256 fees, uint256 units, bytes32 indexed batchId
);
/// @notice A fee reached the treasury (same shape as the queue's event): `entry` at an allocation, `exit`
/// when switched money is returned, `deferred` when fees that had waited are paid.
event FeeCollected(bytes32 indexed kind, address indexed token, uint256 amount, bytes32 indexed ref);
/// @notice A fee that could not be paid to the treasury and waits in the escrow.
event FeeDeferred(bytes32 indexed kind, uint256 amount, bytes32 indexed ref);
/// @notice Money returned to its investor by the operations Safe's decision, with the reason on record.
/// `amount` is what left the investor's deposit; of switched money the difference to the exit fee
/// is withheld from it and shown in `FeeCollected("exit", …)` of the same call (G06).
event Released(address indexed investor, uint256 amount, bytes32 reason);
event DepositsClosed(address indexed by);
event DepositsOpened(address indexed by);
/// @notice USDC that reached the escrow outside `deposit`, moved to quarantine for compliance to decide.
event Swept(uint256 amount, address indexed to, address indexed by);
/// @notice A frozen investor's deposit moved to quarantine under a legal order, through the timelock.
/// `amount` is what left the deposit; of switched money the difference to the exit fee is withheld
/// for the treasury and shown in `FeeCollected("exit", …)` of the same call (E-10), as on a return.
event Seized(address indexed investor, uint256 amount, address indexed to, bytes32 indexed legalRef);
/// @notice A legal hold put on an investor's deposit, and lifted.
event Held(address indexed investor, address indexed by, bytes32 indexed ref);
event HoldLifted(address indexed investor, bytes32 indexed ref);
/// @notice A token other than USDC that reached the escrow, moved to quarantine.
event Rescued(address indexed token, uint256 amount, address indexed to, address indexed by);
/// @notice An investor left out of an allocation, and why: `released` (nothing left in escrow, the
/// money was returned since the batch was prepared), `not-allowed` (frozen or removed since),
/// `held` (under a legal hold), `after-cut-off` (placed after the day's cut-off), `failed`.
event Skipped(address indexed investor, bytes32 reason, bytes32 indexed batchId);
/// @notice Why a line `failed`: the revert data of the line, as the token, the ledger or the stablecoin
/// returned it — a cap, a lot limit, a run that rounds to nothing, a refused transfer — so the
/// remedy can be chosen from the record (audit of 13.10.2026, E-5). Beside `Skipped`, never instead.
event LineFailed(address indexed investor, bytes32 indexed batchId, bytes reason);
error NotOps();
error NotQueue();
error NotDirectory();
error NotAllowed(address investor);
error ZeroAmount();
error InsufficientDeposit(uint256 requested, uint256 available);
error ZeroAddress();
error LengthMismatch();
error FeeTooHigh(uint16 feeBps);
error NotLatestDay(uint32 day, uint32 latest);
error NoPrice(uint32 day);
error PriceStale(uint32 day);
error DepositsAreClosed();
error Replaced();
error TokenPaused();
error NotPauser();
error NothingToSweep();
error NoQuarantine();
error NotGovernance();
error InvestorNotFrozen(address investor);
error NoLegalRef();
error NothingToRescue();
error UseSweepUnrecorded();
error IsHeld(address investor);
error BadQuarantine(address quarantine);
error TooManyTranches(address investor);
error TooLarge();
error PricePublished(address investor, uint256 opsMayReleaseAt);
error NothingDone();
modifier onlyOps() {
if (msg.sender != ops) revert NotOps();
_;
}
constructor(
IERC20 usdc_,
AllowlistRegistry registry_,
address destination_,
address ops_,
ISeriesDirectory directory_,
AttestationAnchor anchor_,
ProductToken token_
) {
if (address(usdc_) == address(0) || address(registry_) == address(0)) revert ZeroAddress();
if (destination_ == address(0) || ops_ == address(0) || address(directory_) == address(0)) {
revert ZeroAddress();
}
if (address(anchor_) == address(0) || address(token_) == address(0)) revert ZeroAddress();
usdc = usdc_;
registry = registry_;
destination = destination_;
ops = ops_;
directory = directory_;
anchor = anchor_;
token = token_;
}
// ── Investor ────────────────────────────────────────────────────────────────────────────
/// @notice Place USDC for allocation. Requires prior `approve` on the USDC contract.
function deposit(uint256 amount) external {
_live();
if (amount == 0) revert ZeroAmount();
if (!registry.isAllowed(msg.sender)) revert NotAllowed(msg.sender);
// new money would only join a deposit nobody can return or allocate (review of 30c, R-01)
if (held[msg.sender]) revert IsHeld(msg.sender);
uint16 entryBps = IEntryFee(directory.parameters()).entryBpsOf(address(token));
_note(msg.sender, amount, anchor.dealingDayFor(token.series()), entryBps, false, 0);
usdc.safeTransferFrom(msg.sender, address(this), amount);
emit Deposited(msg.sender, amount);
}
/// @notice Place the proceeds of a switch in the holder's name. Only the redemption queue of the day may
/// do this, and only with what that holder's own redemption paid: it is how a holder moves between
/// series without the money leaving the platform. `dealDay` is the day the redemption was settled
/// at, so the money deals here at the same day's price; `topUp` is what an exit would have cost
/// above the switch fee paid, withheld if the money is returned instead of allocated.
function depositFor(address investor, uint256 amount, uint32 dealDay, uint256 topUp) external {
if (msg.sender != registry.redemptionSink()) revert NotQueue();
_live();
if (amount == 0) revert ZeroAmount();
if (!registry.isAllowed(investor)) revert NotAllowed(investor);
if (held[investor]) revert IsHeld(investor); // the queue skips such a switch before it pays
_note(investor, amount, dealDay, 0, true, topUp > amount ? amount : topUp);
usdc.safeTransferFrom(msg.sender, address(this), amount);
emit Deposited(investor, amount);
}
/// @dev Deposits are taken only by the escrow the directory names for the series now, and only while open:
/// a replaced escrow can no longer issue, so it takes no money (the audit's G03).
function _live() private view {
if (!depositsOpen) revert DepositsAreClosed();
if (directory.escrowOf(address(token)) != address(this)) revert Replaced();
}
/// @dev Record an amount as a tranche: it joins the investor's newest tranche when the dealing day, the
/// terms and the origin are the same, else it opens one.
function _note(address investor, uint256 amount, uint32 dealDay, uint16 entryBps, bool switched, uint256 topUp)
private
{
if (amount > type(uint128).max) revert TooLarge();
Tranche[] storage T = _tranches[investor];
uint16 lockDays = token.lockDays();
uint16 penaltyBps = token.penaltyBps();
deposited[investor] += amount;
totalDeposited += amount;
emit TrancheNoted(investor, amount, dealDay, switched);
if (T.length != 0) {
Tranche storage last = T[T.length - 1];
if (
last.dealDay == dealDay && last.entryBps == entryBps && last.lockDays == lockDays
&& last.penaltyBps == penaltyBps && last.switched == switched
) {
last.amount += uint128(amount);
last.topUp += uint128(topUp);
return;
}
}
if (T.length >= MAX_TRANCHES) revert TooManyTranches(investor);
T.push(Tranche(uint128(amount), dealDay, entryBps, lockDays, penaltyBps, switched, uint128(topUp)));
}
// ── Operations ──────────────────────────────────────────────────────────────────────────
/// @notice Stop taking deposits — the escrow is being replaced, or something is wrong. Easy to do:
/// the operations Safe or the token's sentinel. Returns stay possible.
function closeDeposits() external {
if (msg.sender != ops && msg.sender != token.sentinel()) revert NotPauser();
depositsOpen = false;
emit DepositsClosed(msg.sender);
}
/// @notice The directory closes a replaced escrow: it can no longer issue, so it takes no more money.
function closeByDirectory() external {
if (msg.sender != address(directory)) revert NotDirectory();
depositsOpen = false;
emit DepositsClosed(msg.sender);
}
/// @notice Take deposits again. The operations Safe only.
function openDeposits() external onlyOps {
// a replaced escrow stays closed: it cannot issue, so it must not take money (review of 28.09.2026, G-03)
if (directory.escrowOf(address(token)) != address(this)) revert Replaced();
depositsOpen = true;
emit DepositsOpened(msg.sender);
}
/// @notice An investor's tranches, oldest first.
/// @notice Whether a switch of `investor` dealing on `dealDay` has room here — a free slot, or a newest
/// tranche it would join, exactly as `depositFor` would decide: the queue asks before it pays a
/// switch in, so a full list is a reason on record and not a payment that fails (audit of
/// 05.10.2026, P-05; its follow-up, I-01b: a switch that merges needs no slot).
function hasRoomFor(address investor, uint32 dealDay) external view returns (bool) {
Tranche[] storage T = _tranches[investor];
if (T.length < MAX_TRANCHES) return true;
Tranche storage last = T[T.length - 1];
return last.switched && last.dealDay == dealDay && last.entryBps == 0 && last.lockDays == token.lockDays()
&& last.penaltyBps == token.penaltyBps();
}
function tranchesOf(address investor) external view returns (Tranche[] memory) {
return _tranches[investor];
}
/// @notice What of an investor's deposit deals at the price of the latest anchored day: every tranche
/// placed before that day's cut-off.
function dealableOf(address investor) public view returns (uint256 sum) {
uint32 latest = anchor.latestDayOf(token.series());
if (latest == 0) return 0;
uint32 n = anchor.dayNumberOf(latest);
Tranche[] storage T = _tranches[investor];
for (uint256 i = 0; i < T.length; i++) {
if (T[i].dealDay <= n) sum += T[i].amount;
}
}
/// @notice Move what nobody deposited — the balance above what depositors are owed and the fees that wait
/// for the treasury — to the directory's quarantine address. Cannot reach a cent of any
/// depositor's money; refused while no quarantine is set.
function sweepUnrecorded() external onlyOps {
address to = _quarantine();
uint256 excess = usdc.balanceOf(address(this)) - totalDeposited - feesDue;
if (excess == 0) revert NothingToSweep();
usdc.safeTransfer(to, excess);
emit Swept(excess, to, msg.sender);
}
/// @notice Move a deposit to quarantine under a court or police order: governance only — the timelock, so
/// the order is public for the timelock's delay before it takes effect — and only the deposit of an
/// investor the registry no longer allows (frozen or removed): an investor in good standing keeps
/// their money. The destination is the directory's quarantine, never an address named in the call;
/// the quarantine itself is governance's to set, through the timelock, so a governance quorum gone
/// bad could name a Safe of its own and seize into it — visible for the timelock's delay, which is
/// the protection (AUDIT-PACK §12). `legalRef` is a reference on record, not a proof of the order:
/// the contract cannot check a court's decision, nor a total across several seizures under one
/// reference. Compliance hands the money on from the quarantine as the order says. The accounting
/// is that of `release`: the newest money goes first, and what the escrow owes in total falls by
/// the same amount — so a sweep can never reach another depositor's money. Of switched money the
/// difference to the exit fee is the treasury's, as on a return: it is paid there, not to the
/// quarantine (audit of 13.10.2026, E-10); `amount` is what left the deposit, the quarantine
/// receives it less that difference, shown in `FeeCollected("exit", …)` of the same call.
function seize(address investor, uint256 amount, bytes32 legalRef) external {
if (msg.sender != directory.governance()) revert NotGovernance();
if (legalRef == bytes32(0)) revert NoLegalRef();
if (registry.isAllowed(investor)) revert InvestorNotFrozen(investor);
address to = _quarantine();
uint256 topUp = _takeBack(investor, amount, false);
usdc.safeTransfer(to, amount - topUp);
if (topUp != 0) _payFee(topUp, "exit", legalRef);
emit Seized(investor, amount, to, legalRef);
}
/// @notice Move a token other than USDC that reached the escrow — nobody's, the escrow takes no other
/// token — to the directory's quarantine, where compliance decides. USDC above what depositors are
/// owed goes by `sweepUnrecorded`, which cannot reach a depositor's cent; USDC is refused here.
function rescue(IERC20 stray) external onlyOps {
if (address(stray) == address(usdc)) revert UseSweepUnrecorded();
address to = _quarantine();
uint256 amount = stray.balanceOf(address(this));
if (amount == 0) revert NothingToRescue();
stray.safeTransfer(to, amount);
emit Rescued(address(stray), amount, to, msg.sender);
}
/// @notice Put a legal hold on an investor's deposit in this escrow: from now on it is neither returned nor
/// allocated, whoever asks, and takes no new money, until governance lifts the hold; a seizure still
/// moves it. The operations Safe sets it at once — the order arrives and the money stops the same
/// hour; governance may set it too, through the timelock like everything governance does. Lifted
/// only by governance: easy to set, hard to lift, like the pause — so a hold set by mistake keeps
/// the money at least for the timelock's delay. The hold is this escrow's: an investor with money
/// in several escrows (another series, a replaced escrow) is held in each separately, and a full
/// seizure does not lift it.
function hold(address investor, bytes32 ref) external {
if (msg.sender != ops && msg.sender != directory.governance()) revert NotOps();
if (ref == bytes32(0)) revert NoLegalRef();
held[investor] = true;
emit Held(investor, msg.sender, ref);
}
/// @notice Lift a legal hold. Governance only, with the reference of the decision that lifts it.
function liftHold(address investor, bytes32 ref) external {
if (msg.sender != directory.governance()) revert NotGovernance();
if (ref == bytes32(0)) revert NoLegalRef();
held[investor] = false;
emit HoldLifted(investor, ref);
}
/// @dev Where anything nobody is owed goes: the directory's quarantine — the one in force now, whichever
/// queue serves the contour (the audit's G07) — set, and never this escrow itself: a transfer to
/// oneself would erase a debt without moving a cent (review of 30.09.2026, L-17).
function _quarantine() private view returns (address to) {
to = directory.quarantine();
if (to == address(0)) revert NoQuarantine();
if (to == address(this)) revert BadQuarantine(to);
}
/// @notice Return money to its investor: at their request, when a subscription is declined, when the
/// escrow is being replaced — the operations Safe's decision, for an investor the registry allows.
/// For an investor it no longer allows — frozen or removed — a return is itself a decision on an
/// order (a licence, a mistaken freeze): governance's, through the timelock (review of 30.09.2026,
/// Q-01: a frozen deposit could otherwise leave while a seizure waited out the delay). A deposit
/// under a legal hold is returned by nobody until governance lifts the hold. It goes to the
/// investor's own address and nowhere else; the amount is theirs to begin with, so this is a
/// release, not a payment. The newest money goes back first — what waits for a later day before
/// what is ready to deal (review of 28.09.2026, L-13). Of money that came by a switch, the
/// difference to the exit fee is withheld for the treasury (G06). The `reason` is logged.
/// @notice A subscription is not a free option on a public price (audit of 13.10.2026, E-2): the mirror of
/// the queue's cancel rule. The operations Safe may return a tranche only while no price from its
/// first dealing day on is anchored — the money cannot have seen its price — or once it has waited
/// `OPS_RELEASE_AFTER` past that day's cut-off unallocated. In between a return would be the
/// depositor's option on a price already public, handed back through the operator: there only
/// governance returns, through the timelock. A replaced escrow is free of the rule — nothing in
/// it can be allocated any more, so its money is only ever returned — and so is a seizure.
function release(address investor, uint256 amount, bytes32 reason) external {
address gov = directory.governance();
if (msg.sender != ops && msg.sender != gov) revert NotOps();
if (held[investor]) revert IsHeld(investor);
if (msg.sender != gov && !registry.isAllowed(investor)) revert NotGovernance();
bool guarded = msg.sender != gov && directory.escrowOf(address(token)) == address(this);
uint256 topUp = _takeBack(investor, amount, guarded);
usdc.safeTransfer(investor, amount - topUp);
if (topUp != 0) _payFee(topUp, "exit", reason);
emit Released(investor, amount, reason);
}
/// @notice What of an investor's deposit the operations Safe may return right now under the rule of
/// `release`: the newest tranches up to the first that has seen its price and not yet waited
/// `OPS_RELEASE_AFTER` — a return takes the newest money first, so nothing behind that one is
/// reachable either. Everything, for a replaced escrow.
function opsReleasableOf(address investor) external view returns (uint256 sum) {
Tranche[] storage T = _tranches[investor];
if (directory.escrowOf(address(token)) != address(this)) return deposited[investor];
uint32 latestN = _latestDayNumber();
for (uint256 i = T.length; i > 0; i--) {
if (_opsMayReturnAt(T[i - 1], latestN) > block.timestamp) return sum;
sum += T[i - 1].amount;
}
}
/// @dev The number of the latest day anchored for the series, zero while none is.
function _latestDayNumber() private view returns (uint32) {
uint32 latest = anchor.latestDayOf(token.series());
return latest == 0 ? 0 : anchor.dayNumberOf(latest);
}
/// @dev From when the operations Safe may return a tranche: now, while no price from its dealing day on is
/// public; else `OPS_RELEASE_AFTER` past the cut-off of that day.
function _opsMayReturnAt(Tranche storage t, uint32 latestN) private view returns (uint256) {
if (latestN == 0 || latestN < t.dealDay) return 0;
return uint256(t.dealDay) * 1 days + anchor.cutOffOn(t.dealDay) + OPS_RELEASE_AFTER;
}
/// @dev Take `amount` off an investor's tranches, newest first; what of it is the withheld part of
/// switched money. The escrow owes that much less. `guarded` holds every tranche touched to the rule
/// of `release` for the operations Safe (E-2).
function _takeBack(address investor, uint256 amount, bool guarded) private returns (uint256 topUp) {
if (amount == 0) revert ZeroAmount();
uint256 available = deposited[investor];
if (amount > available) revert InsufficientDeposit(amount, available);
deposited[investor] = available - amount;
totalDeposited -= amount;
Tranche[] storage T = _tranches[investor];
uint256 left = amount;
uint32 latestN = guarded ? _latestDayNumber() : 0;
while (left != 0) {
Tranche storage t = T[T.length - 1];
if (guarded) {
uint256 at = _opsMayReturnAt(t, latestN);
if (at > block.timestamp) revert PricePublished(investor, at);
}
uint256 piece = t.amount < left ? t.amount : left;
uint256 part = (uint256(t.topUp) * piece) / t.amount;
topUp += part;
left -= piece;
if (piece == t.amount) {
T.pop();
} else {
t.amount -= uint128(piece);
t.topUp -= uint128(part);
}
}
}
/// @dev A fee to the treasury. If the transfer is refused the fee waits here instead of failing the
/// dealing it was taken in (B-10).
function _payFee(uint256 amount, bytes32 kind, bytes32 ref) private {
(bool ok, bytes memory ret) =
address(usdc).call(abi.encodeCall(IERC20.transfer, (directory.feeRecipient(), amount)));
if (ok && (ret.length == 0 || (ret.length == 32 && abi.decode(ret, (bool))))) {
emit FeeCollected(kind, address(token), amount, ref);
} else {
feesDue += amount;
emit FeeDeferred(kind, amount, ref);
}
}
/// @notice Pay the treasury the fees that had to wait. The operations Safe, once the treasury can receive.
function payFees(bytes32 ref) external onlyOps {
uint256 amount = feesDue;
if (amount == 0) revert ZeroAmount();
feesDue = 0;
usdc.safeTransfer(directory.feeRecipient(), amount);
emit FeeCollected("deferred", address(token), amount, ref);
}
/// @notice Allocation: move parts of investors' deposits to `destination` and issue their units. The
/// price is the one anchored for `day`, which must be the latest day anchored for the series —
/// dealing always happens at the newest published price, never at an older one — and only money
/// placed before that day's cut-off takes part. Each amount pays the entry fee (the lower of the
/// one in force when it was placed and the one in force now; nothing for switched money) to the
/// treasury; the rest goes to `destination` and buys floor(net × 1e6 ÷ price) units.
/// @dev A batch is prepared from the escrow as it stood, signed later and executed later still. An
/// investor whose money was returned meanwhile is allocated what is left, or skipped when
/// nothing is; one no longer allowed is skipped. Each is said in a `Skipped` event — the batch does not fail
/// because one person changed their mind (the mirror of the queue's settlement). A batch in which no
/// line went through reverts `NothingDone` (E-5).
function allocate(address[] calldata investors, uint256[] calldata amounts, uint32 day, bytes32 batchId)
external
onlyOps
{
if (investors.length != amounts.length) revert LengthMismatch();
if (token.paused()) revert TokenPaused(); // nothing would issue: say so, rather than skip every line (G-05)
Dealing memory d;
d.feeBps = IEntryFee(directory.parameters()).entryBpsOf(address(token));
if (d.feeBps > MAX_FEE_BPS) revert FeeTooHigh(d.feeBps);
d.price = _priceOf(day);
d.dayNumber = anchor.dayNumberOf(day);
d.batchId = batchId;
for (uint256 i = 0; i < investors.length; i++) {
if (amounts[i] == 0) revert ZeroAmount(); // a malformed batch, not a line to skip
// one line that cannot be allocated — a cap, a lot limit, a rounding to nothing — is skipped, the
// rest of the batch goes through (F-08); the line itself runs as a call so its revert is contained
try this.allocateOne(investors[i], amounts[i], d) returns (uint256 amt, uint256 fee, uint256 u) {
d.total += amt;
d.fees += fee;
d.units += u;
} catch (bytes memory err) {
emit Skipped(investors[i], "failed", batchId);
emit LineFailed(investors[i], batchId, err);
}
}
// a batch that allocated nothing — every line skipped or failed — is a failure, not a dealing of nought:
// the Safe transaction fails and says so, instead of a `Dealt` of zeros under a green tick (E-5)
if (d.total == 0) revert NothingDone();
totalDeposited -= d.total;
usdc.safeTransfer(destination, d.total - d.fees);
// to the treasury, never to the operations Safe: the fee is ALCUM's the moment it is taken
if (d.fees != 0) _payFee(d.fees, "entry", batchId);
emit Dealt(day, d.price, d.total, d.fees, d.units, batchId);
}
/// @dev What one dealing shares across its lines, and adds up.
struct Dealing {
uint16 feeBps;
uint32 dayNumber;
uint256 price;
bytes32 batchId;
uint256 total;
uint256 fees;
uint256 units;
}
/// @dev The anchored price of `day`, which has to be the latest day anchored for this series.
function _priceOf(uint32 day) private view returns (uint256 price) {
bytes32 series = token.series();
uint32 latest = anchor.latestDayOf(series);
if (day != latest) revert NotLatestDay(day, latest);
// the latest day, but not for ever: a price older than the anchor's age is no price (M-05)
if (anchor.isStale(series)) revert PriceStale(day);
price = anchor.dealingPrice(series, day);
if (price == 0) revert NoPrice(day);
}
/// @dev One line of an allocation, callable only by this contract from `allocate` (so that its revert is
/// contained). Returns what it moved: the amount, the fee taken from it, the units issued.
function allocateOne(address investor, uint256 amount, Dealing calldata d)
external
returns (uint256 taken, uint256 fee, uint256 units)
{
if (msg.sender != address(this)) revert NotOps();
if (deposited[investor] == 0) {
emit Skipped(investor, "released", d.batchId);
return (0, 0, 0);
}
if (!registry.isAllowed(investor)) {
emit Skipped(investor, "not-allowed", d.batchId);
return (0, 0, 0);
}
if (held[investor]) {
emit Skipped(investor, "held", d.batchId);
return (0, 0, 0);
}
(taken, fee, units) = _deal(investor, amount, d);
// money placed after the day's cut-off waits for the next day's price (forward pricing, F-03, A-02);
// what was placed before it deals now, whatever came after (G-01)
if (taken == 0) {
emit Skipped(investor, "after-cut-off", d.batchId);
return (0, 0, 0);
}
deposited[investor] -= taken;
emit Allocated(investor, taken, d.batchId);
}
/// @dev The running state of one line: what it has taken, and the run of money waiting to be issued on
/// one set of lock-up terms.
struct Line {
uint256 taken;
uint256 fee;
uint256 units;
uint256 net;
uint16 lock;
uint16 pen;
uint256 keep;
}
/// @dev Walk an investor's tranches, oldest first, taking up to `amount` from those that deal at this day:
/// each pays its own entry fee, and what shares the same lock-up terms is issued as one lot.
function _deal(address investor, uint256 amount, Dealing calldata d) private returns (uint256, uint256, uint256) {
Tranche[] storage T = _tranches[investor];
Line memory l;
uint256 n = T.length;
for (uint256 i = 0; i < n; i++) {
Tranche memory t = T[i];
if (t.dealDay <= d.dayNumber && l.taken < amount) {
uint256 piece = t.amount < amount - l.taken ? t.amount : amount - l.taken;
uint256 f = (piece * (t.entryBps < d.feeBps ? t.entryBps : d.feeBps)) / 10_000;
if (l.net != 0 && (t.lockDays != l.lock || t.penaltyBps != l.pen)) {
l.units += _issue(investor, l.net, l.lock, l.pen, d);
l.net = 0;
}
l.lock = t.lockDays;
l.pen = t.penaltyBps;
l.net += piece - f;
l.taken += piece;
l.fee += f;
// what was allocated is no longer money that could be returned: its share of the top-up lapses
t.topUp -= uint128((uint256(t.topUp) * piece) / t.amount);
t.amount -= uint128(piece);
}
if (t.amount != 0) T[l.keep++] = t;
}
while (T.length > l.keep) {
T.pop();
}
if (l.net != 0) l.units += _issue(investor, l.net, l.lock, l.pen, d);
return (l.taken, l.fee, l.units);
}
/// @dev Issue what `net` buys at the day's price. A run that rounds to nothing fails the line: the batch
/// skips it and says so.
function _issue(address investor, uint256 net, uint16 lock, uint16 pen, Dealing calldata d)
private
returns (uint256 u)
{
u = (net * 1e6) / d.price;
if (u == 0) revert ZeroAmount();
token.mint(investor, u, d.price, lock, pen, d.batchId);
}
}
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;
}
}
src/AttestationAnchor.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @title AttestationAnchor — the daily valuation, fixed in time
/// @notice One hash per series per day: the SHA-256 of the canonical JSON of that day's signed
/// attestation. It proves when a figure was published and that it has not changed since. The
/// first hash written for a day is the one that stands — writing it again with the same value
/// changes nothing, and writing a different one is refused. Nobody, including governance, can
/// overwrite a day that has been anchored.
/// @notice Beside the hash, the day's dealing price: the unit price the escrow issues at and the queue
/// redeems at. It is written once with the hash, before any dealing uses it, and neither the
/// operations Safe nor anyone else can deal at another price. A price may not sit further than
/// `priceBandBps` from the last one anchored for the series, nor further than `wideBandBps` from the
/// price of five business days earlier: a stolen anchorer key can nudge a day's price, not invent
/// one, and cannot walk it a step a day either; governance widens a band, with notice, if the world
/// moves (audit of 13.10.2026, E-8).
/// @dev Anchoring happens every business day without a human, so it cannot sit behind a Safe quorum.
/// It is given to a single `anchorer` key instead, whose entire power is to write 32 bytes once
/// per day per series. That key moves nothing and can undo nothing; the worst it can do is
/// anchor a wrong hash for a day that has not been anchored yet, which is visible immediately
/// against the published attestation. Governance can replace it at any time.
/// @notice The dealing cut-off lives here too (owner, 04.10.2026): money and requests received before
/// `cutOff` (seconds after 00:00 UTC, 13:00 by default) of a day take part in that day's dealing,
/// later ones in the next. A day is anchored only once its cut-off has passed, so nothing deals at
/// a price that was public when it was placed (review of 02.10.2026, A-02; the audit's G08).
/// @notice Anchoring can be paused — by the sentinel, the operations Safe, any one of its owners, or
/// governance — and only governance resumes it. While paused nothing is anchored and the latest
/// price is no price to deal at: a stolen anchorer key is stopped the hour it is noticed, not after
/// the timelock (review of 03.10.2026, B-03).
/// @dev The one Safe view the anchor relies on: any Safe owner may pause alone.
interface ISafeOwner {
function isOwner(address owner) external view returns (bool);
}
contract AttestationAnchor {
/// @notice Governance (the Governance Safe behind the timelock): replaces the anchorer, sets the band, the
/// price age and the cut-off, and resumes after a pause. It cannot rewrite an anchored day.
address public immutable governance;
/// @notice The key that writes the daily hashes.
address public anchorer;
/// @notice The Operations Safe: it, and any one of its owners, may pause anchoring.
address public immutable ops;
/// @notice The one key that may live on a server and only pauses. Governance names it.
address public sentinel;
/// @notice No anchoring and no dealing at the latest price while set.
bool public paused;
/// @dev The dealing cut-off, in seconds after 00:00 UTC, of the days before `cutOffFromDay`; and the one
/// of that day and every day after it. A change never touches the day it is made on: the schedule a
/// day was dealt and anchored under is the one it began with (audit of 05.10.2026, M-01, P-06).
uint32 private _cutOffBefore = 13 hours;
uint32 private _cutOffFrom = 13 hours;
/// @notice The first day (days since 1970-01-01) the cut-off last set applies to.
uint32 public cutOffFromDay;
/// @notice series → the last month (YYYYMM) that has a later month anchored after it, and the price of its
/// last anchored day: what a month closed at, for the monthly crystallisation of the performance
/// fee (review of 03.10.2026, B-11).
mapping(bytes32 => uint32) public closedMonth;
mapping(bytes32 => uint256) public closedPrice;
/// @notice series → month → the price that month closed at: every close is kept, not only the last, so
/// a close nobody acted on before the next one is not lost (audit of 05.10.2026, M-02).
mapping(bytes32 => mapping(uint32 => uint256)) public closedPriceOf;
/// @notice series → a closed month (zero: before the first) → the month that closed next after it; zero
/// while none has. The closes of a series in the order they happened.
mapping(bytes32 => mapping(uint32 => uint32)) public nextClosedAfter;
/// @notice keccak256(series, day) → the hash anchored for that day.
mapping(bytes32 => bytes32) public anchorOf;
/// @notice keccak256(series, day) → the dealing price of that day, micro-USDC per unit.
mapping(bytes32 => uint256) public priceOf;
/// @notice series → the latest day anchored, the only day dealing may use.
mapping(bytes32 => uint32) public latestDayOf;
/// @notice series → the price of the latest day, the band's reference.
mapping(bytes32 => uint256) public latestPriceOf;
/// @notice The fast band: how far a day's price may sit from the band's reference, in basis points (10 %).
/// Never off, never wider than `MAX_BAND_BPS` (audit of 13.10.2026, E-8).
uint16 public priceBandBps = 1_000;
/// @notice The slow band: how far a day's price may sit from the price the series stood at five business
/// days earlier — the latest record at least `WIDE_BAND_DAYS` business days before the day being
/// anchored, when there is one — in basis points (25 %). The fast band bounds one step; this bounds
/// a walk: a stolen key stepping the fast band every day is refused on chain by the third step,
/// where before it could compound ten per cent a day until somebody paused (E-8).
uint16 public wideBandBps = 2_500;
/// @notice The slow band's distance, in business days (Monday to Friday by the day's number; the contract
/// knows weekends, not holidays — a holiday only moves the reference one record further back).
uint32 public constant WIDE_BAND_DAYS = 5;
/// @notice The widest either band may be set to: half the price, either way.
uint16 public constant MAX_BAND_BPS = 5_000;
/// @dev series → every day anchored for it, YYYYMMDD, in the order they were written: strictly rising, so
/// the slow band's reference is a binary search, never a scan.
mapping(bytes32 => uint32[]) private _anchoredDays;
/// @notice The band's reference per series: the last price that had stood for at least `BAND_STEP`
/// before the next was written — not simply the last record. Days anchored in a burst (a
/// backfill after an outage) are all measured against the price the world last dealt at, so
/// a stolen key cannot compound the band eight times in one transaction (review of 27.09.2026, M-06).
mapping(bytes32 => uint256) public bandRefPrice;
mapping(bytes32 => uint64) public bandRefAt;
uint64 public constant BAND_STEP = 20 hours;
/// @notice series → when its latest day was anchored; with `maxPriceAge` it says whether the latest
/// price may still be dealt at. A day may not be used for ever when the agent falls silent
/// (review of 27.09.2026, M-05). Governance sets the age, within a month; five days by default
/// cover a Friday's price until Tuesday with a Monday holiday.
mapping(bytes32 => uint64) public latestAnchoredAt;
/// @notice series → Σ price × seconds over every stretch a price stood, up to the latest record: the
/// published trajectory as an integral, so what accrues on NAV over time is read off the record
/// and never off the two ends of an interval somebody chose (review of 28.09.2026, M-15).
mapping(bytes32 => uint256) public priceSeconds;
/// @notice series → until when its latest price counts in the integral: the end of its valuation day plus
/// the price age in force when it was anchored. Fixed with the record, so a later change of the age
/// reaches only later records and the integral never runs backwards (re-check of 05d: shortening
/// the age used to take back a stretch the fee ledger had already charged). Whether the price may
/// be dealt at is `isStale`, which reads the age in force now.
mapping(bytes32 => uint64) public countsUntil;
uint32 public maxPriceAge = 5 days;
uint32 public constant MAX_PRICE_AGE = 30 days;
/// @notice series → the price the series launches at: the band's reference for its first record. Set
/// by governance, or by whoever deployed this contract within a day of it (the deployment run);
/// without it nothing is anchored, so the first price of a series is never the anchorer's to
/// invent (review of 27.09.2026, E-02).
mapping(bytes32 => uint256) public launchPriceOf;
address public immutable initialiser;
uint64 public immutable initialiserUntil;
event Anchored(
bytes32 indexed series, uint32 indexed day, bytes32 attestationHash, uint256 priceMicro, address indexed by
);
event AnchorerSet(address indexed anchorer);
event PriceBandSet(uint16 bps);
event WideBandSet(uint16 bps);
event MaxPriceAgeSet(uint32 seconds_);
event LaunchPriceSet(bytes32 indexed series, uint256 priceMicro);
event CutOffSet(uint32 seconds_, uint32 fromDay);
event SentinelSet(address indexed sentinel);
event Paused(address indexed by);
event Unpaused();
event BandReferenceSet(bytes32 indexed series, uint256 priceMicro);
event MonthClosed(bytes32 indexed series, uint32 indexed month, uint256 priceMicro);
error NotAnchorer();
error NotGovernance();
error ZeroAddress();
error ZeroHash();
error DayInvalid(uint32 day);
error DayInFuture(uint32 day, uint32 latest);
error AlreadyAnchored(bytes32 series, uint32 day, bytes32 existing);
error DayNotAfterLatest(uint32 day, uint32 latest);
error ZeroPrice();
error PriceOutOfBand(uint256 priceMicro, uint256 lastPriceMicro, uint16 bandBps);
error PriceOutOfWideBand(uint256 priceMicro, uint256 refPriceMicro, uint16 bandBps);
error BandInvalid(uint16 bps);
error PriceAgeInvalid(uint32 seconds_);
error NoLaunchPrice(bytes32 series);
error LaunchPriceSet_(bytes32 series);
error PriceTooLarge(uint256 priceMicro);
error BeforeCutOff(uint32 day);
error CutOffInvalid(uint32 seconds_);
error IsPaused();
error NotPauser();
constructor(address governance_, address anchorer_, address ops_, address sentinel_) {
if (governance_ == address(0) || anchorer_ == address(0) || ops_ == address(0)) revert ZeroAddress();
governance = governance_;
anchorer = anchorer_;
ops = ops_;
sentinel = sentinel_;
emit SentinelSet(sentinel_);
emit CutOffSet(_cutOffFrom, 0);
initialiser = msg.sender;
initialiserUntil = uint64(block.timestamp + 1 days);
emit AnchorerSet(anchorer_);
emit PriceBandSet(priceBandBps);
emit WideBandSet(wideBandBps);
}
/// @notice The key of a day in storage; also what a reader recomputes to check an anchor.
function keyOf(bytes32 series, uint32 day) public pure returns (bytes32) {
return keccak256(abi.encode(series, day));
}
/// @notice The price dealing uses for `series` on `day`: zero if the day is not anchored.
function dealingPrice(bytes32 series, uint32 day) external view returns (uint256) {
return priceOf[keyOf(series, day)];
}
/// @notice Whether the latest price of `series` is too old to deal at: the age counts from the end of
/// the valuation day itself, not from when it was written, so a late record of an old day is
/// as old as its day (review of 27.09.2026, E-01).
function isStale(bytes32 series) external view returns (bool) {
uint32 latest = latestDayOf[series];
if (latest == 0 || paused) return true;
return block.timestamp > startOf(latest) + 1 days + maxPriceAge;
}
/// @notice The dealing cut-off of today, in seconds after 00:00 UTC.
function cutOff() external view returns (uint32) {
return cutOffOn(uint32(block.timestamp / 1 days));
}
/// @notice The dealing cut-off of the day numbered `dayNumber` (days since 1970-01-01).
function cutOffOn(uint32 dayNumber) public view returns (uint32) {
return dayNumber >= cutOffFromDay ? _cutOffFrom : _cutOffBefore;
}
/// @notice The number (days since 1970-01-01) of the first day whose cut-off lies after `timestamp`: the
/// dealing day that money or a request placed at `timestamp` first takes part in.
function dealingDayAt(uint256 timestamp) public view returns (uint32) {
uint32 d = uint32(timestamp / 1 days);
return timestamp < uint256(d) * 1 days + cutOffOn(d) ? d : d + 1;
}
/// @notice The dealing day money or a request of `series` placed now first takes part in: the day by the
/// cut-off, and never a day the series already has a price for — whatever the schedule says,
/// nothing is placed onto a price that is public (audit of 05.10.2026, M-01).
function dealingDayFor(bytes32 series) external view returns (uint32 d) {
d = dealingDayAt(block.timestamp);
uint32 latest = latestDayOf[series];
if (latest != 0) {
uint32 next = dayNumberOf(latest) + 1;
if (next > d) d = next;
}
}
/// @notice The number of a YYYYMMDD day, comparable with `dealingDayAt`.
function dayNumberOf(uint32 day) public pure returns (uint32) {
return uint32(startOf(day) / 1 days);
}
/// @notice The Unix timestamp at which a YYYYMMDD day begins (UTC), the inverse of `todayOf`.
function startOf(uint32 day) public pure returns (uint256) {
// civil date → days since 1970-01-01, Howard Hinnant's algorithm
uint256 y = day / 10_000;
uint256 m = (day / 100) % 100;
uint256 d = day % 100;
if (m == 0 || m > 12 || d == 0 || d > 31) return 0;
if (m <= 2) y -= 1;
uint256 era = y / 400;
uint256 yoe = y - era * 400;
uint256 doy = (153 * (m > 2 ? m - 3 : m + 9) + 2) / 5 + d - 1;
uint256 doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
return (era * 146_097 + doe - 719_468) * 1 days;
}
/// @notice Record the day's attestation hash and dealing price. `day` is the valuation day as
/// YYYYMMDD, so a log is readable without a decoder. Days are anchored in order: a day before
/// the latest one is refused, so the latest day is always the newest price.
function anchor(bytes32 series, uint32 day, bytes32 attestationHash, uint256 priceMicro) external {
if (msg.sender != anchorer) revert NotAnchorer();
if (paused) revert IsPaused();
if (attestationHash == bytes32(0)) revert ZeroHash();
if (priceMicro == 0) revert ZeroPrice();
if (priceMicro > type(uint128).max) revert PriceTooLarge(priceMicro);
// A plausible date, not a real calendar: enough to catch a timestamp or a block number arriving
// here by mistake, which would anchor a day that can never be looked up.
if (day < 20_000_101 || day > 99_991_231 || todayOf(startOf(day)) != day) revert DayInvalid(day);
// A day is anchored when it has happened, or at the latest the day after (the key writes at the
// cut-off, and the chain's clock is not ours). Anything further is a key that has been stolen
// trying to spoil days that cannot be repaired — the one thing a stolen key could do here.
// a day is anchored when it has happened, never ahead: a record for tomorrow would deal a day longer
// and shut today's out (review F-09)
uint32 latest = todayOf(block.timestamp);
if (day > latest) revert DayInFuture(day, latest);
// nor before its own cut-off: what was placed between the record and the cut-off would deal at a
// price already public (A-02)
if (block.timestamp < startOf(day) + cutOffOn(dayNumberOf(day))) revert BeforeCutOff(day);
bytes32 key = keyOf(series, day);
bytes32 existing = anchorOf[key];
if (existing != bytes32(0)) {
// Re-anchoring the same values is what a retry looks like; a different value is not a retry.
if (existing != attestationHash || priceOf[key] != priceMicro) {
revert AlreadyAnchored(series, day, existing);
}
return;
}
uint32 newest = latestDayOf[series];
if (day <= newest) revert DayNotAfterLatest(day, newest);
// The reference: the last price that stood before this day's writing began. It moves on only when
// a day's worth of time has passed since it was last set, and then to the latest record — never to
// the record being written — so every record of one burst is measured against the same price.
uint256 ref = bandRefPrice[series];
if (ref == 0) {
// a series' first record is measured against its launch price, and nothing else will do
ref = launchPriceOf[series];
if (ref == 0) revert NoLaunchPrice(series);
bandRefPrice[series] = ref;
bandRefAt[series] = uint64(block.timestamp);
} else if (
block.timestamp - bandRefAt[series] >= BAND_STEP && block.timestamp - latestAnchoredAt[series] >= BAND_STEP
) {
// the latest record becomes the reference only once it has itself stood a step (E-04)
ref = latestPriceOf[series];
bandRefPrice[series] = ref;
bandRefAt[series] = uint64(block.timestamp);
}
{
uint256 diff = priceMicro > ref ? priceMicro - ref : ref - priceMicro;
if (diff * 10_000 > ref * priceBandBps) revert PriceOutOfBand(priceMicro, ref, priceBandBps);
}
// the slow band: against the price of five business days ago, when the series has one (E-8)
(, uint256 slow) = wideBandReference(series, day);
if (slow != 0) {
uint256 diff = priceMicro > slow ? priceMicro - slow : slow - priceMicro;
if (diff * 10_000 > slow * wideBandBps) revert PriceOutOfWideBand(priceMicro, slow, wideBandBps);
}
_anchoredDays[series].push(day);
anchorOf[key] = attestationHash;
priceOf[key] = priceMicro;
// a month that has a later month after it is closed, at the price of its last anchored day
if (newest != 0 && newest / 100 != day / 100) {
nextClosedAfter[series][closedMonth[series]] = newest / 100;
closedPriceOf[series][newest / 100] = latestPriceOf[series];
closedMonth[series] = newest / 100;
closedPrice[series] = latestPriceOf[series];
emit MonthClosed(series, newest / 100, latestPriceOf[series]);
}
// the price that stood until now is added for the time it stood — and no longer than it could be
// dealt at (B-13) — before the new one starts its stretch
if (latestAnchoredAt[series] != 0) {
priceSeconds[series] += latestPriceOf[series] * (_stoodUntil(series) - latestAnchoredAt[series]);
}
latestDayOf[series] = day;
latestPriceOf[series] = priceMicro;
latestAnchoredAt[series] = uint64(block.timestamp);
countsUntil[series] = uint64(startOf(day) + 1 days + maxPriceAge);
emit Anchored(series, day, attestationHash, priceMicro, msg.sender);
}
/// @notice The slow band's reference for anchoring `day` (YYYYMMDD) of `series`: the latest day anchored at
/// least `WIDE_BAND_DAYS` business days before it, and its price; zero while the series has none
/// that old — its first week is held by the fast band and the launch price alone.
function wideBandReference(bytes32 series, uint32 day) public view returns (uint32 refDay, uint256 priceMicro) {
uint32 target = businessDaysBefore(dayNumberOf(day), WIDE_BAND_DAYS);
uint32[] storage list = _anchoredDays[series];
// the last record whose day number is at or before the target: binary search over a rising list
uint256 lo;
uint256 hi = list.length;
while (lo < hi) {
uint256 mid = (lo + hi) / 2;
if (dayNumberOf(list[mid]) <= target) lo = mid + 1;
else hi = mid;
}
if (lo == 0) return (0, 0);
refDay = list[lo - 1];
priceMicro = priceOf[keyOf(series, refDay)];
}
/// @notice How many days have been anchored for a series, and the n-th of them (YYYYMMDD, in order).
function anchoredDayCount(bytes32 series) external view returns (uint256) {
return _anchoredDays[series].length;
}
function anchoredDayAt(bytes32 series, uint256 index) external view returns (uint32) {
return _anchoredDays[series][index];
}
/// @notice Whether a day number (days since 1970-01-01, a Thursday) falls on a Monday to Friday.
function isBusinessDay(uint32 dayNumber) public pure returns (bool) {
return (dayNumber + 3) % 7 < 5;
}
/// @notice The day number `count` business days before `dayNumber`.
function businessDaysBefore(uint32 dayNumber, uint32 count) public pure returns (uint32 n) {
n = dayNumber;
while (count != 0) {
n--;
if (isBusinessDay(n)) count--;
}
}
/// @notice The price integral of a series up to now: Σ price × seconds over the record, the latest price
/// counted to this moment. The difference of two readings is what one unit was worth, in
/// USDC-seconds, over the time between them.
/// A price counts only for as long as it may be dealt at: once it is stale the integral stands
/// still, so nothing accrues on a series whose valuation has stopped (review of 03.10.2026, B-13).
function priceIntegral(bytes32 series) external view returns (uint256) {
uint64 at = latestAnchoredAt[series];
if (at == 0) return 0;
return priceSeconds[series] + latestPriceOf[series] * (_stoodUntil(series) - at);
}
/// @dev Until when the latest price counts: now, or the moment fixed for it when it was anchored, never
/// before it was written. Nothing here moves with a later setting, so the integral only grows.
function _stoodUntil(bytes32 series) private view returns (uint256 end) {
end = countsUntil[series];
if (end > block.timestamp) end = block.timestamp;
uint256 at = latestAnchoredAt[series];
if (end < at) end = at;
}
/// @notice The civil date of a Unix timestamp as YYYYMMDD (proleptic Gregorian, UTC).
function todayOf(uint256 timestamp) public pure returns (uint32) {
// days since 1970-01-01 → civil date, Howard Hinnant's algorithm
int256 z = int256(timestamp / 1 days) + 719_468;
int256 era = (z >= 0 ? z : z - 146_096) / 146_097;
uint256 doe = uint256(z - era * 146_097);
uint256 yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
uint256 doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
uint256 mp = (5 * doy + 2) / 153;
uint256 d = doy - (153 * mp + 2) / 5 + 1;
uint256 m = mp < 10 ? mp + 3 : mp - 9;
uint256 y = uint256(int256(yoe) + era * 400) + (m <= 2 ? 1 : 0);
return uint32(y * 10_000 + m * 100 + d);
}
/// @notice Replace the key that anchors. Governance only; anchored days are untouched.
function setAnchorer(address anchorer_) external {
if (msg.sender != governance) revert NotGovernance();
if (anchorer_ == address(0)) revert ZeroAddress();
anchorer = anchorer_;
emit AnchorerSet(anchorer_);
}
/// @notice Name the band's reference of a series afresh: after a stolen key has written prices, the honest
/// key is measured against the price governance states, not against the forged one (review of
/// 03.10.2026, B-03). Governance only, through the timelock, in one batch with `setAnchorer`.
function setBandReference(bytes32 series, uint256 priceMicro) external {
if (msg.sender != governance) revert NotGovernance();
if (priceMicro == 0) revert ZeroPrice();
if (priceMicro > type(uint128).max) revert PriceTooLarge(priceMicro);
bandRefPrice[series] = priceMicro;
bandRefAt[series] = uint64(block.timestamp);
emit BandReferenceSet(series, priceMicro);
}
/// @notice Stop anchoring, and with it dealing at the latest price. Easy to set: the sentinel, the
/// operations Safe, any one of its owners, or governance.
function pause() external {
bool allowed = msg.sender == sentinel || msg.sender == ops || msg.sender == governance;
if (!allowed) {
(bool ok, bytes memory data) = ops.staticcall(abi.encodeCall(ISafeOwner.isOwner, (msg.sender)));
allowed = ok && data.length >= 32 && abi.decode(data, (bool));
}
if (!allowed) revert NotPauser();
paused = true;
emit Paused(msg.sender);
}
/// @notice Resume. Governance only, with the timelock's notice.
function unpause() external {
if (msg.sender != governance) revert NotGovernance();
paused = false;
emit Unpaused();
}
function setSentinel(address sentinel_) external {
if (msg.sender != governance) revert NotGovernance();
sentinel = sentinel_;
emit SentinelSet(sentinel_);
}
/// @notice Move the dealing cut-off, from the next calendar day (UTC) on. Governance only, with the
/// timelock's notice. Today keeps the cut-off it began with, so neither what was placed today nor
/// today's record is moved across it: an earlier cut-off cannot deal today's money at a price
/// struck before it came, a later one cannot reopen a day whose price is already public (audit of
/// 05.10.2026, M-01, P-06). Money and requests already placed keep the dealing day they were given.
function setCutOff(uint32 seconds_) external {
if (msg.sender != governance) revert NotGovernance();
if (seconds_ >= 1 days) revert CutOffInvalid(seconds_);
uint32 today = uint32(block.timestamp / 1 days);
_cutOffBefore = cutOffOn(today);
_cutOffFrom = seconds_;
cutOffFromDay = today + 1;
emit CutOffSet(seconds_, today + 1);
}
/// @notice The price a series launches at, the reference for its first record. The deployer may set it
/// within a day of this contract's deployment, once; governance may set or replace it at any time
/// until the series' first record — so a wrong value from the deployment is governance's to
/// correct, without touching the band every other series lives under (review of 27.09.2026, L-02).
function setLaunchPrice(bytes32 series, uint256 priceMicro) external {
if (latestDayOf[series] != 0) revert LaunchPriceSet_(series);
if (msg.sender != governance) {
bool deployerInWindow = msg.sender == initialiser && block.timestamp <= initialiserUntil;
if (!deployerInWindow || launchPriceOf[series] != 0) revert NotGovernance();
}
if (priceMicro == 0) revert ZeroPrice();
if (priceMicro > type(uint128).max) revert PriceTooLarge(priceMicro);
launchPriceOf[series] = priceMicro;
emit LaunchPriceSet(series, priceMicro);
}
/// @notice How long the latest price may be dealt at. Governance only, within a month. Dealing follows the
/// new age at once (`isStale`); the integral keeps, for the price already anchored, the age it was
/// anchored under, and takes the new one from the next record on.
function setMaxPriceAge(uint32 seconds_) external {
if (msg.sender != governance) revert NotGovernance();
if (seconds_ == 0 || seconds_ > MAX_PRICE_AGE) revert PriceAgeInvalid(seconds_);
maxPriceAge = seconds_;
emit MaxPriceAgeSet(seconds_);
}
/// @notice Widen or narrow the fast band on the day's price. Governance only, with the timelock's notice.
/// Never off and never past half the price (E-8): a band that can be switched off is no band.
function setPriceBand(uint16 bps) external {
if (msg.sender != governance) revert NotGovernance();
if (bps == 0 || bps > MAX_BAND_BPS) revert BandInvalid(bps);
priceBandBps = bps;
emit PriceBandSet(bps);
}
/// @notice Widen or narrow the slow band, within the same bounds. Governance only, with the timelock's
/// notice: the way through a week in which the world moved more than the band allows.
function setWideBand(uint16 bps) external {
if (msg.sender != governance) revert NotGovernance();
if (bps == 0 || bps > MAX_BAND_BPS) revert BandInvalid(bps);
wideBandBps = bps;
emit WideBandSet(bps);
}
}
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);
}
}
}
}
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.