Verified contractPartialMIT
SeriesDirectory
Address0x1b9cb3e88acc6d917ff5dcddc092f35e004c2df2
- Balance
0 ETH
- Transactions
4
- Compiler
solc 0.8.26
- Same code
Only this 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,049
- Creation transaction
- 0x2226ffd529…44e0ab0a96
19 files
- src/SeriesDirectory.solmain27.36 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/NavFeeLedger.sol32.33 KB
- src/ProductToken.sol43.9 KB
- src/SeriesParameters.sol15.79 KB
- src/SubscriptionEscrow.sol39.8 KB
src/SeriesDirectory.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {AllowlistRegistry} from "./AllowlistRegistry.sol";
import {SubscriptionEscrow} from "./SubscriptionEscrow.sol";
import {AttestationAnchor} from "./AttestationAnchor.sol";
import {ProductToken} from "./ProductToken.sol";
import {SeriesParameters} from "./SeriesParameters.sol";
import {NavFeeLedger} from "./NavFeeLedger.sol";
/// @dev What the directory asks the queue of the day before a series' token is replaced.
interface IQueueDebts {
function pendingUnits(address token) external view returns (uint256);
function feesDue(address token) external view returns (uint256);
}
/// @title SeriesDirectory — which series the contour has, and what each of them is bound to
/// @notice One record per series: the escrow it subscribes through (the token's only minter), the custody
/// its redemptions are paid from, and — for the contour as a whole — where fees go and where doubtful
/// money is swept to. It also keeps what each series has paid out in redemptions, day by day, and
/// enforces the redemption gate on it.
/// @notice The directory is not the redemption queue. Until the review of 04.10.2026 the queue held all of
/// this, so replacing the queue meant new escrows, a second registration of every series and an
/// empty payout history — and the old escrows went on reading the old queue (the audit's G03, G04,
/// G07). Now the queue of the day is whatever the registry names as its redemption sink; the tokens,
/// the escrows and the fee ledger read the directory, which is never replaced. A new queue is one
/// governance act and nothing else changes.
/// @dev Governance changes a record through the timelock; the deployer may register series and name the
/// quarantine within a day of deployment, as before.
contract SeriesDirectory {
IERC20 public immutable usdc;
AllowlistRegistry public immutable registry;
/// @notice The Operations Safe.
address public immutable ops;
/// @notice Governance (the Governance Safe behind the timelock).
address public immutable governance;
/// @notice Where the day's price comes from.
AttestationAnchor public immutable anchor;
/// @notice The tariffs and the gate of every series, set by governance.
SeriesParameters public immutable parameters;
/// @notice What the NAV fees may amount to, per series.
NavFeeLedger public immutable feeLedger;
/// @notice Where USDC that reached an escrow outside `deposit` — nobody's, or somebody's we must not
/// touch — is swept to for compliance to decide. Zero until it is set; no sweep before.
address public quarantine;
/// @notice Where every fee of the contour goes — the Treasury Safe: entry, exit, switch and the NAV fees.
address public feeRecipient;
/// @notice Series token → the escrow that series subscribes through. Zero until the series is added.
mapping(address => address) public escrowOf;
/// @notice Series token → the address its redemptions are paid from: the custody of that series, which
/// holds nothing of any other series. It must have approved the queue of the day.
mapping(address => address) public payerOf;
/// @dev A price series serves one token, and a custody pays for one series: neither can be shared.
mapping(bytes32 => bool) public seriesTaken;
mapping(address => bool) public isPayer;
/// @notice Whether an address is the escrow of a series now: the only switch destinations.
mapping(address => bool) public isSeriesEscrow;
/// @notice Every escrow the directory has ever named, current or replaced: none may become the quarantine.
mapping(address => bool) public wasEscrow;
/// @notice A replaced token → the token that took its series over (`replaceToken`): a switch asked into the
/// old one's escrow lands in the escrow of whoever holds the series now (follow-up audit, L-01b).
mapping(address => address) public successorOf;
/// @notice A price series → the token that holds it now: where any earlier token of the series resolves
/// to in one step, however many replacements lie between (re-check of 05c).
mapping(bytes32 => address) public tokenOfSeries;
/// @notice When a series was registered.
mapping(address => uint256) public registeredAt;
/// @dev Who built the directory, and until when that key may register series (one day).
address public immutable initialiser;
uint64 public immutable initialiserUntil;
/// @dev What a series paid out in redemptions on one day (days since 1970-01-01, UTC), for the gate.
struct Paid {
uint32 day;
uint192 gross;
}
/// @dev By price series, not by token or queue: neither a new queue nor a reissued token starts the
/// window afresh (the audit's G04).
mapping(bytes32 => Paid[]) private _paid;
mapping(bytes32 => uint256) private _paidHead;
event SeriesAdded(address indexed token, address indexed escrow, address indexed payer);
event PayerSet(address indexed token, address indexed payer);
event EscrowSet(address indexed token, address indexed escrow, address indexed replaced);
event FeeRecipientSet(address indexed feeRecipient);
event QuarantineSet(address indexed quarantine);
event PaidOut(address indexed token, uint32 indexed day, uint256 gross);
event TokenReplaced(address indexed replaced, address indexed token, address indexed escrow);
error NotGovernance();
error NotQueue();
error ZeroAddress();
error UnknownSeries(address token);
error SeriesExists(address token);
error TokenMismatch(address token);
error EscrowMismatch(address escrow);
error LedgerMismatch();
error SeriesTaken(bytes32 series);
error PayerTaken(address payer);
error TermsNotSet(address token);
error BadQuarantine(address quarantine);
error GateExceeded(uint256 asked, uint256 remaining);
error SeriesMismatch(bytes32 series);
error NotRetired(address token);
error StillOwes(address token);
error ReissueNotFinished(address token);
error NotPaused(address token);
error UnitsNotCarried(uint256 carried, uint256 outstanding);
error IsRetired(address token);
error ReissueSourceMismatch(address token, address source);
/// @dev Registering a series: governance, or the deployer within a day of deployment (the set is built and
/// registered in one go; after that day the deployer key is powerless here).
modifier onlyGovernanceOrInitialiser() {
if (msg.sender != governance && !(msg.sender == initialiser && block.timestamp <= initialiserUntil)) {
revert NotGovernance();
}
_;
}
modifier onlyGovernance() {
if (msg.sender != governance) revert NotGovernance();
_;
}
constructor(
IERC20 usdc_,
AllowlistRegistry registry_,
address ops_,
address governance_,
AttestationAnchor anchor_,
address feeRecipient_,
SeriesParameters parameters_,
NavFeeLedger feeLedger_
) {
if (
address(usdc_) == address(0) || address(registry_) == address(0) || ops_ == address(0)
|| governance_ == address(0)
) {
revert ZeroAddress();
}
if (address(anchor_) == address(0) || feeRecipient_ == address(0)) revert ZeroAddress();
if (address(parameters_) == address(0) || address(feeLedger_) == address(0)) revert ZeroAddress();
// the ledger reads this set's registry, anchor and parameters, or it bounds nothing of ours (L-14)
if (
feeLedger_.registry() != registry_ || feeLedger_.anchor() != anchor_
|| feeLedger_.parameters() != parameters_
) revert LedgerMismatch();
usdc = usdc_;
registry = registry_;
ops = ops_;
governance = governance_;
anchor = anchor_;
parameters = parameters_;
feeLedger = feeLedger_;
initialiser = msg.sender;
initialiserUntil = uint64(block.timestamp + 1 days);
feeRecipient = feeRecipient_;
emit FeeRecipientSet(feeRecipient_);
}
// ── Series ──────────────────────────────────────────────────────────────────────────────
/// @notice Register a series. Governance's act (through the timelock), or the deployer's in the first day
/// after the directory was built — the same window the deployer has to fill a series' terms.
/// Registering a series makes its escrow the token's minter and names where its redemptions are
/// paid from, so what is registered is checked, not trusted: the token was built for this
/// registry, this operations Safe, this governance and this directory; the escrow was built for
/// this token and this directory; the price series is not another token's; the terms are filed;
/// and the payer pays for this series alone (review of 27.09.2026).
function addSeries(IERC20 token, SubscriptionEscrow escrow, address payer) external onlyGovernanceOrInitialiser {
if (address(token) == address(0) || address(escrow) == address(0) || payer == address(0)) revert ZeroAddress();
if (escrowOf[address(token)] != address(0)) revert SeriesExists(address(token));
ProductToken t = ProductToken(address(token));
if (t.registry() != registry || t.ops() != ops || t.governance() != governance) {
revert TokenMismatch(address(token));
}
if (address(t.directory()) != address(this)) revert TokenMismatch(address(token));
if (seriesTaken[t.series()]) revert SeriesTaken(t.series());
if (isPayer[payer]) revert PayerTaken(payer);
if (
quarantine != address(0)
&& (payer == quarantine || address(escrow) == quarantine || address(token) == quarantine)
) {
revert BadQuarantine(quarantine);
}
if (!parameters.isSet(address(token))) revert TermsNotSet(address(token));
// every issue and burn of a registered token reaches this set's ledger (review of 28.09.2026, L-14)
if (t.feeLedger() != address(feeLedger)) revert TokenMismatch(address(token));
// a token retired in the ledger can never issue, and a retirement is never undone: such a series
// would take deposits it can only return (re-check of 05c)
if (feeLedger.accountOf(address(token)).retired) revert IsRetired(address(token));
// a token in the middle of a migration is no series yet: what it carries is bound to its source only
// when the migration is closed (`finishReissue`), and a series is registered whole or not at all
// (audit of 13.10.2026, E-1)
if (t.reissueState() != 0 && t.reissuedSource() == address(0)) revert ReissueNotFinished(address(token));
_checkEscrow(token, escrow, payer);
seriesTaken[t.series()] = true;
tokenOfSeries[t.series()] = address(token);
isPayer[payer] = true;
registeredAt[address(token)] = block.timestamp;
escrowOf[address(token)] = address(escrow);
payerOf[address(token)] = payer;
isSeriesEscrow[address(escrow)] = true;
wasEscrow[address(escrow)] = true;
emit SeriesAdded(address(token), address(escrow), payer);
}
/// @notice Replace a series' token with its successor under the same price series — the recovery when a
/// token itself must go (audit of 05.10.2026, M-03). Governance, through the timelock. The series
/// keeps its price record, its custody and its payout history (the gate's window is the price
/// series', so it goes on unbroken); the successor gets a fresh escrow built for it, and the old
/// token is no series any more: nothing is issued in it, requested, settled or collected for it,
/// so a unit is never redeemed twice. What it is held to before the act:
/// the old token is retired in the fee ledger and owes nothing there; the queue of the day holds
/// no request in it and no fee deferred for it; the successor was built for this set and the same
/// price series, its terms are filed, its reissue is finished and seeded; the old token is paused
/// and the successor carries exactly its supply — every unit, with its lot and basis; nothing at
/// all only where the old token has none. The order of a replacement: stop requests, settle or
/// cancel what is open in the old token, `retire` it, collect what it owes, pause it and read the
/// positions, build the successor and its escrow, `reissue` … `finishReissue`, `seed`, then this
/// call. A switch still waiting to come into the series from another lands in the successor's escrow.
/// Deposits still waiting in the old escrow are returned by the operations Safe, as after `setEscrow`.
function replaceToken(IERC20 old, IERC20 token, SubscriptionEscrow escrow) external onlyGovernance {
address oldEscrow = escrowOf[address(old)];
if (oldEscrow == address(0)) revert UnknownSeries(address(old));
if (address(token) == address(0) || address(escrow) == address(0)) revert ZeroAddress();
if (escrowOf[address(token)] != address(0)) revert SeriesExists(address(token));
ProductToken t = ProductToken(address(token));
if (t.registry() != registry || t.ops() != ops || t.governance() != governance) {
revert TokenMismatch(address(token));
}
if (address(t.directory()) != address(this) || t.feeLedger() != address(feeLedger)) {
revert TokenMismatch(address(token));
}
bytes32 series = ProductToken(address(old)).series();
if (t.series() != series) revert SeriesMismatch(t.series());
if (!parameters.isSet(address(token))) revert TermsNotSet(address(token));
// the successor is live in the ledger: one retired there could never issue (re-check of 05c)
if (feeLedger.accountOf(address(token)).retired) revert IsRetired(address(token));
// the old token is closed: retired, nothing owed, nothing waiting
if (!feeLedger.accountOf(address(old)).retired) revert NotRetired(address(old));
(uint256 management, uint256 performance) = feeLedger.entitlementOf(address(old));
IQueueDebts queue = IQueueDebts(registry.redemptionSink());
if (
management != 0 || performance != 0 || queue.pendingUnits(address(old)) != 0
|| queue.feesDue(address(old)) != 0
) revert StillOwes(address(old));
// the successor is whole: a reissue, if there was one, finished and in the ledger's record
if (t.reissueState() == 1 || feeLedger.accountOf(address(token)).migrated != 0) {
revert ReissueNotFinished(address(token));
}
// and what it carried over came from this token and no other: the migration named its source when it
// was closed (E-1). A successor that migrated nothing stands only for an old token that has no units.
if (t.reissueState() == 2 && t.reissuedSource() != address(old)) {
revert ReissueSourceMismatch(address(token), t.reissuedSource());
}
address payer = payerOf[address(old)];
if (address(escrow) == quarantine || address(token) == quarantine) revert BadQuarantine(quarantine);
if (wasEscrow[address(escrow)]) revert EscrowMismatch(address(escrow));
_checkEscrow(token, escrow, payer);
// and it carries every unit of the old token, no more and no fewer: an empty or a partial successor
// would leave holders with units that are no series' (follow-up audits, L-02b, P-07). The old token
// is paused, so the positions the migration was read from cannot have moved since — the pause comes
// first, then the snapshot. Who got which units, and at what basis, is the migration manifest's to
// show; the sum is what the contract can hold it to.
if (!ProductToken(address(old)).paused()) revert NotPaused(address(old));
if (t.reissuedUnits() != old.totalSupply() || token.totalSupply() != old.totalSupply()) {
revert UnitsNotCarried(t.reissuedUnits(), old.totalSupply());
}
SubscriptionEscrow(oldEscrow).closeByDirectory();
isSeriesEscrow[oldEscrow] = false;
delete escrowOf[address(old)];
delete payerOf[address(old)];
isSeriesEscrow[address(escrow)] = true;
wasEscrow[address(escrow)] = true;
escrowOf[address(token)] = address(escrow);
payerOf[address(token)] = payer;
registeredAt[address(token)] = block.timestamp;
successorOf[address(old)] = address(token);
tokenOfSeries[series] = address(token);
emit TokenReplaced(address(old), address(token), address(escrow));
}
/// @notice The escrow a series subscribes through now, asked by any token it has ever had: the token's own,
/// or that of the token that holds its series today — in one step, however many replacements lie
/// between. Zero for a token that never was a series.
function escrowNow(address token) external view returns (address escrow) {
escrow = escrowOf[token];
if (escrow == address(0) && successorOf[token] != address(0)) {
escrow = escrowOf[tokenOfSeries[ProductToken(token).series()]];
}
}
/// @notice Replace a series' escrow — blacklisted, compromised, or simply rotated — with the timelock's
/// notice, the custody staying the same. The new escrow must be built for this token, this
/// directory and this custody. From the moment it is set, only it can mint the token and only it
/// is a switch destination; the old one is closed, can no longer allocate, and what it holds is
/// still returned to its depositors by the operations Safe.
function setEscrow(IERC20 token, SubscriptionEscrow escrow) external onlyGovernance {
_setEscrow(token, escrow);
}
/// @notice Move a series to another custody — rotated or compromised — with the timelock's notice: the
/// payer and the escrow together, because an escrow pays its allocations to a fixed destination
/// and money in and money out of a series are one address (review of 27.09.2026, N-03). Changing
/// the payer alone left subscriptions flowing to the custody that was rotated out (review of
/// 03.10.2026, B-09), so there is no such call. A custody address is never reused (N-02).
function rotateCustody(IERC20 token, address payer, SubscriptionEscrow escrow) external onlyGovernance {
if (payer == address(0)) revert ZeroAddress();
if (escrowOf[address(token)] == address(0)) revert UnknownSeries(address(token));
if (isPayer[payer]) revert PayerTaken(payer);
if (payer == quarantine) revert BadQuarantine(payer);
isPayer[payer] = true;
payerOf[address(token)] = payer;
emit PayerSet(address(token), payer);
_setEscrow(token, escrow);
}
function _setEscrow(IERC20 token, SubscriptionEscrow escrow) private {
address old = escrowOf[address(token)];
if (old == address(0)) revert UnknownSeries(address(token));
if (address(escrow) == address(0)) revert ZeroAddress();
if (address(escrow) == quarantine) revert BadQuarantine(quarantine);
if (wasEscrow[address(escrow)]) revert EscrowMismatch(address(escrow));
// the same binding a registration is held to
_checkEscrow(token, escrow, payerOf[address(token)]);
SubscriptionEscrow(old).closeByDirectory(); // no new deposits into an escrow that can no longer issue
isSeriesEscrow[old] = false;
isSeriesEscrow[address(escrow)] = true;
wasEscrow[address(escrow)] = true;
escrowOf[address(token)] = address(escrow);
emit EscrowSet(address(token), address(escrow), old);
}
/// @dev An escrow is accepted only if every one of its immutable bindings is this set's: the token it
/// mints, the directory it reads, the stablecoin, the registry, the operations Safe, the anchor it
/// prices from, and the custody it pays allocations to — which must be the series' payer.
function _checkEscrow(IERC20 token, SubscriptionEscrow escrow, address payer) private view {
if (address(escrow.token()) != address(token) || address(escrow.directory()) != address(this)) {
revert EscrowMismatch(address(escrow));
}
if (address(escrow.usdc()) != address(usdc) || escrow.registry() != registry) {
revert EscrowMismatch(address(escrow));
}
if (escrow.ops() != ops || escrow.anchor() != anchor) revert EscrowMismatch(address(escrow));
if (escrow.destination() != payer) revert EscrowMismatch(address(escrow));
}
// ── The contour's two addresses ─────────────────────────────────────────────────────────
/// @notice Where swept money goes. Unset, nothing can be swept. The deployer may name it once, while none
/// is set, within its day-long right, so a set goes live with its quarantine instead of 48 h
/// after; every later change is governance's, through the timelock. The quarantine is a contract
/// (a Safe: the deployment script checks its proxy, owners and threshold on mainnet) and none of
/// the contour's own addresses — not a queue, an escrow, a series' units, a custody, the treasury,
/// a role, the registry, the anchor, the tariffs, the fee ledger, this directory or USDC: doubtful
/// money must not mix with the contour's, and an escrow as its own quarantine would erase a debt
/// without moving a cent (review of 30.09.2026, L-17).
function setQuarantine(address quarantine_) external onlyGovernanceOrInitialiser {
if (msg.sender != governance && quarantine != address(0)) revert NotGovernance();
if (quarantine_ == address(0)) revert ZeroAddress();
if (
quarantine_.code.length == 0 || quarantine_ == address(this) || registry.wasRedemptionSink(quarantine_)
|| wasEscrow[quarantine_] || escrowOf[quarantine_] != address(0) || isPayer[quarantine_]
|| quarantine_ == feeRecipient || quarantine_ == ops || quarantine_ == governance
|| quarantine_ == address(registry) || quarantine_ == address(anchor)
|| quarantine_ == address(parameters) || quarantine_ == address(feeLedger)
|| quarantine_ == address(usdc)
) revert BadQuarantine(quarantine_);
quarantine = quarantine_;
emit QuarantineSet(quarantine_);
}
/// @notice Move where the fees go — the treasury rotated — with the timelock's notice.
function setFeeRecipient(address feeRecipient_) external onlyGovernance {
if (feeRecipient_ == address(0)) revert ZeroAddress();
if (feeRecipient_ == quarantine) revert BadQuarantine(feeRecipient_);
feeRecipient = feeRecipient_;
emit FeeRecipientSet(feeRecipient_);
}
// ── The redemption gate ─────────────────────────────────────────────────────────────────
/// @notice The queue of the day reports what a settlement paid out, `gross`, on NAV as the settlement
/// found it (`supply` units at `priceMicro`). Refused when it would take the series past its gate:
/// at most the gate's share of NAV in the window, counted in whole calendar days (UTC) — today and
/// the `windowDays − 1` days before it (owner, 04.10.2026). A day's payouts are one entry under
/// that day's number, so they leave the window together and only when the day itself has left it
/// (the audit's G02: an entry dated at its first payout left early).
function notePayout(address token, uint256 supply, uint256 priceMicro, uint256 gross) external {
if (msg.sender != registry.redemptionSink()) revert NotQueue();
bytes32 series = ProductToken(token).series();
SeriesParameters.Gate memory g = parameters.gateOf(token);
Paid[] storage paid = _paid[series];
uint256 today = block.timestamp / 1 days;
// what is dropped for good is only what no window governance may set could reach again: the window is
// a filter over the rest, so widening it counts earlier payouts (27.09.2026, M-07). The head moves on
// whether or not a gate is set today — one entry per day (F-07), at most 92 of them (M-11)
uint256 head = _paidHead[series];
uint256 widest = parameters.MAX_GATE_WINDOW_DAYS();
while (head < paid.length && uint256(paid[head].day) + widest <= today) head++;
_paidHead[series] = head;
if (g.bps != 0) {
uint256 inWindow = _inWindow(paid, head, today, g.windowDays);
uint256 cap = ((supply * priceMicro) / 1e6 * g.bps) / 10_000;
uint256 remaining = cap > inWindow ? cap - inWindow : 0;
if (gross > remaining) revert GateExceeded(gross, remaining);
}
if (gross != 0) {
uint256 last = paid.length;
if (last != 0 && paid[last - 1].day == today) paid[last - 1].gross += uint192(gross);
else paid.push(Paid(uint32(today), uint192(gross)));
emit PaidOut(token, uint32(today), gross);
}
}
/// @notice What a series has paid out inside its gate window, and the window's cap at the latest price:
/// the same window the gate itself applies.
function gateStatus(address token) external view returns (uint256 paidInWindow, uint256 cap) {
SeriesParameters.Gate memory g = parameters.gateOf(token);
if (g.bps == 0) return (0, type(uint256).max);
bytes32 series = ProductToken(token).series();
paidInWindow = _inWindow(_paid[series], _paidHead[series], block.timestamp / 1 days, g.windowDays);
uint256 nav = (IERC20(token).totalSupply() * anchor.latestPriceOf(series)) / 1e6;
cap = (nav * g.bps) / 10_000;
}
/// @dev The payouts of today and the `windowDays − 1` days before it.
function _inWindow(Paid[] storage paid, uint256 head, uint256 today, uint256 windowDays)
private
view
returns (uint256 sum)
{
for (uint256 i = head; i < paid.length; i++) {
if (uint256(paid[i].day) + windowDays > today) sum += paid[i].gross;
}
}
}
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/NavFeeLedger.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {AllowlistRegistry} from "./AllowlistRegistry.sol";
import {AttestationAnchor} from "./AttestationAnchor.sol";
import {SeriesParameters} from "./SeriesParameters.sol";
import {ProductToken, Lot} from "./ProductToken.sol";
/// @title NavFeeLedger — what the NAV fees (management, performance) may amount to, per series
/// @notice The ceiling on what the operations Safe may collect from a series' custody as management and
/// performance fee, kept where a queue replacement cannot reset it (review of 28.09.2026, M-14) and
/// measured on the units as they were issued, lot by lot, never on today's supply applied to all
/// history (M-13, M-18, M-21, M-22):
///
/// - management accrues on NAV over time along the published trajectory: at every issue, burn, rate
/// change and collection the units that stood since the last mark earn `units × ∫price dt` read off
/// the anchor's record (M-15), at the rate in force over that stretch (M-16); what is not collected
/// stays owed (a partial collection loses nothing). The anchor's integral stands still once a price
/// is stale, and a series governance has retired accrues nothing (review of 03.10.2026, B-13);
/// - performance (owner, 04.10.2026): each unit bears the rate on its own rise above its basis — the
/// higher of the series' high-water mark and the price it was issued at. A unit's basis travels with
/// its lot under a number of the ledger's own giving: when the token issues, the ledger names the
/// cohort — units issued above the mark at one price are one cohort — and the token writes that
/// number into the lot. The fee becomes owed on two occasions only. On a burn: the token reports the
/// lots that left, and the gain owed is that of exactly those units over their basis at that
/// moment's price (M-19, M-21). At a month's close: once the anchor has a later month on record,
/// every unit owes its gain at the price the month closed at, cohorts below that price join the
/// floor, a cohort above it keeps its basis (M-20), and the mark moves to that price. Between the
/// two nothing is owed: a gain that does not last to the month's close is charged to nobody, and a
/// collection can no longer fix the mark at a price of the Safe's choosing (review of 03.10.2026,
/// B-11). The anchored price is net of the fee accrued in NAV, so the gain is grossed up:
/// `(price − basis) × rate ÷ (1 − rate)` is the rate on the rise before the fee.
///
/// Cohorts are numbered once and never reused; at most `MAX_COHORTS` stand above the floor at once,
/// beyond that a new issue joins the last one at the higher basis (the lower ceiling).
///
/// The ledger bounds the Safe, it does not compute the invoice: the Calculation Agent's figures are the
/// fee, and where they exceed the ceiling the ceiling binds; where the ledger has to choose, it
/// chooses the lower ceiling.
///
/// Migration: a reissue hands over each lot's units and basis. They stand apart, earning and owing
/// nothing, until governance seeds them — which enters every one of them in one call, never partially,
/// never twice, with the mark they carry: lots issued above that mark keep their own basis, so nobody
/// is charged for a rise he never had (the audit of 04.10.2026, EX-01); the rest join the floor (L-15).
contract NavFeeLedger {
/// @dev Units issued above the floor at one basis.
struct Cohort {
uint128 units;
uint128 basis;
}
struct Account {
/// @dev Units on record (6 decimals): at the floor and in cohorts.
uint128 units;
/// @dev Units at the floor: issued at or below the mark, moved to it at a collection, or seeded.
uint128 floorUnits;
/// @dev The last mark.
uint64 at;
/// @dev Whether governance has seeded the series.
bool seeded;
/// @dev The last cohort number given.
uint32 lastCohort;
/// @dev Units a reissue carried over and governance has not seeded: apart, and uncharged.
uint128 migrated;
/// @dev The anchor's price integral at the last mark.
uint256 integralAt;
/// @dev The high-water mark, the floor of every basis; zero means the launch price.
uint256 hwm;
/// @dev Accrued and not yet collected, micro-USDC.
uint256 owedManagement;
uint256 owedPerformance;
/// @dev Of `migrated`, the units a reissue carried over with a basis of their own: in cohorts already.
uint128 migratedAbove;
/// @dev The last month (YYYYMM) whose close has been crystallised.
uint32 crystallisedMonth;
/// @dev Governance has retired the series: nothing accrues any more.
bool retired;
/// @dev What the last management accrual left under one micro-USDC, in the units of its numerator:
/// carried into the next, so marking often rounds nothing away (audit of 05.10.2026, I-01).
uint256 managementCarry;
}
/// @notice The month closes one issue, burn or collection crystallises on its way. A record left alone for
/// longer is brought up by `crystallise`, as many calls as it takes, before anything else touches it.
uint256 public constant MAX_CLOSES = 12;
/// @dev 100 % in basis points × a year × the price's six decimals: what the management numerator is over.
uint256 private constant MANAGEMENT_DENOMINATOR = 10_000 * 365 days * 1e6;
/// @notice The most cohorts above the floor a series carries at once.
uint16 public constant MAX_COHORTS = 400;
AllowlistRegistry public immutable registry;
AttestationAnchor public immutable anchor;
SeriesParameters public immutable parameters;
address public immutable governance;
mapping(address => Account) private _accounts;
/// @dev token → cohort number → the cohort, while it stands above the floor.
mapping(address => mapping(uint32 => Cohort)) private _cohort;
/// @dev token → the numbers of the cohorts above the floor, in no order.
mapping(address => uint32[]) private _open;
/// @dev token → cohort number → its position in `_open` plus one; zero when not there.
mapping(address => mapping(uint32 => uint256)) private _slot;
/// @dev token → basis → the open cohort at that basis, so an issue at a basis already standing joins it.
mapping(address => mapping(uint256 => uint32)) private _atBasis;
event Issued(address indexed token, uint32 indexed cohort, uint256 units, uint256 basisMicro);
event Burned(address indexed token, uint256 units, uint256 priceMicro);
event Accrued(address indexed token, bytes32 indexed kind, uint256 amount);
event Collected(address indexed token, bytes32 indexed kind, uint256 amount, uint256 owedAfter);
event Seeded(address indexed token, uint256 units, uint256 hwm);
event Crystallised(address indexed token, uint32 indexed month, uint256 priceMicro);
event Retired(address indexed token);
error ZeroAddress();
error NotSink();
error NotGovernance();
error NotParameters();
error UnknownFeeKind(bytes32 kind);
error FeeAboveEntitlement(bytes32 kind, uint256 amount, uint256 owed);
error AlreadySeeded(address token);
error NothingToSeed(address token);
error ZeroAmount();
error NotSeeded(address token);
error IsRetired(address token);
error LengthMismatch();
error ClosesPending(address token);
constructor(
AllowlistRegistry registry_,
AttestationAnchor anchor_,
SeriesParameters parameters_,
address governance_
) {
if (address(registry_) == address(0) || address(anchor_) == address(0)) {
revert ZeroAddress();
}
if (address(parameters_) == address(0) || governance_ == address(0)) revert ZeroAddress();
registry = registry_;
anchor = anchor_;
parameters = parameters_;
governance = governance_;
}
// ── Who writes ──────────────────────────────────────────────────────────────────────────
/// @dev The queue of the day: the registry's redemption sink.
modifier onlySink() {
if (msg.sender != registry.redemptionSink()) revert NotSink();
_;
}
// ── The record ──────────────────────────────────────────────────────────────────────────
/// @notice The token is issuing `units` at `priceMicro` and says so itself: the ledger names the cohort
/// they go into — zero, the floor, at or below the mark; else the open cohort at that price, or a
/// new one — and the token writes it into their lot. A series is its token: every account is
/// written by its own token and by nobody else.
function noteIssued(uint256 units, uint256 priceMicro) external returns (uint32 cohort) {
address token = msg.sender;
if (units == 0 || priceMicro == 0) revert ZeroAmount();
Account storage a = _accounts[token];
if (a.retired) revert IsRetired(token);
// what a reissue carried over enters the record first, with its mark: an issue before the seed would
// stand beside units the ledger does not count yet
if (a.migrated != 0) revert NotSeeded(token);
_mark(a, token);
_crystallise(a, token);
uint256 hwm = _hwm(a, token);
if (priceMicro > hwm) {
cohort = _join(a, token, units, priceMicro);
} else {
a.floorUnits += uint128(units);
}
a.units += uint128(units);
emit Issued(token, cohort, units, priceMicro > hwm ? priceMicro : hwm);
}
/// @notice The token burned these lots — settled by the queue or retired by the operations Safe — and
/// says so in the same call: the gain of exactly these units, over their basis and at today's
/// price, is owed before they go. A lot of cohort zero is at the floor, and charged only as far as
/// the floor has units on record.
function noteBurned(Lot[] calldata lots) external {
address token = msg.sender;
Account storage a = _accounts[token];
_mark(a, token);
_crystallise(a, token);
uint256 price = anchor.latestPriceOf(ProductToken(token).series());
uint256 hwm = _hwm(a, token);
(, uint16 performanceBps) = parameters.navFeesOf(token);
uint256 gain;
uint256 total;
for (uint256 i = 0; i < lots.length; i++) {
uint256 u = lots[i].units;
if (u == 0) continue;
Cohort storage c = _cohort[token][lots[i].cohort];
if (a.migrated != 0) {
// carried over and not seeded: never on record, never charged, never anyone else's floor
a.migrated = a.migrated > u ? a.migrated - uint128(u) : 0;
if (lots[i].cohort != 0 && c.units != 0) {
uint256 above = u < c.units ? u : c.units;
c.units -= uint128(above);
a.migratedAbove = a.migratedAbove > above ? a.migratedAbove - uint128(above) : 0;
if (c.units == 0) _close(token, lots[i].cohort, c.basis);
}
continue;
}
total += u;
if (lots[i].cohort != 0 && c.units != 0) {
uint256 fromCohort = u < c.units ? u : c.units;
uint256 b = c.basis > hwm ? c.basis : hwm; // never below the mark, whatever the record says
gain += _gain(fromCohort, price, b, performanceBps);
c.units -= uint128(fromCohort);
if (c.units == 0) _close(token, lots[i].cohort, c.basis);
u -= fromCohort;
}
if (u != 0) {
// at the floor: issued at or below the mark, moved to it, or seeded — and only as far as the
// floor has units; what the ledger never issued nor seeded earns no ceiling (K-01)
uint256 known = u < a.floorUnits ? u : a.floorUnits;
gain += _gain(known, price, hwm, performanceBps);
a.floorUnits -= uint128(known);
}
}
if (total > a.units) total = a.units;
a.units -= uint128(total);
// a retired series accrues nothing, on this path as on every other: its units leave the record and
// owe nothing new (review of 03.10.2026, B-13; audit of 05.10.2026, L-01 and P-02)
if (a.retired) gain = 0;
if (gain != 0) {
a.owedPerformance += gain;
emit Accrued(token, "performance", gain);
}
emit Burned(token, total, price);
}
/// @notice The token reissued units carried over from a replaced token, lot by lot: `basis[i]` is the
/// basis `units[i]` stood at there, or zero for units at that token's mark. The ledger names the
/// cohort of each — the token's `MIGRATED_COHORT` for the ones without a basis of their own — and
/// keeps them all apart, uncharged, until governance seeds the series.
function noteMigrated(uint256[] calldata units, uint256[] calldata basis)
external
returns (uint32[] memory cohorts)
{
address token = msg.sender;
if (units.length != basis.length) revert LengthMismatch();
Account storage a = _accounts[token];
if (a.seeded || a.units != 0) revert AlreadySeeded(token);
uint32 none = ProductToken(token).MIGRATED_COHORT();
cohorts = new uint32[](units.length);
for (uint256 i = 0; i < units.length; i++) {
a.migrated += uint128(units[i]);
if (basis[i] == 0) {
cohorts[i] = none;
} else {
cohorts[i] = _join(a, token, units[i], basis[i]);
a.migratedAbove += uint128(units[i]);
}
}
}
/// @notice The parameters are about to change a NAV rate: what accrued does so at the rates in force —
/// management always, performance only when its own rate changes (I-01).
function checkpoint(address token, bool performance) external {
if (msg.sender != address(parameters)) revert NotParameters();
Account storage a = _accounts[token];
_mark(a, token);
_crystallise(a, token);
if (performance && !a.retired) {
// the period is closed early, at the latest price and at the rate that is about to go
(, uint16 performanceBps) = parameters.navFeesOf(token);
_accruePerformance(a, token, performanceBps, anchor.latestPriceOf(ProductToken(token).series()));
}
}
/// @notice Crystallise the months that have closed and have not been, oldest first, each at the price it
/// closed at and at most `MAX_CLOSES` of them a call: anyone may call it, it reads only the
/// anchor's record. Every issue, burn and collection does the same first.
function crystallise(address token) external {
Account storage a = _accounts[token];
_mark(a, token);
_catchUp(a, token);
}
/// @notice Retire a series: a token that has been replaced accrues nothing from here on, beside its
/// successor or otherwise (review of 03.10.2026, B-13). What is owed stays collectable; what had
/// accrued since the last month's close and not crystallised is not charged here — the units carry
/// their bases to the successor, and it is charged there. Governance, through the timelock; never undone.
function retire(address token) external {
if (msg.sender != governance) revert NotGovernance();
Account storage a = _accounts[token];
_mark(a, token);
_crystallise(a, token);
a.retired = true;
emit Retired(token);
}
/// @notice The queue collects `amount` of `kind` for the series: refused above what has accrued.
function collect(address token, bytes32 kind, uint256 amount) external onlySink {
if (amount == 0) revert ZeroAmount();
Account storage a = _accounts[token];
_mark(a, token);
if (kind == bytes32("management")) {
if (amount > a.owedManagement) revert FeeAboveEntitlement(kind, amount, a.owedManagement);
a.owedManagement -= amount;
emit Collected(token, kind, amount, a.owedManagement);
} else if (kind == bytes32("performance")) {
// only what has crystallised — at a month's close or on a burn — is owed (B-11)
_crystallise(a, token);
if (amount > a.owedPerformance) revert FeeAboveEntitlement(kind, amount, a.owedPerformance);
a.owedPerformance -= amount;
emit Collected(token, kind, amount, a.owedPerformance);
} else {
revert UnknownFeeKind(kind);
}
}
/// @notice The units a reissue carried over enter the record: all of them, with the mark they carry over;
/// once per series, never partially. The ones with a basis above the mark stay in their cohorts,
/// the rest are at the floor. Governance, through the timelock.
function seed(address token, uint256 hwm) external {
if (msg.sender != governance) revert NotGovernance();
if (hwm == 0) revert ZeroAmount();
Account storage a = _accounts[token];
if (a.seeded) revert AlreadySeeded(token);
if (a.migrated == 0) revert NothingToSeed(token);
_mark(a, token);
uint256 units = a.migrated;
a.seeded = true;
a.units += uint128(units);
a.floorUnits += uint128(units - a.migratedAbove);
a.migrated = 0;
a.migratedAbove = 0;
// the higher of the migration's mark and the series' own (its launch price, or where it stands): the
// lower ceiling either way
uint256 own = _hwm(a, token);
a.hwm = hwm > own ? hwm : own;
// the mark is stated as of now: a month that closed before the seed is not this record's to charge
a.crystallisedMonth = anchor.closedMonth(ProductToken(token).series());
// no basis in force below the mark: every open cohort at or under it joins the floor, uncharged —
// the rise of the mark forgives that stretch, it does not sell it (review of 28.09.2026, M-24)
_floorUnder(a, token, a.hwm);
emit Seeded(token, units, a.hwm);
}
// ── Views ───────────────────────────────────────────────────────────────────────────────
function accountOf(address token) external view returns (Account memory) {
return _accounts[token];
}
/// @notice The cohorts above the floor, with their numbers.
function cohortsOf(address token) external view returns (uint32[] memory ids, Cohort[] memory out) {
ids = _open[token];
out = new Cohort[](ids.length);
for (uint256 i = 0; i < ids.length; i++) {
out[i] = _cohort[token][ids[i]];
}
}
/// @notice The basis a lot of cohort `cohort` is charged above, now.
function basisOf(address token, uint32 cohort) external view returns (uint256) {
Cohort storage c = _cohort[token][cohort];
uint256 hwm = _markNow(_accounts[token], token);
return cohort != 0 && c.units != 0 && c.basis > hwm ? c.basis : hwm;
}
/// @notice The high-water mark the next performance fee is measured from: where it stands once a month
/// that has closed is crystallised, whether or not anyone has touched the record since.
function highWaterMarkOf(address token) external view returns (uint256) {
return _markNow(_accounts[token], token);
}
/// @notice What could be collected now of each kind, were it collected now: the owed, plus the management
/// fee accrued since the last mark, plus the performance fee of a month that has closed and has
/// not been crystallised yet. Exactly what `collect` would allow.
function entitlementOf(address token) external view returns (uint256 management, uint256 performance) {
Account storage a = _accounts[token];
(uint16 managementBps, uint16 performanceBps) = parameters.navFeesOf(token);
bytes32 series = ProductToken(token).series();
management = a.owedManagement;
uint256 integral = anchor.priceIntegral(series);
if (!a.retired && a.at != 0 && a.units != 0 && integral > a.integralAt) {
management += (uint256(a.units) * (integral - a.integralAt) * managementBps + a.managementCarry)
/ MANAGEMENT_DENOMINATOR;
}
(performance,) = _pendingCloses(a, token, performanceBps);
performance += a.owedPerformance;
}
/// @notice The performance fee accrued in NAV at the latest price and not yet owed: what a month's close
/// at this price would crystallise. It falls when the price falls.
function accrualOf(address token) external view returns (uint256) {
Account storage a = _accounts[token];
(, uint16 performanceBps) = parameters.navFeesOf(token);
if (a.units == 0 || a.retired) return 0;
return _gainAt(a, token, anchor.latestPriceOf(ProductToken(token).series()), _markNow(a, token), performanceBps);
}
// ── Internals ───────────────────────────────────────────────────────────────────────────
/// @dev Units above the floor join the open cohort at their price, or a new one; beyond the limit they
/// join the last cohort in the list at the higher basis — the lower ceiling.
function _join(Account storage a, address token, uint256 units, uint256 basis) private returns (uint32 id) {
id = _atBasis[token][basis];
if (id != 0) {
_cohort[token][id].units += uint128(units);
return id;
}
uint32[] storage open = _open[token];
if (open.length >= MAX_COHORTS) {
id = open[open.length - 1];
Cohort storage last = _cohort[token][id];
if (basis > last.basis) {
delete _atBasis[token][last.basis];
last.basis = uint128(basis);
_atBasis[token][basis] = id;
}
last.units += uint128(units);
return id;
}
id = ++a.lastCohort;
_cohort[token][id] = Cohort(uint128(units), uint128(basis));
_atBasis[token][basis] = id;
open.push(id);
_slot[token][id] = open.length;
}
/// @dev A cohort with nothing left, or one that joined the floor, leaves the list; its number is never given again.
function _close(address token, uint32 id, uint256 basis) private {
uint32[] storage open = _open[token];
uint256 i = _slot[token][id];
if (i == 0) return;
uint32 last = open[open.length - 1];
open[i - 1] = last;
_slot[token][last] = i;
open.pop();
delete _slot[token][id];
if (_atBasis[token][basis] == id) delete _atBasis[token][basis];
delete _cohort[token][id];
}
/// @dev Every open cohort with a basis at or under `mark` joins the floor, uncharged; its number is closed.
function _floorUnder(Account storage a, address token, uint256 mark) private {
uint32[] storage open = _open[token];
uint256 i = 0;
while (i < open.length) {
uint32 id = open[i];
Cohort storage c = _cohort[token][id];
if (c.basis <= mark) {
a.floorUnits += c.units;
_close(token, id, c.basis); // the last number moves into slot i: look at i again
} else {
i++;
}
}
}
/// @dev NAV × time since the last mark, for the units that stood, along the anchor's price trajectory
/// (M-15), at the management rate in force (M-16): owed from here on.
function _mark(Account storage a, address token) private {
uint256 integral = anchor.priceIntegral(ProductToken(token).series());
if (!a.retired && a.at != 0 && a.units != 0 && integral > a.integralAt) {
(uint16 managementBps,) = parameters.navFeesOf(token);
// whole micro-USDC are owed; the fraction waits in the numerator for the next mark (I-01)
uint256 numerator = uint256(a.units) * (integral - a.integralAt) * managementBps + a.managementCarry;
uint256 amount = numerator / MANAGEMENT_DENOMINATOR;
a.managementCarry = numerator % MANAGEMENT_DENOMINATOR;
if (amount != 0) {
a.owedManagement += amount;
emit Accrued(token, "management", amount);
}
}
a.at = uint64(block.timestamp);
// the mark only moves forward: were the integral ever read lower than it was, the stretch between
// would otherwise be charged a second time on its way back up (re-check of 05d)
if (integral > a.integralAt) a.integralAt = integral;
}
function _hwm(Account storage a, address token) private view returns (uint256) {
return a.hwm != 0 ? a.hwm : anchor.launchPriceOf(ProductToken(token).series());
}
/// @dev The rate on a rise before the fee, read off a price that is net of it:
/// `units × (price − basis) × bps ÷ (10 000 − bps)`, in micro-USDC.
function _gain(uint256 units, uint256 price, uint256 basis, uint256 bps) private pure returns (uint256) {
if (price <= basis || bps == 0) return 0;
return (units * (price - basis) * bps) / ((10_000 - bps) * 1e6);
}
/// @dev Whether a month has closed that the record has not crystallised, and would charge if it did.
function _closePending(Account storage a, bytes32 series) private view returns (bool) {
return !a.retired && a.migrated == 0 && a.units != 0 && anchor.closedMonth(series) > a.crystallisedMonth;
}
/// @dev The mark as it stands once every month that has closed is crystallised.
function _markNow(Account storage a, address token) private view returns (uint256 hwm) {
(, hwm) = _pendingCloses(a, token, 0);
}
/// @dev What the months that have closed and are not crystallised yet would owe, taken oldest first each
/// at its own closing price, and where the mark would then stand: `_catchUp` without the writing.
function _pendingCloses(Account storage a, address token, uint256 bps)
private
view
returns (uint256 gain, uint256 hwm)
{
hwm = _hwm(a, token);
bytes32 series = ProductToken(token).series();
if (!_closePending(a, series)) return (0, hwm);
uint32[] storage open = _open[token];
uint256[] memory units = new uint256[](open.length);
uint256[] memory basis = new uint256[](open.length);
for (uint256 i = 0; i < units.length; i++) {
Cohort storage c = _cohort[token][open[i]];
units[i] = c.units;
basis[i] = c.basis;
}
uint256 floorUnits = a.floorUnits;
uint32 month = a.crystallisedMonth;
while (true) {
month = anchor.nextClosedAfter(series, month);
if (month == 0) break;
uint256 price = anchor.closedPriceOf(series, month);
if (price <= hwm) continue;
gain += _gain(floorUnits, price, hwm, bps);
for (uint256 i = 0; i < units.length; i++) {
uint256 b = basis[i] > hwm ? basis[i] : hwm;
if (units[i] != 0 && price > b) {
gain += _gain(units[i], price, b, bps);
floorUnits += units[i];
units[i] = 0;
}
}
hwm = price;
}
}
/// @dev What every unit on record would owe at `price` with the mark at `hwm`: the floor over the mark, each
/// cohort over its basis.
function _gainAt(Account storage a, address token, uint256 price, uint256 hwm, uint256 bps)
private
view
returns (uint256 gain)
{
if (price <= hwm) return 0;
gain = _gain(a.floorUnits, price, hwm, bps);
uint32[] storage open = _open[token];
for (uint256 i = 0; i < open.length; i++) {
Cohort storage c = _cohort[token][open[i]];
gain += _gain(c.units, price, c.basis > hwm ? c.basis : hwm, bps);
}
}
/// @dev Before the record changes, every month that has closed is crystallised; a record left alone for
/// more than `MAX_CLOSES` months is brought up by `crystallise` first.
function _crystallise(Account storage a, address token) private {
if (!_catchUp(a, token)) revert ClosesPending(token);
}
/// @dev The months that closed and the record has not crystallised, oldest first, each at the price it
/// closed at — the anchor keeps every close, so one nobody acted on before the next is charged all
/// the same, and the mark passes through it (audit of 05.10.2026, M-02). Nothing changed the record
/// between those closes, or it would have crystallised them: the units and bases of today are theirs.
/// At most `MAX_CLOSES` a call; whether the record is now up to date.
function _catchUp(Account storage a, address token) private returns (bool) {
bytes32 series = ProductToken(token).series();
uint32 last = anchor.closedMonth(series);
uint32 month = a.crystallisedMonth;
if (last <= month) return true;
if (a.retired || a.migrated != 0 || a.units == 0) {
// nothing on record to charge, and no mark to move: the closes are passed over
a.crystallisedMonth = last;
return true;
}
(, uint16 bps) = parameters.navFeesOf(token);
for (uint256 i = 0; i < MAX_CLOSES && month != last; i++) {
month = anchor.nextClosedAfter(series, month);
uint256 price = anchor.closedPriceOf(series, month);
_accruePerformance(a, token, bps, price);
emit Crystallised(token, month, price);
}
a.crystallisedMonth = month;
return month == last;
}
/// @dev Above the mark: the floor owes its gain over the mark, every cohort below the price owes its gain
/// and joins the floor, a cohort above the price keeps its basis; then the mark is the price.
function _accruePerformance(Account storage a, address token, uint16 bps, uint256 price) private {
uint256 hwm = _hwm(a, token);
if (price <= hwm || a.units == 0) return; // nothing on record: no gain, and no mark moves
uint256 gain = _gain(a.floorUnits, price, hwm, bps);
uint32[] storage open = _open[token];
uint256 i = 0;
while (i < open.length) {
uint32 id = open[i];
Cohort storage c = _cohort[token][id];
uint256 b = c.basis > hwm ? c.basis : hwm;
if (price > b) {
gain += _gain(c.units, price, b, bps);
a.floorUnits += c.units;
_close(token, id, c.basis); // the last number moves into slot i: look at i again
} else {
i++;
}
}
a.hwm = price;
if (gain != 0) {
a.owedPerformance += gain;
emit Accrued(token, "performance", gain);
}
}
}
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);
}
}
}
}
src/SeriesParameters.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @title SeriesParameters — the tariffs and the gate of every series, in one place, set by governance
/// @notice What used to be a configuration file and an operator's input is on chain here: the entry fee, the
/// exit and switch fee by the age of the units, the management and performance fee rates that
/// accrue inside NAV, and the redemption gate (a share of NAV per window of days, and how long a
/// request may wait). The escrow reads the entry fee, the queue reads the exit and switch fees and
/// the gate, the Calculation Agent reads the NAV fee rates: none of them takes a rate from anyone's
/// hand. Only governance changes a value, through the timelock, within the bounds below; the
/// deployer may fill a series' terms once, at deployment, before governance exists.
/// @notice A change of a tariff reaches only what comes after it (owner, 04.10.2026; review of 03.10.2026,
/// B-01, B-02). Every exit and switch schedule a series has had is kept under a version number; a
/// redemption request carries the versions in force when it was placed and is charged the lower of
/// that schedule and the one in force when it settles. The entry fee is recorded with each deposit by
/// the escrow on the same rule.
/// @dev What the parameters tell the fee ledger before a NAV rate changes.
interface IFeeCheckpoint {
function checkpoint(address token, bool performance) external;
}
contract SeriesParameters {
/// @notice One band of a fee-by-age schedule: `bps` for units younger than `untilDays`. The last band
/// carries `type(uint32).max` and applies for ever.
struct Band {
uint32 untilDays;
uint16 bps;
}
/// @notice The redemption gate: at most `bps` of NAV settled in any `windowDays`; zero bps, no gate.
/// `maxWaitDays` is the rule for the operations Safe (a request older than that is overdue),
/// read off chain.
struct Gate {
uint16 bps;
uint16 windowDays;
uint16 maxWaitDays;
}
/// @notice A series' terms as a reader gets them: the schedules are the ones in force now.
struct Terms {
bool set;
uint16 entryBps;
uint16 managementBps;
uint16 performanceBps;
Gate gate;
Band[] exit;
Band[] switching;
uint128 minRedeemUnits;
}
/// @dev What is stored per series beside the schedules.
struct Core {
bool set;
uint16 entryBps;
uint16 managementBps;
uint16 performanceBps;
Gate gate;
/// @dev The least a redemption request may ask for, unless it is the holder's whole balance: below it
/// the fees of a request round to nothing (review of 03.10.2026, B-16).
uint128 minRedeemUnits;
}
/// @notice Governance (the Governance Safe behind the timelock).
address public immutable governance;
/// @notice May fill a series' terms once, while they are unset: the deployer, at deployment.
address public immutable initializer;
/// @notice Until when the deployer may fill a series' terms: a day, like its right on the queue and the anchor (F-04).
uint64 public immutable initializerUntil;
/// @notice The fee ledger, told before a NAV rate changes so what accrued does so at the old rate (review
/// of 28.09.2026, M-16). Set once: by the deployer at deployment, else by governance.
address public feeLedger;
/// @notice Bounds no change can cross.
uint16 public constant MAX_FEE_BPS = 500;
/// @dev The longest gate window: what the queue keeps of its payout history, so a widened window still counts it.
uint16 public constant MAX_GATE_WINDOW_DAYS = 92;
uint16 public constant MAX_MANAGEMENT_BPS = 300;
uint16 public constant MAX_PERFORMANCE_BPS = 3000;
uint256 public constant MAX_BANDS = 8;
mapping(address => Core) private _terms;
/// @dev Every exit and switch schedule a series has had, in order: the index is the version.
mapping(address => Band[][]) private _exit;
mapping(address => Band[][]) private _switching;
event EntryFeeSet(address indexed token, uint16 bps);
event FeeLedgerSet(address ledger);
event ExitScheduleSet(address indexed token, Band[] bands);
event SwitchScheduleSet(address indexed token, Band[] bands);
event NavFeesSet(address indexed token, uint16 managementBps, uint16 performanceBps);
event GateSet(address indexed token, uint16 bps, uint16 windowDays, uint16 maxWaitDays);
event MinRedeemSet(address indexed token, uint128 units);
error NotGovernance();
error NotInitializer();
error LedgerSet();
error AlreadySet(address token);
error ZeroAddress();
error FeeTooHigh(uint16 bps);
error ManagementTooHigh(uint16 bps);
error PerformanceTooHigh(uint16 bps);
error GateInvalid();
error ScheduleInvalid();
error TermsNotSet(address token);
modifier onlyGovernance() {
if (msg.sender != governance) revert NotGovernance();
_;
}
/// @dev A setter changes terms that exist: a series' terms are filed whole, by `initialise`, and a single
/// setter never marks them as filed with the rest empty (review of 03.10.2026, B-14).
modifier whenSet(address token) {
if (!_terms[token].set) revert TermsNotSet(token);
_;
}
constructor(address governance_, address initializer_) {
if (governance_ == address(0) || initializer_ == address(0)) revert ZeroAddress();
governance = governance_;
initializer = initializer_;
initializerUntil = uint64(block.timestamp + 1 days);
}
// ── Deployment: once per series ─────────────────────────────────────────────────────────
/// @notice Fill a series' terms while they are unset. The deployer at deployment, or governance.
function initialise(
address token,
uint16 entryBps,
Band[] calldata exit,
Band[] calldata switching,
uint16 managementBps,
uint16 performanceBps,
Gate calldata gate
) external {
if (msg.sender != governance && !(msg.sender == initializer && block.timestamp <= initializerUntil)) revert NotInitializer();
if (token == address(0)) revert ZeroAddress();
if (_terms[token].set) revert AlreadySet(token);
_terms[token].set = true;
_setEntry(token, entryBps);
_setSchedule(token, exit, true);
_setSchedule(token, switching, false);
_setNavFees(token, managementBps, performanceBps);
_setGate(token, gate);
}
// ── Governance (through the timelock) ───────────────────────────────────────────────────
function setEntryFee(address token, uint16 bps) external onlyGovernance whenSet(token) {
_setEntry(token, bps);
}
function setExitSchedule(address token, Band[] calldata bands) external onlyGovernance whenSet(token) {
_setSchedule(token, bands, true);
}
function setSwitchSchedule(address token, Band[] calldata bands) external onlyGovernance whenSet(token) {
_setSchedule(token, bands, false);
}
function setNavFees(address token, uint16 managementBps, uint16 performanceBps)
external
onlyGovernance
whenSet(token)
{
// what has accrued so far is settled at the rates that were in force; the new ones apply from here
if (feeLedger != address(0)) {
// performance is settled at the old rate only when that rate changes: a management change alone
// moves no mark (review of 28.09.2026, I-01)
IFeeCheckpoint(feeLedger).checkpoint(token, _terms[token].performanceBps != performanceBps);
}
_setNavFees(token, managementBps, performanceBps);
}
/// @notice The least a redemption request may ask for (a holder may always ask for all he has). Governance,
/// or the deployer within its day while it is unset.
function setMinRedeem(address token, uint128 units) external whenSet(token) {
if (msg.sender != governance) {
bool deployerInWindow = msg.sender == initializer && block.timestamp <= initializerUntil;
if (!deployerInWindow || _terms[token].minRedeemUnits != 0) revert NotGovernance();
}
_terms[token].minRedeemUnits = units;
emit MinRedeemSet(token, units);
}
/// @notice Name the fee ledger, once. The deployer at deployment, else governance.
function setFeeLedger(address ledger) external {
if (msg.sender != governance && !(msg.sender == initializer && block.timestamp <= initializerUntil)) {
revert NotInitializer();
}
if (ledger == address(0)) revert ZeroAddress();
if (feeLedger != address(0)) revert LedgerSet();
feeLedger = ledger;
emit FeeLedgerSet(ledger);
}
function setGate(address token, Gate calldata gate) external onlyGovernance whenSet(token) {
_setGate(token, gate);
}
// ── Views the contracts read ────────────────────────────────────────────────────────────
function isSet(address token) external view returns (bool) {
return _terms[token].set;
}
function entryBpsOf(address token) external view returns (uint16) {
return _terms[token].entryBps;
}
/// @notice The exit fee for units `ageDays` old under the schedule in force now. Nothing set, nothing charged.
function exitBpsFor(address token, uint256 ageDays) external view returns (uint16) {
return _bpsFor(_latest(_exit[token]), ageDays);
}
/// @notice The switch fee for units `ageDays` old under the schedule in force now.
function switchBpsFor(address token, uint256 ageDays) external view returns (uint16) {
return _bpsFor(_latest(_switching[token]), ageDays);
}
/// @notice The exit and the switch fee a request placed under versions `exitVersion` and `switchVersion`
/// pays for units `ageDays` old: for each, the lower of that schedule and the one in force now.
function feesFor(address token, uint256 ageDays, uint32 exitVersion, uint32 switchVersion)
external
view
returns (uint16 exitBps, uint16 switchBps)
{
exitBps = _lower(_exit[token], exitVersion, ageDays);
switchBps = _lower(_switching[token], switchVersion, ageDays);
}
/// @notice The versions of the exit and switch schedules in force now.
function versionsOf(address token) external view returns (uint32 exitVersion, uint32 switchVersion) {
uint256 e = _exit[token].length;
uint256 w = _switching[token].length;
return (e == 0 ? 0 : uint32(e - 1), w == 0 ? 0 : uint32(w - 1));
}
function minRedeemOf(address token) external view returns (uint128) {
return _terms[token].minRedeemUnits;
}
function navFeesOf(address token) external view returns (uint16 managementBps, uint16 performanceBps) {
Core storage t = _terms[token];
return (t.managementBps, t.performanceBps);
}
function gateOf(address token) external view returns (Gate memory) {
return _terms[token].gate;
}
function exitScheduleOf(address token) external view returns (Band[] memory) {
return _latest(_exit[token]);
}
function switchScheduleOf(address token) external view returns (Band[] memory) {
return _latest(_switching[token]);
}
/// @notice Everything at once, for the console and the Calculation Agent.
function termsOf(address token) external view returns (Terms memory) {
Core storage t = _terms[token];
return Terms({
set: t.set,
entryBps: t.entryBps,
managementBps: t.managementBps,
performanceBps: t.performanceBps,
gate: t.gate,
exit: _latest(_exit[token]),
switching: _latest(_switching[token]),
minRedeemUnits: t.minRedeemUnits
});
}
// ── Internals ───────────────────────────────────────────────────────────────────────────
function _bpsFor(Band[] memory bands, uint256 ageDays) private pure returns (uint16) {
for (uint256 i = 0; i < bands.length; i++) {
if (ageDays < bands[i].untilDays) return bands[i].bps;
}
return 0;
}
/// @dev The schedule in force now: the last version, or none.
function _latest(Band[][] storage versions) private view returns (Band[] memory) {
uint256 n = versions.length;
if (n == 0) return new Band[](0);
return versions[n - 1];
}
/// @dev The lower of the rate under `version` and the rate in force now. A version the series never had
/// is read as the current one.
function _lower(Band[][] storage versions, uint32 version, uint256 ageDays) private view returns (uint16 bps) {
uint256 n = versions.length;
if (n == 0) return 0;
bps = _bpsFor(versions[n - 1], ageDays);
if (version < n - 1) {
uint16 then = _bpsFor(versions[version], ageDays);
if (then < bps) bps = then;
}
}
function _setEntry(address token, uint16 bps) private {
if (bps > MAX_FEE_BPS) revert FeeTooHigh(bps);
_terms[token].entryBps = bps;
emit EntryFeeSet(token, bps);
}
/// @dev A schedule is 1 to MAX_BANDS bands, each within the cap, strictly ascending in `untilDays`, the
/// last one open-ended — so every age finds exactly one band.
function _setSchedule(address token, Band[] calldata bands, bool isExit) private {
if (bands.length == 0 || bands.length > MAX_BANDS) revert ScheduleInvalid();
if (bands[bands.length - 1].untilDays != type(uint32).max) revert ScheduleInvalid();
Band[][] storage versions = isExit ? _exit[token] : _switching[token];
Band[] storage dst = versions.push();
uint32 last = 0;
for (uint256 i = 0; i < bands.length; i++) {
if (bands[i].bps > MAX_FEE_BPS) revert FeeTooHigh(bands[i].bps);
if (i != 0 && bands[i].untilDays <= last) revert ScheduleInvalid();
last = bands[i].untilDays;
dst.push(bands[i]);
}
if (isExit) emit ExitScheduleSet(token, bands);
else emit SwitchScheduleSet(token, bands);
}
function _setNavFees(address token, uint16 managementBps, uint16 performanceBps) private {
if (managementBps > MAX_MANAGEMENT_BPS) revert ManagementTooHigh(managementBps);
if (performanceBps > MAX_PERFORMANCE_BPS) revert PerformanceTooHigh(performanceBps);
_terms[token].managementBps = managementBps;
_terms[token].performanceBps = performanceBps;
emit NavFeesSet(token, managementBps, performanceBps);
}
function _setGate(address token, Gate calldata gate) private {
if (gate.bps > 10_000 || (gate.bps != 0 && gate.windowDays == 0)) revert GateInvalid();
if (gate.windowDays > MAX_GATE_WINDOW_DAYS) revert GateInvalid();
_terms[token].gate = gate;
emit GateSet(token, gate.bps, gate.windowDays, gate.maxWaitDays);
}
}
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);
}
}
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.