Verified contractPartialMIT
HoldingPeriodModule
Address0xea2aae28d27df9e6639cc82745a77e9c82dac438
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.22
- Same code
1 more contract
Details
- Compiler
- solc 0.8.22+commit.4fc1097e
- Language
- solidity
- Optimization
- Yes, 100 runs
- EVM version
- paris
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,415,116
- Creation transaction
- 0xc1850b5d29…c0aae3c649
10 files
- src/contracts/modules/HoldingPeriodModule.solmain11.01 KB
- @openzeppelin/contracts/access/Ownable.sol3.1 KB
- @openzeppelin/contracts/access/Ownable2Step.sol2.48 KB
- @openzeppelin/contracts/utils/Context.sol963 B
- @openzeppelin/contracts/utils/introspection/IERC165.sol871 B
- src/contracts/interfaces/ICompliance.sol5.36 KB
- src/contracts/interfaces/IIdentityRegistry.sol34.06 KB
- src/contracts/interfaces/IPartitionInfo.sol5.23 KB
- src/contracts/lib/BaseComplianceModule.sol3.05 KB
- src/contracts/lib/ReasonCodes.sol7.45 KB
src/contracts/modules/HoldingPeriodModule.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.22;
import {Ownable2Step, Ownable} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {IComplianceEvents} from "../interfaces/ICompliance.sol";
import {IIdentityRegistry} from "../interfaces/IIdentityRegistry.sol";
import {IPartitionInfo} from "../interfaces/IPartitionInfo.sol";
import {BaseComplianceModule} from "../lib/BaseComplianceModule.sol";
import {ReasonCodes} from "../lib/ReasonCodes.sol";
/// @title HoldingPeriodModule
/// @notice Partition-aware compliance module enforcing the per-holder holding clock.
/// @dev Gates on the SENDER's per-holder-per-partition `holdingEnd(from, partition)` clock
/// (not the partition-wide lockupEnd). A recipient with a restricted claim cannot
/// receive a transfer until the sender's holding period has elapsed.
///
/// MINT SAFE: On a mint (`from == address(0)`) the gate reads
/// `holdingEnd(address(0), partition)`, which is the plain mapping default `0`
/// (NOT type(uint256).max — that sentinel is only for `lockupEnd`). So
/// `block.timestamp < 0` is false → mints always pass. Every `IPartitionInfo`
/// implementor MUST return `0` (not max) for an unset `(holder, partition)`.
///
/// NO DISTRIBUTOR CARVE-OUT: Unlike `LockupModule`, this module has no early-return
/// for `DISTRIBUTOR` claim holders. Distributors bypass the lockup (LockupModule)
/// but remain subject to the holding-period sender clock here.
/// Do NOT add a DISTRIBUTOR carve-out: it would let a restricted-person distributor receive
/// from a restricted-person seller before the holding period ends, violating the holding period.
///
/// GOVERNANCE: `registry` and `token` are `immutable` (address types). `restrictedClaimTypes`
/// is stored in regular storage (dynamic arrays cannot be `immutable` in Solidity) and is
/// live-updatable post-deploy via `setRestrictedClaimType` (`onlyOwner`, `Ownable2Step` —
/// typically the TimelockController). The set must never go empty — removing the last entry
/// reverts `EmptyClaimTypes` (an empty set here would silently and permanently disable the
/// holding-period gate for every recipient).
///
/// BINDING GATE: In deployments where `holdingPeriod > lockupPeriod` this
/// module is the operative compliance gate. In the standard lockup profile (both 365d)
/// `lockupEnd >= holdingEnd` for every holder, so LockupModule is always the longer
/// block — this module is retained for holding-period audit trail and wash confirmation.
///
/// NEVER reverts during moduleCheck — veto is always (false, reasonCode), not revert.
contract HoldingPeriodModule is Ownable2Step, IComplianceEvents, BaseComplianceModule {
// ─────────────────────────── errors ───────────────────────────────────────
error ZeroAddress();
error EmptyClaimTypes();
error TooManyClaimTypes();
error DuplicateClaimType(bytes32 claimType);
// ─────────────────────────── constants ────────────────────────────────────
/// @notice Maximum number of restricted claim types (bounded loop guard).
uint256 public constant MAX_RESTRICTED_CLAIM_TYPES = 10;
// ─────────────────────────── state ────────────────────────────────────────
/// @notice IdentityRegistry — consulted for `hasClaim` on `to` (restricted class check).
IIdentityRegistry public immutable registry;
/// @notice Token read for `holdingEnd(from, partition)` — the sender's per-holder clock.
/// `immutable` (address value type). Set once in constructor.
IPartitionInfo public immutable token;
/// @dev Restricted claim types (OR logic). Governance-settable via `setRestrictedClaimType`.
/// Dynamic arrays cannot be `immutable` in Solidity — stored in regular storage.
bytes32[] private _restrictedClaimTypes;
/// @dev O(1) membership check companion to `_restrictedClaimTypes`, mirroring
/// `IdentityRegistry`'s `_isRequired` mapping pattern.
mapping(bytes32 => bool) private _isRestrictedClaimType;
// ─────────────────────────── constructor ──────────────────────────────────
/// @param registry_ IIdentityRegistry for `hasClaim` lookups on `to`.
/// @param token_ IPartitionInfo for `holdingEnd(from, partition)` reads.
/// @param restrictedClaimTypes_ Claim types triggering the holding gate (e.g. `["US_PERSON"]`).
/// Non-empty, max `MAX_RESTRICTED_CLAIM_TYPES` (10).
/// @param owner_ Initial owner (governance — typically the TimelockController).
constructor(
IIdentityRegistry registry_,
IPartitionInfo token_,
bytes32[] memory restrictedClaimTypes_,
address owner_
) Ownable(owner_) {
if (address(registry_) == address(0)) revert ZeroAddress();
if (address(token_) == address(0)) revert ZeroAddress();
if (restrictedClaimTypes_.length == 0) revert EmptyClaimTypes();
if (restrictedClaimTypes_.length > MAX_RESTRICTED_CLAIM_TYPES) revert TooManyClaimTypes();
registry = registry_;
token = token_;
// Duplicates would permanently desync the array from its membership mapping:
// setRestrictedClaimType(..., false) clears the mapping but `break`s after removing a
// single copy, so the leftover copies stay enforced by moduleCheck even though
// governance believes the type was removed, and re-adding pushes yet another. Reject at
// construction — the governance setter is idempotent and cannot introduce a duplicate.
_restrictedClaimTypes = restrictedClaimTypes_;
for (uint256 i = 0; i < restrictedClaimTypes_.length; i++) {
bytes32 ct = restrictedClaimTypes_[i];
if (_isRestrictedClaimType[ct]) revert DuplicateClaimType(ct);
_isRestrictedClaimType[ct] = true;
}
}
// ─────────────────────────── governance ───────────────────────────────────
/// @notice Add or remove a claim type from the restricted-recipient set.
/// @dev Idempotent: no-op (no state change, no event) if `required` already matches the
/// current state. Mirrors `IdentityRegistry.setRequiredCertification`'s swap-and-pop
/// removal. Reverts `EmptyClaimTypes` if removal would leave the set empty — this set
/// must never go empty (unlike `CertificationModule`'s vacuous-pass sets), or the
/// holding-period gate would be silently and permanently disabled for every recipient.
/// Emits `ClaimSetUpdated("restrictedClaimTypes", claimType, required)`.
function setRestrictedClaimType(bytes32 claimType, bool required) external onlyOwner {
if (required) {
if (_isRestrictedClaimType[claimType]) return; // idempotent no-op — no state change, no event
if (_restrictedClaimTypes.length >= MAX_RESTRICTED_CLAIM_TYPES) revert TooManyClaimTypes();
_isRestrictedClaimType[claimType] = true;
_restrictedClaimTypes.push(claimType);
} else {
if (!_isRestrictedClaimType[claimType]) return; // idempotent no-op — no state change, no event
if (_restrictedClaimTypes.length == 1) revert EmptyClaimTypes();
_isRestrictedClaimType[claimType] = false;
uint256 len = _restrictedClaimTypes.length;
for (uint256 i = 0; i < len; i++) {
if (_restrictedClaimTypes[i] == claimType) {
_restrictedClaimTypes[i] = _restrictedClaimTypes[len - 1];
_restrictedClaimTypes.pop();
break;
}
}
}
emit ClaimSetUpdated("restrictedClaimTypes", claimType, required);
}
// ─────────────────────────── IComplianceModule ────────────────────────
/// @notice Partition-aware holding period check.
/// @dev Iterates `restrictedClaimTypes` (OR logic). If the RECIPIENT holds any
/// restricted claim AND `block.timestamp < holdingEnd(from, partition)` (the
/// SENDER's per-holder clock), returns (false, HOLDING_PERIOD_NOT_MET).
///
/// MINT PASS: When `from == address(0)`, `holdingEnd(0, partition)` returns
/// the plain mapping default `0`, so `block.timestamp < 0` is false → passes.
/// The Token's `holdingEnd` getter MUST return `0` (not max) for unset entries.
///
/// BOUNDARY: `>=` passes — only strict `<` vetoes.
/// Single error code regardless of which claim matched.
/// NEVER reverts (BaseComplianceModule invariant).
function moduleCheck(
bytes32 partition,
address from,
address to,
uint256 /* amount */
) external view returns (bool ok, bytes32 reasonCode) {
// Check if recipient holds any restricted claim (OR logic, bounded loop)
uint256 len = _restrictedClaimTypes.length;
for (uint256 i = 0; i < len; i++) {
if (registry.hasClaim(to, _restrictedClaimTypes[i])) {
// Restricted recipient: veto if sender's holding period not yet elapsed
// from == address(0) → holdingEnd(0, partition) == 0 → block.timestamp < 0 is false → passes
if (block.timestamp < token.holdingEnd(from, partition)) {
return (false, ReasonCodes.HOLDING_PERIOD_NOT_MET);
}
// Holding period elapsed — pass
return (true, bytes32(0));
}
}
// Non-restricted recipient — pass regardless
return (true, bytes32(0));
}
// ─────────────────────────── view helpers ─────────────────────────────────
/// @notice Returns the configured restricted claim types (for off-chain inspection).
function restrictedClaimTypes() external view returns (bytes32[] memory) {
return _restrictedClaimTypes;
}
}
@openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
@openzeppelin/contracts/access/Ownable2Step.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {Ownable} from "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This extension of the {Ownable} contract includes a two-step mechanism to transfer
* ownership, where the new owner must call {acceptOwnership} in order to replace the
* old one. This can help prevent common mistakes, such as transfers of ownership to
* incorrect accounts, or to contracts that are unable to interact with the
* permission system.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*
* Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
@openzeppelin/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;
}
}
@openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @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/contracts/interfaces/ICompliance.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.22;
/// @title IComplianceEvents
/// @notice Shared governance events for all ERC-1400 compliance modules.
/// @dev Single-owner discipline (same as ReasonCodes.sol): defined ONCE here,
/// consumed by KYCRequiredModule, SanctionsModule, ConcentrationCapModule.
/// The governance handler indexes topic0 of ComplianceRuleUpdated to detect any
/// compliance-parameter change across all modules — requires a single shared definition.
interface IComplianceEvents {
/// @notice Emitted when a governance-gated compliance rule parameter is updated.
/// @dev Frozen signature: `param` is a bytes32 short-string (fits in 32 bytes),
/// `indexed` so consumers can topic-filter by rule without decoding calldata.
/// `param` naming (not `rule`) matches architecture §8 listing.
/// `uint256` arg type (not `uint64`) matches architecture generic form.
/// Modules inherit this interface — do NOT redeclare the event per-module.
event ComplianceRuleUpdated(bytes32 indexed param, uint256 oldValue, uint256 newValue);
/// @notice Emitted when a claim/cert type is added to or removed from a module's
/// governed claim-list set (e.g. restricted claim types, required cert types).
/// @dev `ComplianceRuleUpdated` doesn't fit this shape (scalar uint256 old/new only) —
/// mirrors `IdentityRegistry.RequiredCertificationUpdated`'s dedicated-event pattern.
/// `param` identifies which set on the module (e.g. "restrictedClaimTypes",
/// "accreditedRequiredCertTypes", "offshoreRequiredCertTypes").
event ClaimSetUpdated(bytes32 indexed param, bytes32 indexed claimType, bool required);
}
/// @title IComplianceModule
/// @notice Partition-aware compliance module interface for ERC-1400.
/// @dev ALWAYS returns (bool, bytes32 reasonCode) — NEVER reverts.
/// Partition `bytes32(0)` is the default single-tranche partition.
/// The engine calls moduleCheck; modules must not revert — revert crashes the
/// transfer pipeline.
/// An unset partition closeDate (sentinel type(uint256).max) causes LockupModule to
/// veto restricted-class recipients (period not started) rather than revert.
/// Zero-address `to` guard is CENTRALIZED in the engine — modules do NOT
/// repeat it.
interface IComplianceModule {
/// @notice Partition-aware compliance check called by the engine for each attached module.
/// @param partition The ERC-1410 partition. `bytes32(0)` = default single-tranche partition.
/// @param from Sender. `address(0)` = mint path (modules may allow/deny mints per logic).
/// @param to Recipient. Engine guarantees `to != address(0)` before this is called.
/// @param amount Token amount (wei).
/// @return ok True if this module allows the transfer.
/// @return reasonCode Opaque bytes32 reason code (from ReasonCodes.sol) when ok == false;
/// bytes32(0) when ok == true.
function moduleCheck(
bytes32 partition,
address from,
address to,
uint256 amount
) external view returns (bool ok, bytes32 reasonCode);
}
/// @title ICompliance
/// @notice Partition-native ERC-1400 compliance dispatch surface.
/// @dev One instance per asset. No `asset` param — modules are bound
/// to a single asset's registry/token at construction.
/// `bytes32(0)` is the default single-tranche partition.
interface ICompliance {
/// @notice Emitted when a compliance module is attached. Frozen signature.
/// `indexed` so the governance handler can topic-filter per module address.
event ModuleAttached(address indexed module);
/// @notice Emitted when a compliance module is detached. Frozen signature.
/// `indexed` so the governance handler can topic-filter per module address.
event ModuleDetached(address indexed module);
/// @notice Partition-native compliance check. Runs engine fast-path first, then module walk.
/// @dev View — does not revert under normal operation. If an attached module reverts inside
/// `moduleCheck`, the revert propagates (fail-closed): a reverting
/// module denies the transfer and never produces an allow. Callers must handle revert.
/// Returns `(false, reasonCode)` on any veto; `(true, bytes32(0))` on all-pass.
/// @param partition ERC-1410 partition key; `bytes32(0)` = default single-tranche.
/// @param from Sender. `address(0)` = mint — NOT rejected by the engine.
/// @param to Recipient.
/// @param amount Token amount (wei).
function canTransferByPartition(
bytes32 partition,
address from,
address to,
uint256 amount
) external view returns (bool ok, bytes32 reasonCode);
/// @notice Attach a compliance module (ordered; first-veto-wins walk order).
function addModule(address module) external;
/// @notice Detach a compliance module.
function removeModule(address module) external;
/// @notice Return the attached module list in attach order.
function modules() external view returns (address[] memory);
}
src/contracts/interfaces/IIdentityRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.22;
/// @title IIdentityRegistry
/// @notice Whitelist registry consulted on every Token transfer. Maps each registered
/// investor wallet to an opaque off-chain-derived identity hash.
/// Also stores typed compliance claims (US_PERSON, DISTRIBUTOR) and KYC timestamps
/// for partition-level transfer gating, sanctions conclusion
/// (blocked + freshness) via a per-wallet blocked-reasons bitmask,
/// one-wallet-per-identity + admin-mediated recovery, and
/// investor certifications with EIP-712 investor-signed mode.
/// @dev `revokeIdentity` is INTENTIONALLY ABSENT for MVP. Wallet revoke + replace
/// ships Post-MVP via UUPS upgrade with an extended interface; do NOT add it here.
///
/// @dev Claim-topic convention (ERC-735 topic model):
/// Topics are keccak256 hashes of human-readable strings, stored as bytes32.
/// - US_PERSON = keccak256("US_PERSON") — restricted-person conclusion.
/// - DISTRIBUTOR = keccak256("DISTRIBUTOR") — lockup-regime distributor carve-out.
/// Absence of US_PERSON encodes NON_US (no separate flag stored).
///
/// @dev Blocked-reasons bitmask: one `uint256 _blockedReasons[wallet]` field,
/// one bit per reason — SANCTIONS=1, AFFILIATE=2, ADMIN=4. Each writer touches only
/// its own bit (|= / &= ~bit), so two reasons can be active simultaneously.
///
/// @dev One-wallet-per-identity: `registerIdentity` rejects a second wallet for
/// an already-bound onchainIdHash. The zero identity (bytes32(0)) is exempt — see
/// `walletOf` NatSpec. Recovery migrates an unblocked binding old→new with state carry-over.
///
/// @dev Certifications: typed investor covenants from the Subscription Agreement
/// (lockup §I / §G / §K). Two evidence modes per call — hash-only (issuer-asserted, owner-gated)
/// or investor EIP-712 signed (permissionless, nonce + deadline replay guard).
/// The proof-level (`_certInvestorSigned`) is stored; attestationHash is emit-only.
interface IIdentityRegistry {
// ─────────────────────────── types ───────────────────────────
/// @notice A recorded Rule 506(c) accreditation verification.
/// @dev Declared on the interface (not `IdentityRegistry`) so `accreditation()`'s
/// return type is shared with `AccreditationModule` as `IIdentityRegistry.AccreditationRecord`
/// — do not redeclare this struct elsewhere; two independent declarations would be
/// distinct types (same reason the `Tranche` enum has a single declaration).
/// Field order: `verifiedAt` alone in slot 0; the three `bytes32` fields each
/// occupy a full slot.
/// @param verifiedAt Unix timestamp of verification; 0 = never verified (sentinel).
/// Freshness is `verifiedAt + AccreditationModule.accreditationWindow`.
/// @param method Verification method label (e.g. keccak256 of a method name).
/// @param providerId Opaque identifier of the verification provider.
/// @param evidenceHash keccak256 of the off-chain evidence document — emit + store, not itself the evidence.
///
/// @dev ⚠️ THERE IS DELIBERATELY NO `expiresAt` FIELD. `AccreditationModule` is the sole
/// freshness authority and derives expiry as `verifiedAt + accreditationWindow`.
/// Do not add a per-record expiry without also making it the authority — two
/// sources of expiry will disagree, and the stored one will look authoritative
/// while gating nothing.
struct AccreditationRecord {
uint64 verifiedAt;
bytes32 method;
bytes32 providerId;
bytes32 evidenceHash;
}
// ─────────────────────────── errors ───────────────────────────
// ──────── source-role errors ────────
/// @notice Thrown when msg.sender does not hold the required source role.
error UnauthorizedSource();
/// @notice Thrown by setBlockedReason / clearBlockedReason when reason == SANCTIONS.
/// @dev SANCTIONS is sanctions-source-exclusive; compliance officer owns AFFILIATE/ADMIN only.
/// The reason IS known but this role doesn't own it.
error ReasonNotOwnedByRole(bytes32 reason);
/// @notice Thrown by setKycSource / setSanctionsSource / setComplianceOfficer on address(0).
error ZeroSourceAddress();
/// @notice Thrown by setBlockedReasonWithFreeze / setSanctionsBlockedWithFreeze when tokenContract is address(0).
error InvalidTokenContract();
/// @notice Thrown when a second wallet attempts to register an already-bound identity hash.
/// @dev bytes32(0) is exempt — the zero identity never arises from off-chain canonicalization.
error IdentityAlreadyBound();
/// @notice Thrown by recoverWallet when the supplied onchainIdHash has no registered wallet.
error IdentityNotBound();
/// @notice Thrown by clearBlockedReason when the named reason's bit is not currently set.
/// @param ownedReason The reason the caller tried to clear.
/// @param mask The current _blockedReasons bitmask (the bit is absent).
error BlockedReasonMismatch(bytes32 ownedReason, uint256 mask);
/// @notice Thrown by setBlockedReason / clearBlockedReason when an unrecognized reason label
/// is passed (not SANCTIONS, AFFILIATE, or ADMIN).
/// @dev Thrown inside _bit(). bytes32(0) also triggers this — zero is not a valid reason label.
error UnknownBlockReason(bytes32 reason);
/// @notice Thrown by recoverWallet when the old wallet has any freeze bit set.
/// @dev Each block must be resolved through its proper channel before recovery:
/// SANCTIONS → clean re-screen via setSanctionsScreening;
/// AFFILIATE/ADMIN → clearBlockedReason by compliance officer.
/// @param blockedReasonsMask The current _blockedReasons bitmask (non-zero).
error WalletBlockedCannotRecover(uint256 blockedReasonsMask);
// ─────────────────────────── events ───────────────────────────
/// @notice Emitted when an investor wallet is registered.
event IdentityRegistered(address indexed wallet, bytes32 indexed onchainId);
/// @notice Emitted when a single typed compliance claim is set or cleared.
/// @dev Emitted by BOTH `setClaim` and `setIdentityClaims` (per claim). Emit-only attestationHash.
event ClaimChanged(
address indexed wallet,
bytes32 indexed claimType,
bool value,
bytes32 attestationHash
);
/// @notice Emitted once per `setIdentityClaims` call to record the KYC timestamp.
/// @dev Emitted by `setIdentityClaims` ONLY. Emit-only attestationHash.
event KYCVerified(address indexed wallet, uint64 kycVerifiedAt, bytes32 attestationHash);
/// @notice Emitted when a wallet's sanctions-screening conclusion changes.
/// @dev Reflects SANCTIONS bit only. Emitted ONLY by setSanctionsScreening.
event SanctionsStatusChanged(address indexed wallet, bool blocked);
/// @notice Emitted on every setSanctionsScreening call to anchor the off-chain record.
/// @dev screenedAt = block.timestamp (not a caller arg). screeningHash emit-only.
event SanctionsScreeningCompleted(
address indexed wallet,
uint64 screenedAt,
bytes32 screeningHash
);
/// @notice Emitted when a wallet is blocked for a reason (AFFILIATE, ADMIN, etc.).
/// @dev Emitted by setBlockedReason on a real 0→1 bit transition only.
event WalletBlocked(address indexed wallet, bytes32 reason);
/// @notice Emitted when a specific blocked reason is cleared for a wallet.
/// @dev Carries the reason — the bitmask clears one reason at a time, so the
/// audit record names which reason was lifted (others may remain set).
/// wallet is indexed to pair with WalletBlocked.
/// @param wallet The investor's wallet address.
/// @param reason The bytes32 reason label that was cleared (AFFILIATE, ADMIN, etc.).
event WalletUnblocked(address indexed wallet, bytes32 reason);
// ──────── source-role events ────────
/// @notice Emitted when the KYC source address is updated.
event KycSourceUpdated(address indexed newSource);
/// @notice Emitted when the sanctions source address is updated.
event SanctionsSourceUpdated(address indexed newSource);
/// @notice Emitted when the compliance officer address is updated.
event ComplianceOfficerUpdated(address indexed newSource);
/// @notice Emitted when the accreditation source address is updated.
event AccreditationSourceUpdated(address indexed newSource);
/// @notice Emitted when an accreditation verification is recorded for a wallet.
/// @dev Carries `verifiedAt` — the timestamp freshness is actually computed from — so an
/// indexer needs no follow-up `accreditation(wallet)` read.
///
/// ⚠️ SIGNATURE IS FROZEN. Changing any parameter type moves `topic0`, and an
/// indexer filtering on the old signature then stops matching SILENTLY — it does
/// not mis-decode, it sees nothing at all. Any change here requires re-registering
/// every webhook against the new signature.
///
/// `indexed` on `method` mirrors `ClaimChanged`'s `claimType`.
event AccreditationVerified(
address indexed wallet,
bytes32 indexed method,
bytes32 providerId,
uint64 verifiedAt,
bytes32 evidenceHash
);
/// @notice Emitted when an identity binding is moved from one wallet to another.
/// @dev FROZEN signature — the governance handler / compliance_events indexes this.
/// All three args are indexed (≤32-byte value types, fully recoverable from topics).
/// Adding `indexed` does NOT change the event selector (topic0).
/// There is ONE recovery event — not a separate WalletRecovered.
/// @param oldWallet The wallet whose registration was cleared.
/// @param newWallet The wallet now bound to the identity.
/// @param identity The onchainIdHash that was rebound (= onchainIdHash arg to recoverWallet).
event IdentityRebound(
address indexed oldWallet,
address indexed newWallet,
bytes32 indexed identity
);
// ─────────────────────────── writes ───────────────────────────
// ──────────── source-role writes ─────────────────
/// @notice Set the KYC source address. onlyOwner.
/// @dev The kycSource may call registerIdentity, setClaim, setIdentityClaims.
/// Default = admin (set in initialize). Reverts ZeroSourceAddress on address(0).
function setKycSource(address source) external;
/// @notice Set the sanctions source address. onlyOwner.
/// @dev The sanctionsSource is the EXCLUSIVE SANCTIONS bit writer via setSanctionsScreening.
/// Default = admin (set in initialize). Reverts ZeroSourceAddress on address(0).
function setSanctionsSource(address source) external;
/// @notice Set the compliance officer address. onlyOwner.
/// @dev The complianceOfficer may call setCertifications (hash-only branch),
/// setBlockedReason, and clearBlockedReason (AFFILIATE/ADMIN only).
/// Default = admin (set in initialize). Reverts ZeroSourceAddress on address(0).
function setComplianceOfficer(address source) external;
/// @notice Set the accreditation source address. onlyOwner.
/// @dev The accreditationSource is the EXCLUSIVE writer of setAccreditationVerification —
/// segregated from kycSource/sanctionsSource (least privilege, R-7).
/// Default = admin (set in initialize, greenfield deploys only — see
/// `setAccreditationVerification` NatSpec for the upgrade runbook step).
/// Reverts ZeroSourceAddress on address(0).
function setAccreditationSource(address source) external;
// ──────────── source-role reads ──────────────────
/// @notice Returns the current KYC source address.
function kycSource() external view returns (address);
/// @notice Returns the current sanctions source address.
function sanctionsSource() external view returns (address);
/// @notice Returns the current compliance officer address.
function complianceOfficer() external view returns (address);
/// @notice Returns the current accreditation source address.
function accreditationSource() external view returns (address);
// ─────────────────────────── writes ───────────────────────────
/// @notice Register a wallet with its off-chain identity hash. onlyKycSource.
/// @dev Reverts IdentityAlreadyBound if onchainIdHash (non-zero) is already bound to another wallet.
/// @param wallet The investor's wallet address.
/// @param onchainIdHash keccak256 of the canonical KYC claim payload.
function registerIdentity(address wallet, bytes32 onchainIdHash) external;
/// @notice Set or clear a single typed compliance claim for a wallet. onlyKycSource.
/// @dev Does NOT update kycVerifiedAt. Emits ClaimChanged only.
function setClaim(
address wallet,
bytes32 claimType,
bool value,
bytes32 attestationHash
) external;
/// @notice Batch-set typed claims + KYC timestamp in a single tx. onlyKycSource.
/// @dev Reverts ClaimArrayLengthMismatch() if array lengths differ.
function setIdentityClaims(
address wallet,
bytes32[] calldata claimTypes,
bool[] calldata values,
uint64 kycVerifiedAt,
bytes32 attestationHash
) external;
/// @notice Record a sanctions-screening conclusion. onlySanctionsSource.
/// @dev Sets or clears ONLY the SANCTIONS bit. Always stamps sanctionsScreenedAt.
function setSanctionsScreening(
address wallet,
bool blocked,
bytes32 screeningHash
) external;
/// @notice Set a blocked-reason bit for a wallet. onlyComplianceOfficer. Set-only (clear via clearBlockedReason).
/// @dev Guarded on 0→1 transition — repeat call with an already-set reason is a no-op.
/// Reverts ReasonNotOwnedByRole if reason == SANCTIONS (use setSanctionsScreening instead).
function setBlockedReason(address wallet, bytes32 reason) external;
/// @notice Clear a specific blocked-reason bit for a wallet. onlyComplianceOfficer.
/// @dev Clears ONLY the named reason's bit (&= ~bit). Structural isolation — cannot disturb
/// another reason's bit. Reverts BlockedReasonMismatch if that bit is not currently set
/// (a compliance clear of a reason that isn't active is an operator error, not a no-op).
/// Asymmetry with setBlockedReason (intentional): set on already-set bit = silent no-op;
/// clear on not-set bit = explicit revert (audit signal).
/// ownedReason == bytes32(0) or unknown label reverts UnknownBlockReason (via _bit).
/// Note: setSanctionsScreening does its own inline SANCTIONS-bit clear — it does NOT
/// route through clearBlockedReason.
/// @param wallet Investor wallet address.
/// @param ownedReason The bytes32 reason label whose bit to clear (AFFILIATE, ADMIN, etc.).
function clearBlockedReason(address wallet, bytes32 ownedReason) external;
/// @notice Migrate an identity binding from the old wallet to a new one. Admin-only.
/// @dev Recovery is ONLY permitted when the old wallet has NO freeze bits set
/// (_blockedReasons == 0). Each block must be resolved through its proper channel first:
/// SANCTIONS → setSanctionsScreening(clean); AFFILIATE/ADMIN → clearBlockedReason.
/// Carries over canonical per-wallet state to newWallet: _claims topics (US_PERSON,
/// DISTRIBUTOR, ...), _kycVerifiedAt, _sanctionsScreenedAt.
/// _blockedReasons is NOT carried over (guard guarantees mask == 0; new wallet starts clean).
/// Old wallet's state is fully zeroed after copy.
/// Reverts IdentityNotBound if onchainIdHash is unregistered.
/// Reverts WalletBlockedCannotRecover if any freeze bit is set.
/// Reverts InvalidWalletAddress if newWallet is the zero address.
/// Reverts AlreadyRegistered if newWallet is already bound to an identity.
/// Emits IdentityRebound(oldWallet, newWallet, onchainIdHash) — the single recovery event.
/// @param onchainIdHash The identity hash whose binding to move.
/// @param newWallet The new wallet to bind this identity to.
function recoverWallet(bytes32 onchainIdHash, address newWallet) external;
// ──── accreditation writes ───────────────────────────────
/// @notice Record a Rule 506(c) accreditation verification for a wallet. onlyAccreditationSource.
/// @dev TWO-STEP WORKFLOW BY DESIGN: this alone does not make a wallet pass
/// `AccreditationModule.moduleCheck`, which requires BOTH `hasClaim(wallet,
/// ACCREDITED)` (set separately by `kycSource` via `setClaim`/`setIdentityClaims`)
/// AND a fresh record from this setter. Neither role alone is sufficient; both
/// calls are required, in either order — calling only this setter leaves the
/// wallet blocked (fails closed, the safe direction).
/// Overwrite semantics — re-verification replaces the prior record (same shape as
/// `setSanctionsScreening` re-stamping); no "already verified" revert.
/// Reverts InvalidWalletAddress on `wallet == address(0)`.
/// Reverts InvalidEvidenceHash on `evidenceHash == bytes32(0)`.
/// Reverts InvalidVerificationTimestamp on `verifiedAt == 0` — 0 is the
/// never-verified sentinel that `AccreditationModule` keys off; a stored record
/// with `verifiedAt == 0` would silently read as "never verified" despite emitting
/// an audit event.
/// Emits AccreditationVerified(wallet, method, providerId, verifiedAt, evidenceHash).
/// Takes NO expiry parameter — expiry is derived as
/// `verifiedAt + AccreditationModule.accreditationWindow`, never supplied per record.
/// @param wallet The investor's wallet address.
/// @param method Verification method label.
/// @param providerId Opaque identifier of the verification provider.
/// @param verifiedAt Unix timestamp of verification (must be non-zero).
/// @param evidenceHash keccak256 of the off-chain evidence document.
function setAccreditationVerification(
address wallet,
bytes32 method,
bytes32 providerId,
uint64 verifiedAt,
bytes32 evidenceHash
) external;
// ──── regulatory reporting writes ───────────────────────────────
/// @notice Block wallet (AFFILIATE/ADMIN reason) AND emit regulatory reporting events for a partition.
/// @dev Calls the same block logic as setBlockedReason (0→1 guard).
/// amount derived from tokenContract.balanceOfByPartition (NOT caller-supplied).
/// Emits WalletBlocked (on real 0→1 transition) + FrozenTransferRecorded + FrozenAssetHeld.
/// onlyComplianceOfficer — reverts UnauthorizedSource for other callers.
function setBlockedReasonWithFreeze(
address wallet,
bytes32 reason,
address tokenContract,
bytes32 partition
) external;
/// @notice Record a SANCTIONS block AND emit regulatory reporting events for a partition.
/// @dev Sets the SANCTIONS bit (idempotent — may already be set) and stamps sanctionsScreenedAt.
/// amount derived from tokenContract.balanceOfByPartition (NOT caller-supplied).
/// Emits SanctionsStatusChanged(true) + SanctionsScreeningCompleted + FrozenTransferRecorded + FrozenAssetHeld.
/// onlySanctionsSource — reverts UnauthorizedSource for other callers.
function setSanctionsBlockedWithFreeze(
address wallet,
bytes32 screeningHash,
address tokenContract,
bytes32 partition
) external;
// ─────────────────────────── reads ────────────────────────────
/// @notice True iff `wallet` was previously registered.
function isVerified(address wallet) external view returns (bool);
/// @notice Returns whether `wallet` holds the given typed claim.
/// @dev NON_US = hasClaim(wallet, keccak256("US_PERSON")) == false.
function hasClaim(address wallet, bytes32 claimType) external view returns (bool);
/// @notice Returns the unix timestamp (seconds) of the most recent KYC verification.
function kycVerifiedAt(address wallet) external view returns (uint64);
/// @notice Returns the unix timestamp (seconds) of the most recent 506(c) accreditation
/// verification (0 if never verified). Raw fact only — no freshness judgment.
/// @dev Mirrors `kycVerifiedAt`/`sanctionsScreenedAt` deliberately: the registry never
/// computes freshness for KYC or sanctions
/// (that lives in `KYCRequiredModule.kycFreshnessWindow` /
/// `SanctionsModule.sanctionsFreshnessWindow`), so accreditation follows the same
/// shape — `AccreditationModule.accreditationWindow` is the sole freshness
/// authority; this getter must never be paired with a registry-side "is fresh"
/// view.
function accreditationVerifiedAt(address wallet) external view returns (uint64);
/// @notice Returns the full recorded accreditation verification for `wallet`.
/// @dev All-zero struct for a wallet that was never verified — `verifiedAt == 0` is the
/// authoritative "never verified" sentinel (see `setAccreditationVerification`).
function accreditation(address wallet) external view returns (AccreditationRecord memory);
/// @notice True iff `wallet` is blocked for ANY reason (any bit in _blockedReasons is set).
function isBlocked(address wallet) external view returns (bool);
/// @notice Returns the raw blocked-reasons bitmask (SANCTIONS=1, AFFILIATE=2, ADMIN=4).
function blockedReasonsMask(address wallet) external view returns (uint256);
/// @notice True iff `wallet` is blocked specifically for `reasonLabel`.
/// @dev Reverts UnknownBlockReason for unrecognized labels.
function isBlockedFor(address wallet, bytes32 reasonLabel) external view returns (bool);
/// @notice Returns the unix timestamp of the most recent sanctions screening (0 if never).
function sanctionsScreenedAt(address wallet) external view returns (uint64);
// ─────────────────── certification errors ────────────────
/// @notice Thrown by setCertifications when certTypes / values / attestationHashes arrays differ in length.
error CertArrayLengthMismatch();
/// @notice Thrown by setCertifications when all three arrays are length zero.
/// @dev An empty signed batch would burn a nonce while emitting nothing; an empty hash-only batch is a no-op.
error EmptyCertBatch();
/// @notice Thrown by setCertifications (signed path) when ECDSA.recover returns an address ≠ wallet.
error InvalidCertSignature();
/// @notice Thrown by setCertifications (signed path) when block.timestamp > deadline.
error CertSignatureExpired();
/// @notice Thrown by setRequiredCertification when adding a type would exceed the required-set cap.
/// @dev Caps the hasAllRequiredCertifications loop against mint-path gas-DoS.
error TooManyCertTypes();
/// @notice Thrown by setCertifications (signed path) when any values[i] == false (revokes require unsigned call).
/// @dev Revocations are an issuer-only action and cannot be combined with an investor EIP-712 signature.
error RevokeNotAllowedInSignedBatch();
// ─────────────────── certification events ────────────────
/// @notice Emitted per set-true entry in setCertifications.
/// @dev attestationHash = keccak256 of the signed covenant document — emit-only, NOT stored.
/// investorSigned: true iff the call carried a valid investor EIP-712 signature.
/// Re-certification (setting an already-set cert again) re-emits this event — each call
/// is a distinct attestation event (possibly a new document hash), not a no-op.
event PurchaserCertified(
address indexed wallet,
bytes32 indexed certType,
bytes32 attestationHash,
bool investorSigned
);
/// @notice Emitted per set-false entry in setCertifications (hash-only / unsigned path only).
/// @dev attestationHash = keccak256 of the revocation record — emit-only, NOT stored.
event CertificationRevoked(
address indexed wallet,
bytes32 indexed certType,
bytes32 attestationHash
);
/// @notice Emitted by setRequiredCertification when the required-cert set changes.
/// @dev A privileged compliance-policy mutation (which cert types are mandatory) — must
/// not be silent (audit trail). Emitted only on a real
/// state change; an idempotent no-op (re-adding a required type / removing an absent
/// one) emits nothing. Consumed by the governance handler.
event RequiredCertificationUpdated(bytes32 indexed certType, bool required);
/// @notice Emitted the first time a non-canonical claim topic is written, registering it
/// for migration by `recoverWallet`.
/// @dev The three canonical topics (US_PERSON, DISTRIBUTOR, ACCREDITED) are copied by
/// `recoverWallet` unconditionally and never emit this.
event TrackedClaimTypeRegistered(bytes32 indexed claimType);
/// @notice Emitted the first time a non-canonical cert type is written or required,
/// registering it for migration by `recoverWallet`.
/// @dev The five canonical cert types are copied unconditionally and never emit this.
event TrackedCertTypeRegistered(bytes32 indexed certType);
// ──── regulatory reporting events (frozen signatures) ──────────
/// @notice Emitted when a blocking flag is set with partition context — regulatory reporting trigger.
/// @dev Emitted by setBlockedReasonWithFreeze and setSanctionsBlockedWithFreeze.
/// amount derived from balanceOfByPartition at the blocking write (NOT
/// caller-supplied). party/partition indexed for compliance_events topic-filter.
event FrozenTransferRecorded(
address indexed party,
bytes32 indexed partition,
bytes32 reason,
uint256 amount,
uint256 timestamp
);
/// @notice Emitted when a blocking flag is set with partition context — regulatory reporting trigger.
/// @dev Emitted by setBlockedReasonWithFreeze and setSanctionsBlockedWithFreeze.
/// amount derived from balanceOfByPartition at the blocking write (NOT
/// caller-supplied). holder/partition indexed for compliance_events topic-filter.
event FrozenAssetHeld(
address indexed holder,
bytes32 indexed partition,
uint256 amount,
uint256 blockingDate
);
// ─────────────────── certification writes ────────────────
/// @notice Batch-set or revoke typed investor certifications. Single-cert = one-element arrays.
/// @dev Access is MODE-DEPENDENT — do NOT put onlyOwner on this function:
/// - Hash-only (investorSig.length == 0): onlyComplianceOfficer.
/// Issuer asserts the cert on the investor's behalf (fiat/manual path).
/// Revocations (values[i] == false) are ONLY allowed in hash-only calls.
/// - Signed (investorSig.length > 0): PERMISSIONLESS — the EIP-712 sig is the authorization.
/// One sig covers the whole batch. All entries must be set-true (no revokes allowed).
/// Nonce increments ONCE per batch. Investor or relayer may submit.
/// attestationHashes[i] = keccak256 of the signed covenant document — passed to event, NOT stored.
/// Reverts CertArrayLengthMismatch if array lengths differ.
/// Reverts EmptyCertBatch if all arrays are length zero.
/// @param wallet The investor wallet.
/// @param certTypes Array of certification type bytes32 labels.
/// @param values Array of booleans (true = set, false = revoke).
/// @param attestationHashes Array of per-cert covenant-document hashes (emit-only).
/// @param investorSig EIP-712 signature bytes (investor-signed path), or empty bytes (hash-only path).
/// @param deadline Unix timestamp after which the signature is expired (ignored in hash-only path).
function setCertifications(
address wallet,
bytes32[] calldata certTypes,
bool[] calldata values,
bytes32[] calldata attestationHashes,
bytes calldata investorSig,
uint256 deadline
) external;
/// @notice Add or remove a certification type from the required set. onlyOwner.
/// @dev Stays onlyOwner — required-cert config is a compliance-POLICY change.
/// Adding: deduped via _isRequired; reverts TooManyCertTypes if count would exceed the cap.
/// Removing: swap-and-pop; no-op if certType not in the set.
/// An empty required set means no certs required (vacuously hasAllRequired == true).
/// @param certType The bytes32 certification type label.
/// @param required True to require, false to remove from the required set.
function setRequiredCertification(bytes32 certType, bool required) external;
// ─────────────────── certification reads ─────────────────
/// @notice True iff wallet currently holds the given certification.
function certified(address wallet, bytes32 certType) external view returns (bool);
/// @notice True iff the wallet's cert was recorded via an investor EIP-712 signed call.
/// @dev False for hash-only (issuer-asserted) certs. Survives recoverWallet.
function certInvestorSigned(address wallet, bytes32 certType) external view returns (bool);
/// @notice Returns the current per-wallet EIP-712 nonce (replay guard for setCertifications signed path).
function certNonce(address wallet) external view returns (uint256);
/// @notice Returns the array of currently-required certification types.
function requiredCertifications() external view returns (bytes32[] memory);
/// @notice True iff wallet holds every currently-required cert type.
/// @dev Vacuously true when the required set is empty.
/// Read by CertificationModule for the issueByPartition mint gate.
function hasAllRequiredCertifications(address wallet) external view returns (bool);
/// @notice True iff wallet holds every currently-required cert type AND each is investor-signed.
/// @dev Vacuously true when the required set is empty.
/// Read by purchaseByPartition — self-purchase requires investor-signed certs.
function hasAllRequiredCertificationsSigned(address wallet) external view returns (bool);
// ─────────────────────────── existing reads ────────────────────────────
/// @notice Reverse lookup: returns the wallet currently bound to `onchainIdHash`.
/// @dev Returns address(0) for unregistered hashes.
/// EXEMPTION: walletOf(bytes32(0)) is exempt from one-wallet-per-identity —
/// multiple wallets may register with the zero hash (off-chain canonicalization
/// never produces bytes32(0)), and walletOf(0) reflects only the LAST writer.
/// The cap module must never aggregate on the zero identity.
function walletOf(bytes32 onchainIdHash) external view returns (address);
/// @notice Forward lookup: returns the identity hash bound to `wallet`.
/// @dev Returns bytes32(0) for unregistered wallets.
/// Exposes the existing private _identityHashes mapping as a public view.
function identityOf(address wallet) external view returns (bytes32);
}
src/contracts/interfaces/IPartitionInfo.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.22;
/// @title IPartitionInfo
/// @notice Minimal view interface that ERC-1400 compliance modules call on the Token
/// to read per-partition and per-holder clocks.
/// @dev Read-only by contract: consumers read these getters and do NOT extend or
/// redeclare the interface.
///
/// - `tranche` — read by LockupModule, AccreditationModule, CertificationModule
/// to dispatch on the partition's tranche.
/// - `lockupEnd` — read by LockupModule (and by CertificationModule's offshore branch).
/// - `holdingEnd` — read by HoldingPeriodModule and by AccreditationModule's
/// post-Rule-144 wash carve-out.
/// - `transferLockEnd` — read by TransferLockModule.
///
/// `isRestricted` label is NOT here — modules gate purely on clocks; a washed
/// holding passes implicitly because the wash requires both clocks already cleared.
/// `isRestricted` is a Token getter for the off-chain read-model/UI.
///
/// Implemented by Token.
interface IPartitionInfo {
/// @notice Partition pool discriminator. Framework-neutral values — descriptive of the
/// investor pool, no regulation named. `OFFSHORE` = 0
/// (default, back-compatible with every partition that predates this field);
/// `ACCREDITED` = 1. Declared here, not in `Token`, so `Token`'s config struct
/// references `IPartitionInfo.Tranche` instead of redeclaring an incompatible
/// second type — two independent `enum Tranche` declarations would not compile
/// against each other.
enum Tranche { OFFSHORE, ACCREDITED }
/// @notice Returns the partition's frozen tranche. Append-only addition — breaks no
/// existing implementor.
/// @dev Returns `Tranche.OFFSHORE` (enum default 0) for a partition that was NEVER
/// created — a return of OFFSHORE is NOT proof the partition exists.
/// `tranche()` never answers "does this partition exist" — check partition
/// existence separately (e.g. via the Token's own creation-tracking) when that
/// question matters. Modules dispatch on this value; never infer existence from it.
/// @param partition ERC-1410 partition key.
/// @return The partition's tranche.
function tranche(bytes32 partition) external view returns (Tranche);
/// @notice Returns the ERC-1400 lockup end timestamp for a partition.
/// @dev Returns `type(uint256).max` when:
/// - `closeDate` is unset (sentinel `type(uint256).max` = continuous partition), OR
/// - the partition is uncreated (stored `closeDate` default == 0).
/// Only computes `closeDate + lockupPeriod` for a genuinely-set, future/now closeDate.
/// Never returns the `0 + lockupPeriod ≈ 1971` fail-open, nor overflows.
/// LockupModule reads this to determine if a restricted-class recipient is blocked.
/// @param partition ERC-1410 partition key.
/// @return Unix timestamp (seconds) after which lockup lifts. `type(uint256).max`
/// means the lockup is indefinite (period not started or partition unknown).
function lockupEnd(bytes32 partition) external view returns (uint256);
/// @notice Returns the holding-period end timestamp for a holder in a partition.
/// @dev Returns 0 when no holding-period clock has been set for this holder/partition pair
/// (default mapping value). `holdingEnd(address(0), partition) == 0` so the mint path
/// passes HoldingPeriodModule implicitly.
/// HoldingPeriodModule reads this to enforce the holding period on the sender.
/// @param holder Wallet address of the holder.
/// @param partition ERC-1410 partition key.
/// @return Unix timestamp (seconds) after which the holding period is satisfied.
/// 0 means no holding-period restriction applies.
function holdingEnd(address holder, bytes32 partition) external view returns (uint256);
/// @notice Returns the universal absolute transfer lock end for a holder in a partition.
/// @dev Returns 0 when no transfer lock has been set (partition has no transferLockPeriod,
/// or the holder has never acquired). 0 = not locked (TransferLockModule passes).
/// Unlike `lockupEnd`, there is NO max-sentinel fail-safe — `0` means genuinely unlocked
/// (partition may have transferLockPeriod == 0 configured). Stored by the Token and
/// stamped FRESH (not tacked) at each acquisition: max(existing, now + period).
/// TransferLockModule reads this to enforce the universal lock.
/// @param holder Wallet address of the holder.
/// @param partition ERC-1410 partition key.
/// @return Unix timestamp (seconds) after which the absolute transfer lock lifts.
/// 0 means no transfer lock applies.
function transferLockEnd(address holder, bytes32 partition) external view returns (uint256);
}
src/contracts/lib/BaseComplianceModule.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.22;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {IComplianceModule} from "../interfaces/ICompliance.sol";
/// @title BaseComplianceModule
/// @notice Abstract base for all ERC-1400 partition-aware compliance modules.
/// @dev MODULE AUTHORING RULE — DEFAULT-BLOCK INVARIANT:
///
/// Every concrete module MUST uphold all three invariants:
///
/// 1. NEVER DEFAULT TO ALLOW.
/// When a required claim is missing, unverifiable, or stale, return
/// `(false, <reasonCode>)`. Never return `(true, bytes32(0))` on absent
/// or unverifiable data. The pipeline MUST default to block.
///
/// 2. NEVER REVERT.
/// `moduleCheck` MUST be a pure `view` that returns a `(bool, bytes32)` tuple
/// under all inputs. A revert inside `moduleCheck` crashes the whole transfer
/// pipeline (the engine does not catch module reverts). Unset partition state
/// (e.g. closeDate == type(uint256).max) is a veto via RESTRICTED_RECIPIENT_LOCKUP,
/// NOT a revert. `MISSING_COMPLIANCE_ANCHOR` is retired.
///
/// 3. FRESHNESS CHECK: USE ADDITION FORM.
/// Stale-claim checks MUST use the addition form:
/// `claimTimestamp + freshnessWindow < block.timestamp`
/// NOT the subtraction form `block.timestamp - claimTimestamp > window`
/// because the subtraction reverts (checked arithmetic) on a future `claimTimestamp`.
/// A future timestamp must NOT revert — it simply hasn't expired yet, so the
/// check passes. Mirror `SanctionsModule` exactly.
///
/// 4. CENTRAL ZERO-TO GUARD IS IN THE ENGINE, NOT MODULES.
/// `to == address(0)` is caught by the engine fast-path.
/// Module `moduleCheck` is only called after that guard passes, so `to` is
/// guaranteed non-zero. Modules do NOT repeat the zero-address check.
///
/// MINT PATH (`from == address(0)`):
/// The engine does not reject the zero `from` — that is a legitimate mint.
/// Per the mint-applicability matrix, each module
/// specifies whether it gates mint. See the module-level NatSpec for details.
abstract contract BaseComplianceModule is IERC165, IComplianceModule {
// Concrete modules implement moduleCheck() and inherit these invariants.
// No shared state is defined here — modules own their own storage.
/// @notice ERC-165 introspection — allows `ModularCompliance.addModule` to validate that
/// an attached address genuinely implements `IComplianceModule`.
/// All concrete modules inherit this automatically — no per-module override needed.
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return
interfaceId == type(IComplianceModule).interfaceId ||
interfaceId == type(IERC165).interfaceId;
}
}
src/contracts/lib/ReasonCodes.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.22;
/// @title ReasonCodes
/// @notice Canonical bytes32 reason-code constants for the ERC-1400 compliance pipeline.
/// @dev Contains the engine fast-path codes plus the full framework-neutral reason set
/// and the optional ERC-1066 `reasonToStatusByte` view helper.
///
/// Codes are keccak256 hashes of their human-readable label strings.
/// Framework-neutral: they describe the mechanism (preserving the auditor/regulator evidence
/// trail) and map to ERC-1066 status bytes for wallet/explorer display.
/// The Token maps a non-success reasonCode to a named revert.
///
/// OMITTED by design:
/// - `MISSING_COMPLIANCE_ANCHOR` — retired; greenfield build has no legacy slot.
/// Unset partition closeDate (type(uint256).max) vetoes via RESTRICTED_RECIPIENT_LOCKUP.
/// - `CERTIFICATION_NOT_SIGNED` — Token-level named error in purchaseByPartition
/// (parallel to BelowMinimumPurchase), not a compliance-module reason code.
library ReasonCodes {
// ─── Fast-path codes ──────────────────────────────────
/// @notice Sender is on a sanctions list or another sanctions-basis block.
/// @dev ERC-1066: 0x50 (Disallowed/Stop)
bytes32 internal constant SANCTIONS_BLOCKED = keccak256("SANCTIONS_BLOCKED");
/// @notice Sender is blocked for a non-sanctions reason (AFFILIATE / ADMIN bit).
/// @dev ERC-1066: 0x50
bytes32 internal constant SENDER_BLOCKED = keccak256("SENDER_BLOCKED");
/// @notice Recipient is blocked or is the zero address (central zero-to guard).
/// @dev ERC-1066: 0x50
bytes32 internal constant RECIPIENT_BLOCKED = keccak256("RECIPIENT_BLOCKED");
// ─── Module reason codes ───────────────────────────
/// @notice Recipient is a restricted class (e.g. US_PERSON) and the lockup
/// period has not yet elapsed for this partition.
/// @dev ERC-1066: 0x50
bytes32 internal constant RESTRICTED_RECIPIENT_LOCKUP = keccak256("RESTRICTED_RECIPIENT_LOCKUP");
/// @notice Holding period not met for the sender in this partition.
/// @dev ERC-1066: 0x50
bytes32 internal constant HOLDING_PERIOD_NOT_MET = keccak256("HOLDING_PERIOD_NOT_MET");
/// @notice Sanctions screening for this wallet has exceeded the freshness window (30-day).
/// @dev ERC-1066: 0x57 (Expired)
bytes32 internal constant SANCTIONS_SCREENING_STALE = keccak256("SANCTIONS_SCREENING_STALE");
/// @notice Recipient is not KYC-verified or not registered in the IdentityRegistry.
/// @dev ERC-1066: 0x56 (Awaiting / not found) — KYC
bytes32 internal constant KYC_NOT_VERIFIED = keccak256("KYC_NOT_VERIFIED");
/// @notice Recipient's KYC verification has exceeded the freshness window (default 12 months).
/// @dev ERC-1066: 0x57 (Expired)
bytes32 internal constant KYC_EXPIRED = keccak256("KYC_EXPIRED");
/// @notice Recipient's aggregate holding would exceed the concentration cap
/// (9.99% cross-partition affiliate cap).
/// @dev ERC-1066: 0x50
bytes32 internal constant CONCENTRATION_CAP_EXCEEDED = keccak256("CONCENTRATION_CAP_EXCEEDED");
/// @notice Recipient is on the destination blocklist (hedging venue / prohibited destination).
/// @dev ERC-1066: 0x50
bytes32 internal constant RECIPIENT_BLOCKLISTED = keccak256("RECIPIENT_BLOCKLISTED");
/// @notice Required certification is absent for the recipient
/// (purchaser certification, resale/hedging covenants).
/// @dev ERC-1066: 0x56
bytes32 internal constant CERTIFICATION_MISSING = keccak256("CERTIFICATION_MISSING");
/// @notice Universal absolute transfer lock — holder has not held for the partition's
/// transferLockPeriod (5y principal / 1y distribution). Jurisdiction-agnostic.
/// @dev ERC-1066: 0x50
bytes32 internal constant TRANSFER_LOCKED = keccak256("TRANSFER_LOCKED");
/// @notice Recipient does not hold the claim a gated partition requires
/// (e.g. a tranche restricted to a specific recipient class).
/// @dev ERC-1066: 0x10 (Disallowed, generic)
bytes32 internal constant RECIPIENT_CLASS_INELIGIBLE = keccak256("RECIPIENT_CLASS_INELIGIBLE");
/// @notice Recipient lacks a required verified-eligibility attestation
/// (claim absent, or present but never verified).
/// @dev ERC-1066: 0x56 (Awaiting/not found)
bytes32 internal constant ACCREDITATION_NOT_VERIFIED = keccak256("ACCREDITATION_NOT_VERIFIED");
/// @notice Recipient's verified-eligibility attestation has exceeded its freshness window.
/// @dev ERC-1066: 0x57 (Expired)
bytes32 internal constant ACCREDITATION_EXPIRED = keccak256("ACCREDITATION_EXPIRED");
/// @notice An attached compliance module reverted inside `moduleCheck`. Fail-closed per the
/// NEVER-REVERT invariant (`BaseComplianceModule` NatSpec) — the engine
/// (`ModularCompliance`) catches the revert and vetoes the transfer with this code
/// instead of letting the revert propagate and brick the pipeline for every other
/// attached module.
/// @dev ERC-1066: 0x10 (Disallowed, generic) — distinct from the hard-block 0x50 codes
/// above, since this reflects a module malfunction, not a substantive compliance veto.
bytes32 internal constant MODULE_ERROR = keccak256("MODULE_ERROR");
// ─── ERC-1066 view helper (display-only, not in the transfer hot path) ───
/// @notice Maps a framework-neutral bytes32 reason code to its ERC-1066 status byte.
/// @dev Display-only — for wallet and block-explorer integrations.
/// Returns 0x10 (Disallowed, generic) for any unknown code.
/// Pure — safe to call in view contexts; no state access, no side effects.
function reasonToStatusByte(bytes32 code) internal pure returns (bytes1) {
// KYC codes → 0x56 (Awaiting/not found) or 0x57 (Expired)
if (code == KYC_NOT_VERIFIED) return 0x56;
if (code == KYC_EXPIRED) return 0x57;
if (code == CERTIFICATION_MISSING) return 0x56;
// Freshness staleness → 0x57 (Expired)
if (code == SANCTIONS_SCREENING_STALE) return 0x57;
// All hard-block codes → 0x50 (Disallowed/Stop)
if (code == SANCTIONS_BLOCKED) return 0x50;
if (code == SENDER_BLOCKED) return 0x50;
if (code == RECIPIENT_BLOCKED) return 0x50;
if (code == RESTRICTED_RECIPIENT_LOCKUP) return 0x50;
if (code == HOLDING_PERIOD_NOT_MET) return 0x50;
if (code == CONCENTRATION_CAP_EXCEEDED) return 0x50;
if (code == RECIPIENT_BLOCKLISTED) return 0x50;
if (code == TRANSFER_LOCKED) return 0x50;
// Accreditation-gate codes
if (code == RECIPIENT_CLASS_INELIGIBLE) return 0x10;
if (code == ACCREDITATION_NOT_VERIFIED) return 0x56;
if (code == ACCREDITATION_EXPIRED) return 0x57;
if (code == MODULE_ERROR) return 0x10;
// Success (bytes32(0) from all-pass) → 0x51 (Success)
if (code == bytes32(0)) return 0x51;
// Unknown code → generic 0x00 (failure default)
return 0x00;
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"useLiteralContent": true
},
"optimizer": {
"runs": 100,
"enabled": true
},
"evmVersion": "paris"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.