Verified contractExactBUSL-1.1
BridgeMixedInterestLib
Address0xd36723b8f7aae778593a4f308f3e8baac0d5ba71
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.30
- Same code
1 more contract
Details
- Compiler
- solc 0.8.30+commit.73712a01
- Language
- solidity
- Optimization
- Yes, 100 runs
- EVM version
- cancun
- License
- BUSL-1.1
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,459,362
- Creation transaction
- 0x7127b947f4…cbdc4fe3f9
src/libraries/BridgeMixedInterestLib.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
import {IAttestationOracle} from "../interfaces/IAttestationOracle.sol";
import {ICollateralRegistry} from "../interfaces/ICollateralRegistry.sol";
import {IContinuousAccrual} from "../interfaces/IContinuousAccrual.sol";
import {IAccrualLifecycle} from "../interfaces/IAccrualLifecycle.sol";
import {IComplianceRegistry} from "../interfaces/IComplianceRegistry.sol";
/// @title BridgeMixedInterestLib
/// @notice Signed metadata and monotone cash/PIK clocks for one-facility mixed-interest notes.
/// @dev Public methods execute by delegatecall in ClaimBridge's context. Authority, class checks,
/// attestation consumption and reentrancy protection remain in ClaimBridge. This library owns
/// an independent ERC-7201 namespace so no historical bridge field moves.
library BridgeMixedInterestLib {
bytes32 internal constant FEATURE_VERSION = keccak256("forestroad.mixed-interest.v1");
bytes32 private constant ORIGINATION_DOMAIN = keccak256("forestroad.mixed-interest.origination.v1");
bytes32 private constant AMENDMENT_DOMAIN = keccak256("forestroad.mixed-interest.amendment.v2");
bytes32 private constant SINGLE_AMENDMENT_DOMAIN = keccak256("forestroad.credit-amendment.v2");
bytes32 private constant SERVICING_DOMAIN = keccak256("forestroad.servicing-state.v1");
/// @notice The two authenticated rates and servicing clocks.
/// @dev LAYOUT-FROZEN: stored as a mapping value and embedded in PendingAmendment; changing
/// its width or field order would shift live proxy storage.
struct InterestLegTerms {
uint16 cashRateBps;
uint16 pikRateBps;
uint64 cashPaymentInterval;
uint64 nextCashPaymentDue;
uint64 pikCapitalizationInterval;
uint64 nextPikCapitalization;
}
/// @dev ABI-identical mirror of ClaimBridge.OriginationTerms. Enums encode as uint8.
struct OriginationTerms {
uint256 classId;
bytes32 borrowerId;
bytes32 stateId;
uint256 principal;
uint16 ltvBps;
uint16 interestRateBps;
uint64 maturity;
address fundingRecipient;
uint64 paymentInterval;
uint64 nextPaymentDue;
uint8 rateType;
uint8 dayCountConvention;
bool renewable;
bytes32 paymentScheduleHash;
bytes32 rateIndexRef;
bytes32 renewalTermsHash;
bytes32 offchainRef;
bool pik;
}
/// @dev ABI-identical mirror of ClaimBridge.Amendment. Enums encode as uint8.
struct Amendment {
uint16 interestRateBps;
uint64 maturity;
uint64 paymentInterval;
uint64 nextPaymentDue;
uint8 rateType;
uint8 dayCountConvention;
bool renewable;
bytes32 paymentScheduleHash;
bytes32 rateIndexRef;
bytes32 renewalTermsHash;
}
/// @dev Storage-identical mirror of ClaimBridge.Facility. Enums encode in one byte.
struct Facility {
uint256 classId;
bytes32 borrowerId;
bytes32 stateId;
uint256 principal;
uint16 ltvBps;
uint16 interestRateBps;
uint64 maturity;
address fundingRecipient;
uint64 paymentInterval;
uint64 nextPaymentDue;
uint8 rateType;
uint8 dayCountConvention;
bool renewable;
bytes32 paymentScheduleHash;
bytes32 rateIndexRef;
bytes32 renewalTermsHash;
bytes32 offchainRef;
uint8 loanState;
bool pik;
}
/// @dev Storage-identical mirror of ClaimBridge.BridgeStorage.
struct BridgeStorage {
ICollateralRegistry registry;
IAttestationOracle oracle;
uint256 nextId;
mapping(uint256 tokenId => Facility) facilities;
mapping(uint256 classId => uint256) requiredMintAttestations;
address accrualReserve;
mapping(uint256 tokenId => uint256) servicingNonce;
}
/// @custom:storage-location erc7201:forestroad.storage.ClaimBridgeMixedInterest
struct State {
mapping(uint256 facilityId => InterestLegTerms) terms;
mapping(uint256 facilityId => bytes32) commitment;
mapping(uint256 facilityId => bytes32) originationCommonHash;
mapping(uint256 facilityId => PendingAmendment) pendingAmendment;
bool enabled;
IComplianceRegistry borrowerPayoutRegistry;
// A cancelled preparation is rejected history, even when an originator later presents
// byte-identical terms at the still-current next id. The generation domain makes every
// post-cancellation commitment fresh, so the prior attester quorum cannot be replayed.
mapping(uint256 facilityId => uint256) originationGeneration;
}
struct PendingAmendment {
InterestLegTerms terms;
bytes32 commonHash;
bytes32 amendmentId;
bytes32 attestationHash;
}
bytes32 private constant MIXED_STORAGE_LOCATION = 0x5b29875874efdde9f2b0d1556dcca4e06c98ca7e47c1bf35a515d9037c1efb00;
bytes32 private constant BRIDGE_SLOT = 0xc9c2da543a2a10e4b712709fb6548fb2c0c97cecbac3457453966d18f1663f00;
uint8 private constant _ACTIVE = 1;
uint8 private constant _AMORTIZING = 2;
uint8 private constant _FIXED = 0;
uint8 private constant _ACTUAL_360 = 0;
uint8 private constant _THIRTY_360 = 2;
uint16 private constant _MAX_INTEREST_RATE_BPS = 10_000;
error MixedInterest_NotEnabled();
error MixedInterest_AlreadyEnabled();
error MixedInterest_InvalidTerms();
error MixedInterest_AlreadyConfigured(uint256 facilityId);
error MixedInterest_NotConfigured(uint256 facilityId);
/// @notice A signed one-shot amendment must be applied or revoked before staging its replacement.
error MixedInterest_UnconsumedAmendment(uint256 facilityId, bytes32 payload);
/// @notice A prepared plan belongs to the servicing state before an intervening receipt or amendment.
error MixedInterest_StalePreparedAmendment(uint256 facilityId);
error Bridge_BadFacility();
error Bridge_UnknownToken(uint256 tokenId);
error Bridge_InvalidTransition(uint256 tokenId, uint8 from, uint8 to);
error Bridge_LegacyPikScheduleRequiresMigration(uint256 tokenId);
error Bridge_TermsAmendmentNotAttested(uint256 tokenId);
error Bridge_AccrualUnsupportedTerms(uint256 tokenId);
error Bridge_MixedInterestUnavailable();
error Bridge_AccrualReserveOnly(address caller);
error Bridge_AccrualDueManaged(uint256 tokenId);
error BorrowerPayout_RegistryAlreadySet(address registry);
error BorrowerPayout_InvalidRegistry(address registry);
error BorrowerPayout_RecipientNotAllowed(address recipient);
event BorrowerPayoutRegistrySet(address indexed registry);
event MixedInterestEnabled(bytes32 indexed version);
/// @notice Exact leg metadata staged for an origination (`actionId == 0`) or amendment.
/// @dev A later Originated/TermsAmended event carrying `termsHash` makes the staged record live;
/// cancellation or replacement leaves it as rejected history. This keeps the mixed-leg
/// register reconstructable from logs without trusting transaction calldata archives.
event MixedInterestTermsStaged(
uint256 indexed facilityId,
bytes32 indexed actionId,
bytes32 indexed termsHash,
uint16 cashRateBps,
uint16 pikRateBps,
uint64 cashPaymentInterval,
uint64 nextCashPaymentDue,
uint64 pikCapitalizationInterval,
uint64 nextPikCapitalization
);
event MixedInterestLegDueSet(uint256 indexed facilityId, uint8 indexed leg, uint64 previousDue, uint64 nextDue);
event NextPaymentDueSet(uint256 indexed tokenId, uint64 previousDue, uint64 nextDue);
event TermsAmended(uint256 indexed tokenId, bytes32 indexed amendmentId, bytes32 termsHash);
/// @notice A receipt or amendment advanced the signed servicing generation at the host proxy.
event ServicingStateAdvanced(uint256 indexed tokenId, uint256 nonce);
/// @notice The host authenticates the receipt; a failed surrounding operation rolls this back.
/// @dev Delegatecall only; the host enforces its trusted CREDIT_ROLE or amendment quorum.
/// @param id Known facility whose current generation must advance.
function advanceServicingState(uint256 id) public {
BridgeStorage storage bridge = _bridgeStorage();
_liveFacility(bridge, id);
uint256 nonce = ++bridge.servicingNonce[id];
emit ServicingStateAdvanced(id, nonce);
}
function enable() public {
State storage s = _state();
if (s.enabled) revert MixedInterest_AlreadyEnabled();
s.enabled = true;
emit MixedInterestEnabled(FEATURE_VERSION);
}
function enabled() public view returns (bool) {
return _state().enabled;
}
function bindBorrowerPayoutRegistry(address registry_) public returns (address bound) {
State storage s = _state();
address current = address(s.borrowerPayoutRegistry);
if (current != address(0)) revert BorrowerPayout_RegistryAlreadySet(current);
if (!_isBorrowerPayoutRegistry(registry_)) revert BorrowerPayout_InvalidRegistry(registry_);
s.borrowerPayoutRegistry = IComplianceRegistry(registry_);
emit BorrowerPayoutRegistrySet(registry_);
return registry_;
}
function borrowerPayoutRegistry() public view returns (address) {
return address(_state().borrowerPayoutRegistry);
}
function requireFundingRecipientAllowed(address recipient) public view returns (bool allowed) {
IComplianceRegistry policy = _state().borrowerPayoutRegistry;
if (address(policy) == address(0) || !policy.isFundingRecipientAllowed(recipient)) {
revert BorrowerPayout_RecipientNotAllowed(recipient);
}
return true;
}
function configured(uint256 id) public view returns (bool) {
return _state().terms[id].cashRateBps != 0;
}
function terms(uint256 id) public view returns (InterestLegTerms memory result) {
result = _state().terms[id];
if (result.cashRateBps == 0) revert MixedInterest_NotConfigured(id);
}
function commitment(uint256 id) public view returns (bytes32) {
return _state().commitment[id];
}
/// @notice Validates and stores a mixed origination before the host's safe-mint callback.
function stageOrigination(uint256 id, bytes calldata encoded) public returns (bytes32 termsHash) {
State storage s = _state();
if (!s.enabled) revert MixedInterest_NotEnabled();
if (s.terms[id].cashRateBps != 0) revert MixedInterest_AlreadyConfigured(id);
(OriginationTerms memory common, InterestLegTerms memory legs) =
abi.decode(encoded, (OriginationTerms, InterestLegTerms));
_validateOrigination(common, legs);
termsHash = _originationHash(s.originationGeneration[id], common, legs);
s.terms[id] = legs;
s.commitment[id] = termsHash;
s.originationCommonHash[id] = keccak256(abi.encode(common));
emit MixedInterestTermsStaged(
id,
bytes32(0),
termsHash,
legs.cashRateBps,
legs.pikRateBps,
legs.cashPaymentInterval,
legs.nextCashPaymentDue,
legs.pikCapitalizationInterval,
legs.nextPikCapitalization
);
}
/// @notice Confirms the ordinary origination calldata is the common half staged for this id.
function preparedOrigination(uint256 id, bytes calldata encodedCommon) public view returns (bytes32 termsHash) {
State storage s = _state();
termsHash = s.commitment[id];
if (
termsHash == bytes32(0) || s.originationCommonHash[id] == bytes32(0)
|| s.originationCommonHash[id] != keccak256(encodedCommon)
) revert MixedInterest_InvalidTerms();
}
function clearPreparedOrigination(uint256 id) public {
State storage s = _state();
if (s.originationCommonHash[id] == bytes32(0)) revert MixedInterest_NotConfigured(id);
delete s.terms[id];
delete s.commitment[id];
delete s.originationCommonHash[id];
++s.originationGeneration[id];
}
/// @notice Validates and stages prospective mixed terms without changing the live clocks.
function stageAmendment(uint256 id, bytes32 amendmentId, bytes calldata encoded)
public
returns (bytes32 attestationHash)
{
State storage s = _state();
if (!s.enabled) revert MixedInterest_NotEnabled();
if (s.terms[id].cashRateBps == 0) revert MixedInterest_NotConfigured(id);
(bytes32 standing,, bool satisfied) =
_bridgeStorage().oracle.latestPayload(id, IAttestationOracle.AttestationKind.TermsAmended);
if (satisfied) revert MixedInterest_UnconsumedAmendment(id, standing);
(Amendment memory common, InterestLegTerms memory legs) = abi.decode(encoded, (Amendment, InterestLegTerms));
_validateAmendment(common, legs);
attestationHash =
keccak256(abi.encode(AMENDMENT_DOMAIN, amendmentId, id, common, legs, _servicingStateHash(id)));
s.pendingAmendment[id] = PendingAmendment({
terms: legs,
commonHash: keccak256(abi.encode(common)),
amendmentId: amendmentId,
attestationHash: attestationHash
});
emit MixedInterestTermsStaged(
id,
amendmentId,
attestationHash,
legs.cashRateBps,
legs.pikRateBps,
legs.cashPaymentInterval,
legs.nextCashPaymentDue,
legs.pikCapitalizationInterval,
legs.nextPikCapitalization
);
}
/// @notice Applies either the historical one-leg amendment or a prepared two-leg amendment.
/// @dev The host supplies role, pause, reentrancy and source-freshness gates. This linked
/// implementation preserves the original bridge namespace and emits from the proxy.
function amendTerms(uint256 id, bytes32 amendmentId, bytes calldata encoded) public {
Amendment memory a = abi.decode(encoded, (Amendment));
BridgeStorage storage bridge = _bridgeStorage();
if (id == 0 || id >= bridge.nextId) revert Bridge_UnknownToken(id);
Facility storage facility = bridge.facilities[id];
if (facility.loanState != _ACTIVE && facility.loanState != _AMORTIZING) revert Bridge_BadFacility();
bool mixed = _state().terms[id].cashRateBps != 0;
ICollateralRegistry.ClassParams memory classTerms = bridge.registry.classParams(facility.classId);
_validateCommonAmendment(facility, a, amendmentId, classTerms.maxMaturity, mixed);
bool continuous =
bridge.accrualReserve != address(0) && IContinuousAccrual(bridge.accrualReserve).accrualSnapshot().enabled;
if (continuous) _requireAccrualTerms(id, facility.pik, a.rateType, a.dayCountConvention);
if (
!continuous && facility.pik
&& (a.paymentInterval != facility.paymentInterval || a.nextPaymentDue != facility.nextPaymentDue)
) revert Bridge_LegacyPikScheduleRequiresMigration(id);
bytes32 expected;
InterestLegTerms memory legs;
if (mixed) (expected, legs) = _preparedAmendment(id, amendmentId, encoded);
else expected = singleAmendmentHash(id, amendmentId, encoded);
(bytes32 payload,, bool ok) = bridge.oracle.latestPayload(id, IAttestationOracle.AttestationKind.TermsAmended);
if (!ok || payload != expected) revert Bridge_TermsAmendmentNotAttested(id);
bridge.oracle.consume(id, IAttestationOracle.AttestationKind.TermsAmended);
advanceServicingState(id);
_checkpointAmendment(bridge.accrualReserve, id, amendmentId, a, continuous, mixed, legs);
_writeAmendment(facility, a);
emit TermsAmended(id, amendmentId, mixed ? expected : _creditTermsHash(facility));
}
/// @notice Hash for a facility's first preparation, before any cancellation history.
/// @dev After cancellation, use the hash returned by `stageOrigination`; its generation is
/// deliberately private to the bridge so callers cannot mistake a stale preview for the
/// commitment that attesters must sign.
function originationHash(bytes calldata encoded) public pure returns (bytes32 termsHash) {
(OriginationTerms memory common, InterestLegTerms memory legs) =
abi.decode(encoded, (OriginationTerms, InterestLegTerms));
return _originationHash(0, common, legs);
}
/// @notice Current state-bound two-leg amendment payload, evaluated in the host proxy context.
/// @param id Known facility being amended.
/// @param amendmentId Identity of this amendment.
/// @param encoded ABI-encoded Amendment and InterestLegTerms tuple.
/// @return termsHash Commitment for a quorum TermsAmended fact.
function amendmentHash(uint256 id, bytes32 amendmentId, bytes calldata encoded)
public
view
returns (bytes32 termsHash)
{
(Amendment memory common, InterestLegTerms memory legs) = abi.decode(encoded, (Amendment, InterestLegTerms));
return keccak256(abi.encode(AMENDMENT_DOMAIN, amendmentId, id, common, legs, _servicingStateHash(id)));
}
/// @notice A one-leg payload has no legacy-unbound fallback.
/// @param id Known facility being amended.
/// @param amendmentId Identity of this amendment.
/// @param encoded ABI-encoded prospective Amendment tuple.
/// @return Commitment bound to the current facility and receipt generation.
function singleAmendmentHash(uint256 id, bytes32 amendmentId, bytes memory encoded) public view returns (bytes32) {
Amendment memory common = abi.decode(encoded, (Amendment));
return keccak256(abi.encode(SINGLE_AMENDMENT_DOMAIN, amendmentId, id, common, _servicingStateHash(id)));
}
/// @notice Advances the cash clock while preserving the aggregate earliest-due bridge field.
/// @dev The host supplies CREDIT_ROLE, reentrancy and source-idle gates.
function setCashDue(uint256 id, uint64 nextDue) public {
BridgeStorage storage bridge = _bridgeStorage();
Facility storage facility = _liveFacility(bridge, id);
if (facility.loanState != _ACTIVE && facility.loanState != _AMORTIZING) {
revert Bridge_InvalidTransition(id, facility.loanState, facility.loanState);
}
if (_state().terms[id].cashRateBps != 0) {
(uint64 previousAggregate, uint64 nextAggregate) = _setCashDue(id, facility.maturity, nextDue);
facility.nextPaymentDue = nextAggregate;
if (nextAggregate != previousAggregate) emit NextPaymentDueSet(id, previousAggregate, nextAggregate);
return;
}
if (
facility.pik && bridge.accrualReserve != address(0)
&& IContinuousAccrual(bridge.accrualReserve).accrualSnapshot().enabled
) revert Bridge_AccrualDueManaged(id);
uint64 previous = facility.nextPaymentDue;
if (nextDue <= previous || nextDue > facility.maturity) revert Bridge_BadFacility();
facility.nextPaymentDue = nextDue;
emit NextPaymentDueSet(id, previous, nextDue);
}
/// @notice Advances or completes the PIK clock from the permanently bound reserve only.
function setPikDue(uint256 id, uint64 nextDue) public {
BridgeStorage storage bridge = _bridgeStorage();
if (bridge.accrualReserve == address(0) || msg.sender != bridge.accrualReserve) {
revert Bridge_AccrualReserveOnly(msg.sender);
}
Facility storage facility = _liveFacility(bridge, id);
if (!facility.pik) revert Bridge_BadFacility();
if (facility.loanState != _ACTIVE && facility.loanState != _AMORTIZING) {
revert Bridge_InvalidTransition(id, facility.loanState, facility.loanState);
}
if (_state().terms[id].cashRateBps != 0) {
(uint64 previousAggregate, uint64 nextAggregate) = _setPikDue(id, facility.maturity, nextDue);
facility.nextPaymentDue = nextAggregate;
if (nextAggregate != previousAggregate) emit NextPaymentDueSet(id, previousAggregate, nextAggregate);
return;
}
uint64 previous = facility.nextPaymentDue;
if (nextDue <= previous || nextDue > facility.maturity) revert Bridge_BadFacility();
facility.nextPaymentDue = nextDue;
emit NextPaymentDueSet(id, previous, nextDue);
}
function _validateOrigination(OriginationTerms memory common, InterestLegTerms memory legs) private view {
if (
!common.pik || common.rateType != 0 || common.dayCountConvention != 0
|| common.paymentInterval != legs.cashPaymentInterval
|| common.nextPaymentDue != _aggregate(legs.nextCashPaymentDue, legs.nextPikCapitalization, common.maturity)
) revert MixedInterest_InvalidTerms();
_validateLegs(common.interestRateBps, common.maturity, legs);
}
function _validateAmendment(Amendment memory common, InterestLegTerms memory legs) private view {
if (
common.rateType != 0 || common.dayCountConvention != 0 || common.paymentInterval != legs.cashPaymentInterval
|| common.nextPaymentDue != _aggregate(legs.nextCashPaymentDue, legs.nextPikCapitalization, common.maturity)
) revert MixedInterest_InvalidTerms();
_validateLegs(common.interestRateBps, common.maturity, legs);
}
function _validateLegs(uint16 totalRate, uint64 maturity, InterestLegTerms memory legs) private view {
if (
legs.cashRateBps == 0 || legs.pikRateBps == 0 || uint256(legs.cashRateBps) + legs.pikRateBps != totalRate
|| totalRate > 10_000 || legs.cashPaymentInterval == 0 || legs.pikCapitalizationInterval == 0
|| legs.nextCashPaymentDue <= block.timestamp || legs.nextCashPaymentDue > maturity
|| legs.nextPikCapitalization <= block.timestamp || legs.nextPikCapitalization > maturity
|| legs.cashPaymentInterval > legs.nextCashPaymentDue
|| legs.pikCapitalizationInterval > legs.nextPikCapitalization
) revert MixedInterest_InvalidTerms();
}
function _validateCommonAmendment(
Facility storage facility,
Amendment memory a,
bytes32 amendmentId,
uint64 maxMaturity,
bool mixed
) private view {
if (
amendmentId == bytes32(0) || a.interestRateBps == 0 || a.interestRateBps > _MAX_INTEREST_RATE_BPS
|| a.paymentInterval == 0 || a.nextPaymentDue <= block.timestamp || a.nextPaymentDue > a.maturity
|| (!mixed && a.paymentInterval > a.nextPaymentDue) || a.maturity <= block.timestamp
|| a.maturity > block.timestamp + maxMaturity || a.paymentScheduleHash == bytes32(0)
|| (a.maturity > facility.maturity && !facility.renewable)
|| (a.rateType == _FIXED) != (a.rateIndexRef == bytes32(0))
|| a.renewable != (a.renewalTermsHash != bytes32(0))
|| (facility.pik && (a.rateType != _FIXED || a.dayCountConvention != _ACTUAL_360))
) revert Bridge_BadFacility();
}
function _checkpointAmendment(
address reserve,
uint256 id,
bytes32 amendmentId,
Amendment memory a,
bool continuous,
bool mixed,
InterestLegTerms memory legs
) private {
if (mixed) {
if (!continuous) revert Bridge_MixedInterestUnavailable();
IAccrualLifecycle(reserve).amendMixedAccruingLoan(
id,
IAccrualLifecycle.MixedTerms({
cashRateBps: legs.cashRateBps,
pikRateBps: legs.pikRateBps,
yearSeconds: uint32(360 days),
nextPikCapitalization: legs.nextPikCapitalization,
pikCapitalizationInterval: legs.pikCapitalizationInterval,
maturity: a.maturity
})
);
_commitAmendment(id, amendmentId, abi.encode(a));
} else if (continuous) {
IAccrualLifecycle(reserve).amendAccruingLoan(
id,
IAccrualLifecycle.Terms({
rateBps: a.interestRateBps,
yearSeconds: a.dayCountConvention == _ACTUAL_360 ? uint32(360 days) : uint32(365 days),
nextPaymentDue: a.nextPaymentDue,
paymentInterval: a.paymentInterval,
maturity: a.maturity
})
);
}
}
function _preparedAmendment(uint256 id, bytes32 amendmentId, bytes memory encodedCommon)
private
view
returns (bytes32 attestationHash, InterestLegTerms memory legs)
{
PendingAmendment storage pending = _state().pendingAmendment[id];
if (
pending.attestationHash == bytes32(0) || pending.amendmentId != amendmentId
|| pending.commonHash != keccak256(encodedCommon)
) revert MixedInterest_InvalidTerms();
bytes32 current = keccak256(
abi.encode(
AMENDMENT_DOMAIN,
amendmentId,
id,
abi.decode(encodedCommon, (Amendment)),
pending.terms,
_servicingStateHash(id)
)
);
if (pending.attestationHash != current) revert MixedInterest_StalePreparedAmendment(id);
return (pending.attestationHash, pending.terms);
}
function _servicingStateHash(uint256 id) private view returns (bytes32) {
BridgeStorage storage bridge = _bridgeStorage();
Facility storage facility = _liveFacility(bridge, id);
return keccak256(
abi.encode(
SERVICING_DOMAIN,
block.chainid,
address(this),
id,
bridge.servicingNonce[id],
_creditTermsHash(facility),
_state().terms[id]
)
);
}
function _commitAmendment(uint256 id, bytes32 amendmentId, bytes memory encodedCommon)
private
returns (InterestLegTerms memory legs)
{
State storage s = _state();
PendingAmendment storage pending = s.pendingAmendment[id];
if (
pending.attestationHash == bytes32(0) || pending.amendmentId != amendmentId
|| pending.commonHash != keccak256(encodedCommon)
) revert MixedInterest_InvalidTerms();
legs = pending.terms;
s.terms[id] = legs;
s.commitment[id] = pending.attestationHash;
delete s.pendingAmendment[id];
}
function _writeAmendment(Facility storage facility, Amendment memory a) private {
facility.interestRateBps = a.interestRateBps;
facility.maturity = a.maturity;
facility.paymentInterval = a.paymentInterval;
facility.nextPaymentDue = a.nextPaymentDue;
facility.rateType = a.rateType;
facility.dayCountConvention = a.dayCountConvention;
facility.renewable = a.renewable;
facility.paymentScheduleHash = a.paymentScheduleHash;
facility.rateIndexRef = a.rateIndexRef;
facility.renewalTermsHash = a.renewalTermsHash;
}
function _creditTermsHash(Facility storage f) private view returns (bytes32) {
OriginationTerms memory original = OriginationTerms({
classId: f.classId,
borrowerId: f.borrowerId,
stateId: f.stateId,
principal: f.principal,
ltvBps: f.ltvBps,
interestRateBps: f.interestRateBps,
maturity: f.maturity,
fundingRecipient: f.fundingRecipient,
paymentInterval: f.paymentInterval,
nextPaymentDue: f.nextPaymentDue,
rateType: f.rateType,
dayCountConvention: f.dayCountConvention,
renewable: f.renewable,
paymentScheduleHash: f.paymentScheduleHash,
rateIndexRef: f.rateIndexRef,
renewalTermsHash: f.renewalTermsHash,
offchainRef: f.offchainRef,
pik: f.pik
});
return keccak256(abi.encode(original));
}
function _requireAccrualTerms(uint256 id, bool pik, uint8 rateType, uint8 dayCount) private pure {
if (rateType != _FIXED || dayCount == _THIRTY_360 || (pik && dayCount != _ACTUAL_360)) {
revert Bridge_AccrualUnsupportedTerms(id);
}
}
function _aggregate(uint64 cashDue, uint64 pikDue, uint64 maturity) private pure returns (uint64) {
uint64 effectivePik = pikDue == 0 ? maturity : pikDue;
return cashDue < effectivePik ? cashDue : effectivePik;
}
function _originationHash(uint256 generation, OriginationTerms memory common, InterestLegTerms memory legs)
private
pure
returns (bytes32)
{
// Generation zero preserves the reviewed first-preparation commitment. Only a deliberate
// cancellation changes the domain, minimizing tooling churn while making that act durable.
if (generation == 0) return keccak256(abi.encode(ORIGINATION_DOMAIN, common, legs));
return keccak256(abi.encode(ORIGINATION_DOMAIN, generation, common, legs));
}
function _setCashDue(uint256 id, uint64 maturity, uint64 nextDue)
private
returns (uint64 previousAggregate, uint64 nextAggregate)
{
InterestLegTerms storage leg = _known(id);
uint64 previous = leg.nextCashPaymentDue;
// A bullet cash schedule can receive more than one partial payment after its cash clock
// has reached legal maturity. The aggregate bridge clock may still expose an earlier PIK
// boundary, so WaterfallEngine cannot identify this no-op from Facility.nextPaymentDue.
// Admit only the exact terminal repetition; every other cash-clock update stays strict.
if (nextDue == previous && nextDue == maturity) {
previousAggregate = _aggregate(previous, leg.nextPikCapitalization, maturity);
return (previousAggregate, previousAggregate);
}
if (nextDue <= previous || nextDue > maturity) revert MixedInterest_InvalidTerms();
previousAggregate = _aggregate(previous, leg.nextPikCapitalization, maturity);
leg.nextCashPaymentDue = nextDue;
nextAggregate = _aggregate(nextDue, leg.nextPikCapitalization, maturity);
emit MixedInterestLegDueSet(id, 0, previous, nextDue);
}
function _setPikDue(uint256 id, uint64 maturity, uint64 nextDue)
private
returns (uint64 previousAggregate, uint64 nextAggregate)
{
InterestLegTerms storage leg = _known(id);
uint64 previous = leg.nextPikCapitalization;
if (previous == 0 || (nextDue != 0 && (nextDue <= previous || nextDue > maturity))) {
revert MixedInterest_InvalidTerms();
}
previousAggregate = _aggregate(leg.nextCashPaymentDue, previous, maturity);
leg.nextPikCapitalization = nextDue;
nextAggregate = _aggregate(leg.nextCashPaymentDue, nextDue, maturity);
emit MixedInterestLegDueSet(id, 1, previous, nextDue);
}
function _liveFacility(BridgeStorage storage bridge, uint256 id) private view returns (Facility storage facility) {
if (id == 0 || id >= bridge.nextId) revert Bridge_UnknownToken(id);
return bridge.facilities[id];
}
function _known(uint256 id) private view returns (InterestLegTerms storage leg) {
leg = _state().terms[id];
if (leg.cashRateBps == 0) revert MixedInterest_NotConfigured(id);
}
function _state() private pure returns (State storage $) {
assembly {
$.slot := MIXED_STORAGE_LOCATION
}
}
function _isBorrowerPayoutRegistry(address registry_) private view returns (bool valid) {
if (registry_.code.length == 0) return false;
(bool ok, bytes memory data) =
registry_.staticcall(abi.encodeCall(IComplianceRegistry.isFundingRecipientAllowed, (address(0))));
if (!ok || data.length != 32) return false;
uint256 word;
assembly ("memory-safe") {
word := mload(add(data, 0x20))
}
return word <= 1;
}
function _bridgeStorage() private pure returns (BridgeStorage storage bridge) {
assembly {
bridge.slot := BRIDGE_SLOT
}
}
}
src/interfaces/IAccrualLifecycle.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
/// @title IAccrualLifecycle
/// @notice Authenticated loan events consumed by the reserve's continuous accounting book.
/// @dev These methods accept no caller-selected accounting timestamp or interest correction.
interface IAccrualLifecycle {
/// @notice Supported forward fixed-rate terms, projected from a consumed bridge amendment.
struct Terms {
uint16 rateBps;
uint32 yearSeconds;
uint64 nextPaymentDue;
uint64 paymentInterval;
uint64 maturity;
}
/// @notice Prospective fixed Actual/360 terms for one concurrent cash/PIK facility.
struct MixedTerms {
uint16 cashRateBps;
uint16 pikRateBps;
uint32 yearSeconds;
uint64 nextPikCapitalization;
uint64 pikCapitalizationInterval;
uint64 maturity;
}
/// @notice Contractual debt, separately disclosed from the reserve's streamed accounting face.
struct Debt {
uint256 principal;
uint256 interest;
uint256 balanceCeiling;
uint64 accruedThrough;
uint64 nextCapitalization;
uint64 maturity;
bool pik;
bool active;
bool known;
}
/// @notice Current unpaid interest separated by its legal settlement leg.
/// @dev `mixed` distinguishes a concurrent facility from the equivalent balances on a
/// one-leg note. Unknown or disabled records return the all-zero shape.
struct InterestLegs {
uint256 cash;
uint256 pik;
uint64 accruedThrough;
bool mixed;
bool known;
}
/// @notice Registers the bound waterfall's just-funded, authenticated bridge facility.
function registerAccruingLoan(uint256 facilityId) external;
/// @notice Processes a bounded number of chronological due events; partial progress persists.
function checkpointAccrual(uint256 maximum) external returns (uint256 processed, bool fresh);
/// @notice Transfers one facility's existing virtual receivable into its native face ledger.
function postAccruedLoan(uint256 facilityId) external returns (uint256 amount);
/// @notice Applies the bridge's consumed, authenticated amendment prospectively.
function amendAccruingLoan(uint256 facilityId, Terms calldata terms) external;
/// @notice Applies the bridge's consumed, authenticated two-leg amendment prospectively.
function amendMixedAccruingLoan(uint256 facilityId, MixedTerms calldata terms) external;
/// @notice Aligns and permanently stops the facility before its default declaration snapshot.
function stopAccruingLoan(uint256 facilityId) external;
/// @notice Changes only the bound default manager's growing past-due cohort membership.
function setAccrualPastDue(uint256 facilityId, bool marked) external;
/// @notice Contractual debt through the capped, coherent portfolio frontier, in constant time.
function accruedDebt(uint256 facilityId) external view returns (Debt memory);
/// @notice Current cash-pay and PIK balances through the same coherent frontier, in constant time.
function accruedInterestLegs(uint256 facilityId) external view returns (InterestLegs memory);
/// @notice Additional unposted interest on a class's marked past-due cohort.
function accruedPastDue(uint256 classId) external view returns (uint256 amount);
/// @notice Streamed book face not yet posted for one facility; distinct from canonical interest.
function unpostedAccruedLoan(uint256 facilityId) external view returns (uint256 amount);
/// @notice Read at most 100 facility contributions through one coherent portfolio frontier.
/// @dev Values equal individual unpostedAccruedLoan reads in the supplied order, including duplicates.
function unpostedAccruedLoans(uint256[] calldata facilityIds) external view returns (uint256[] memory amounts);
}
/// @notice The reserve alone advances already signed PIK capitalization boundaries.
interface IAccrualBridge {
function setAccruedPaymentDue(uint256 facilityId, uint64 nextDue) external;
}
/// @notice Narrow notification of a posted receivable already counted in effective exposure.
interface IAccrualRegistry {
function recordAccruedExposure(uint256 classId, bytes32 borrowerId, bytes32 stateId, uint256 amount) external;
}
/// @notice Moves already-counted cohort growth into the default manager's recorded risk carrier.
interface IAccrualRisk {
function onAccrualPosted(uint256 facilityId, uint256 amount) external;
}
/// @notice The waterfall changes its standing interest fee only prospectively.
interface IAccrualFeeConfig {
function setAccrualFee(uint16 feeBps, address recipient) external;
}
/// @notice Constant-time servicing of signed dates with no positive queued accrual work.
interface IAccrualServicing {
function serviceAccruedLoan(uint256 facilityId) external returns (uint256 capitalized);
function accrualLoanScheduled(uint256 facilityId) external view returns (bool);
}
/// @notice Explicit native loss allocation of an independently derived sub-unit discrepancy.
interface IAccrualRounding {
/// @notice Monotone unabsorbed contractual rounding loss, never caller-selected debt relief.
function roundingLossUnabsorbed() external view returns (uint256);
/// @notice Controller-only consumption of one exact reserve-owned physical burn permit.
/// @dev Returns false outside a rounding continuation; normal loss admission then applies.
function consumeAccrualLossBurn(address caller, address from, uint256 amount) external returns (bool);
}
/// @notice The reserve reduces only a marked contribution whose face it has actually written down.
interface IAccrualRoundingRisk {
function onAccrualRounding(uint256 facilityId, uint256 amount) external;
}
/// @notice Registry continuation paired with a reserve-proved native rounding write-down.
interface IAccrualRoundingRegistry {
function recordAccruedWriteDown(uint256 classId, bytes32 borrowerId, bytes32 stateId, uint256 amount) external;
}
/// @notice Measured receipt settlement and terminal retirement, separately bound to servicing modules.
interface IAccrualReceipts {
/// @notice Measures an attested receipt and discharges separately tracked principal and interest.
function repayAccruingLoan(uint256 facilityId, address payer, uint256 principal, uint256 interest)
external
returns (uint256 outstanding);
/// @notice Releases a fully extinguished, resolved facility's active-book slot after its risk hooks.
function retireAccruedLoan(uint256 facilityId) external;
}
src/interfaces/IAttestationOracle.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
/// @title IAttestationOracle
/// @notice Off-chain → on-chain synchronization layer (ADR-0007). Facilities may not
/// mint, and material state may not advance, without the required attestations.
/// @dev TRUST NOTE (state prominently everywhere): the protocol executes faithfully on
/// whatever authorized attesters assert. A false attestation or compromised
/// attester key means the protocol acts on false information. This is the
/// protocol's primary trust assumption (ADR-0007; brief Part 11 gate 6).
interface IAttestationOracle {
/// @notice Attestation kinds, per ADR-0007 / the legal-wrapper sync table.
enum AttestationKind {
AssignmentExecuted,
UCCFiled,
CreditIssued,
PaymentReceived,
DefaultDeclared,
Valuation,
LossRealized,
PastDueCured,
TermsAmended,
/// @dev One-shot opening debt for continuous accrual. The payload binds the reserve,
/// migration session, cutoff, facility identity, contractual cursor and balances.
AccrualOpening
}
/// @notice Lifecycle of a single ECONOMIC FACT, keyed by (facilityId, kind, payload).
/// @dev AUDIT FIX (C4-01/C4-02). This enum exists because the EIP-712 DIGEST is the wrong
/// uniqueness key: `nonce`, `asOf` and `expiry` are all inside the digest but outside the
/// fact, so the SAME real-world event re-signed under a fresh nonce produced a fresh
/// digest and sailed past `used[digest]`. The fact key is digest-independent, so a fact
/// leaves `None` exactly once and never returns to it. See `attest`.
/// @custom:member None Never recorded — the only state from which `attest` accepts the fact.
/// @custom:member Recorded Accepted and standing; the credit layer has not spent it yet.
/// @custom:member Consumed Spent by a CREDIT_ROLE module (the write-down/distribution ran).
/// @custom:member Revoked Governance killed it (C4-02: a DURABLE tombstone, not just a flag).
enum FactStatus {
None,
Recorded,
Consumed,
Revoked
}
/// @notice One attested fact, signed by m-of-n authorized attesters over EIP-712.
/// @param facilityId The facility.
/// @param kind The attestation kind.
/// @param payload Kind-specific commitment. Valuation stores the 18-decimal value
/// directly; operational facts commit to their complete action parameters
/// (terms, payment id/payer/amounts/due date, evidence hash, or amendment id).
/// @param asOf The ATTESTED observation time (inside the signed payload — not the
/// submission block time; freshness rules depend on this, ADR-0017 §4).
/// @param expiry Submission deadline for this signed bundle.
/// @param nonce Uniqueness salt (any unused value; digests are consume-once).
struct AttestationInput {
uint256 facilityId;
AttestationKind kind;
bytes32 payload;
uint64 asOf;
uint64 expiry;
uint256 nonce;
}
// ── Events ───────────────────────────────────────────────────────────
/// @notice Emitted once per recovered signer of an accepted attestation.
event Attested(uint256 indexed facilityId, AttestationKind indexed kind, address indexed attester, uint64 at);
/// @notice The fact is now on-chain truth (threshold met).
event AttestationSatisfied(uint256 indexed facilityId, AttestationKind indexed kind, bytes32 payload, uint64 asOf);
/// @notice A one-shot fact was consumed by the credit layer (e.g. a
/// PaymentReceived spent by its distribution).
event AttestationConsumed(uint256 indexed facilityId, AttestationKind indexed kind, address indexed by);
/// @notice Governance revoked a fact (e.g. discovered-false attestation).
event AttestationRevoked(uint256 indexed facilityId, AttestationKind indexed kind);
event ThresholdSet(AttestationKind indexed kind, uint8 threshold);
// NOTE: `ValuationWatermarkReset` and the `resetValuationWatermark` lever were REMOVED
// (owner decision 2026-07-22). The H-02 anti-rollback watermark itself is unchanged; a stuck
// watermark is recovered via the oracle's timelocked UUPS upgrade, not a dedicated lever.
// ── Errors ───────────────────────────────────────────────────────────
error Oracle_Expired(uint64 expiry);
error Oracle_BadAsOf(uint64 asOf);
error Oracle_DigestAlreadyUsed(bytes32 digest);
error Oracle_ThresholdNotMet(uint8 required, uint256 provided);
error Oracle_NotAttester(address recovered);
error Oracle_UnorderedSigners(address prev, address current);
error Oracle_ZeroValuation();
error Oracle_StaleValuation(uint64 asOf, uint64 existing);
error Oracle_NotSatisfied(uint256 facilityId, AttestationKind kind);
/// @notice Process or revoke the current action before submitting another of the same kind.
error Oracle_UnconsumedFact(uint256 facilityId, AttestationKind kind, bytes32 payload);
error Oracle_BadThreshold();
/// @notice AUDIT FIX (C4-01/C4-02): this economic fact has already left `None`. It was
/// recorded, spent, or revoked, and no re-signing under a fresh nonce brings it back.
/// @param factKey keccak256(abi.encode(facilityId, uint8(kind), payload)) — see `factKey`.
/// @param status The terminal-for-`attest` state the fact is already in.
error Oracle_FactAlreadyRealised(bytes32 factKey, FactStatus status);
// ── Submission (permissionless relay of attester signatures) ─────────
/// @notice Records `a` as on-chain truth if at least the kind's threshold of
/// DISTINCT authorized attesters signed exactly this struct (EIP-712).
/// Anyone may relay the bundle; the signatures are the authority.
function attest(AttestationInput calldata a, bytes[] calldata signatures) external;
// ── Credit-layer consumption ─────────────────────────────────────────
/// @notice Clears the satisfied flag of a one-shot fact (payload/asOf retained
/// for audit). Only a wired CREDIT_ROLE module may consume a fact.
function consume(uint256 facilityId, AttestationKind kind) external;
// ── Governance ───────────────────────────────────────────────────────
/// @notice Revokes a fact (clears satisfied; a revoked Valuation is zeroed so the
/// margin path blocks until a fresh mark). Timelocked governance only.
function revoke(uint256 facilityId, AttestationKind kind) external;
// NOTE (owner decision 2026-07-22): the `resetValuationWatermark` recovery lever was REMOVED.
// The H-02 anti-rollback watermark itself is unchanged. Rationale: the lever was also an
// attack surface -- governance goes through a PUBLIC timelock queue, so a queued reset let a
// holder of a pre-signed OLDER valuation race the watermark down the instant it executed,
// re-opening the rollback the watermark prevents. The rare "watermark stuck at a far-future
// asOf after an attester-quorum compromise" recovery is instead handled by the oracle's
// timelocked UUPS upgrade (redundant with the lever, without the race surface). This
// supersedes the 2026-07-21 decision to keep it.
/// @notice Sets a kind's m-of-n threshold (>= 1). Timelocked governance only.
function setThreshold(AttestationKind kind, uint8 threshold_) external;
// ── Views ────────────────────────────────────────────────────────────
/// @notice True if `facilityId` has a currently valid attestation of `kind`.
function isSatisfied(uint256 facilityId, AttestationKind kind) external view returns (bool);
/// @notice Latest attested valuation mark for a facility (conservative, haircut).
/// @return value 18-dec USD mark (0 = no valid mark).
/// @return asOf Attested observation time of the mark (staleness checks per
/// ADR-0015 for marked-to-market classes).
function latestValuation(uint256 facilityId) external view returns (uint256 value, uint64 asOf);
/// @notice Latest recorded fact for (facility, kind).
function latestPayload(uint256 facilityId, AttestationKind kind)
external
view
returns (bytes32 payload, uint64 asOf, bool satisfied);
/// @notice The facility's valuation anti-rollback high-watermark: the highest attested
/// `asOf` ever ACCEPTED for this facility, preserved across `revoke` and `consume`.
/// A new `Valuation` must beat it strictly.
/// @param facilityId The facility identifier.
/// @return highestAsOf Highest accepted observation time (0 = never marked).
function valuationWatermark(uint256 facilityId) external view returns (uint64 highestAsOf);
/// @notice Current m-of-n threshold for a kind.
function threshold(AttestationKind kind) external view returns (uint8);
/// @notice True if an attestation digest was already submitted (replay guard).
/// @dev NOT a fact-uniqueness guard — it is defeated by re-signing the same fact under a
/// fresh nonce. Read `factStatus` for "has this real-world event already been realised".
function digestUsed(bytes32 digest) external view returns (bool);
/// @notice The consume-once key for an economic fact: the (facility, kind, payload) triple,
/// with the digest's replay salt (`nonce`/`asOf`/`expiry`) DELIBERATELY excluded.
/// @dev AUDIT FIX (C4-01). Exposed so relayers and attester tooling can check whether a fact
/// is already spent before paying for signatures.
/// @param facilityId The facility the fact concerns.
/// @param kind The attestation kind.
/// @param payload The kind-specific commitment identifying the real-world event.
/// @return key keccak256(abi.encode(facilityId, uint8(kind), payload)).
function factKey(uint256 facilityId, AttestationKind kind, bytes32 payload) external pure returns (bytes32 key);
/// @notice Lifecycle state of one economic fact (C4-01/C4-02). `None` is the only state from
/// which `attest` accepts it; the transition out of `None` is irreversible.
/// @dev Always `None` for `Valuation`: a valuation is a monotone OBSERVATION SERIES, not a
/// one-shot event, and its uniqueness key is `valuationWatermark`, not the payload. Two
/// genuinely distinct marks may legitimately carry the identical value.
/// @param facilityId The facility the fact concerns.
/// @param kind The attestation kind.
/// @param payload The kind-specific commitment identifying the real-world event.
/// @return status `None` if never realised; otherwise `Recorded`, `Consumed` or `Revoked`.
function factStatus(uint256 facilityId, AttestationKind kind, bytes32 payload)
external
view
returns (FactStatus status);
/// @notice The EIP-712 digest attesters sign for `a`.
/// @dev Exposed for signing tools, atomic executors, and replay-safe relayers.
function attestationDigest(AttestationInput calldata a) external view returns (bytes32);
}
src/interfaces/ICollateralRegistry.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
/// @title ICollateralRegistry
/// @notice Per-vertical collateral-class parameters and book-level concentration
/// accounting (ADR-0003 as amended: five classes at genesis, one of which is
/// marked-to-market per ADR-0015).
interface ICollateralRegistry {
/// @notice How a class's collateral behaves — drives valuation and remedy paths.
enum CollateralModel {
Receivable, // legal-enforcement remedies (UCC foreclosure, secondary sale)
MarkedToMarket // margin-call / liquidation remedies (ADR-0015)
}
struct ClassParams {
string name;
CollateralModel model;
bool active;
uint16 maxLtvBps; // draw ceiling (initial LTV for MTM classes)
uint64 maxMaturity; // seconds from origination
uint16 concentrationLimitBps; // max share of total book in this class
// ── marked-to-market extension (zero for receivable classes) ──────
uint16 marginCallLtvBps; // breach → MarginCalled + cure window
uint16 liquidationLtvBps; // breach / cure expiry → LiquidationInitiated
uint64 maxMarkAge; // valuation freshness bound (seconds)
}
event ClassSet(uint256 indexed classId);
event ExposureRecorded(uint256 indexed classId, bytes32 indexed borrowerId, bytes32 indexed stateId, int256 delta);
/// @notice Emitted alongside `ExposureRecorded` when the increase came from PIK capitalisation
/// rather than from an origination, so the two are distinguishable in the event stream.
/// @dev Origination exposure is a decision somebody made and an admission check passed.
/// Capitalised exposure is arithmetic on a term already agreed. A reader reconciling the
/// book needs to tell them apart, and `ExposureRecorded` alone cannot.
event CapitalizedExposureRecorded(
uint256 indexed classId, bytes32 indexed borrowerId, bytes32 indexed stateId, uint256 principal
);
event BorrowerLimitSet(uint16 limitBps);
/// @notice Governance set a per-borrower concentration limit overriding the global one.
/// @param borrowerId The borrower key.
/// @param limitBps The borrower's own max share of the book, in bps.
event BorrowerLimitOverrideSet(bytes32 indexed borrowerId, uint16 limitBps);
/// @notice Governance removed a per-borrower override; the global limit applies again.
/// @param borrowerId The borrower key.
event BorrowerLimitOverrideCleared(bytes32 indexed borrowerId);
event StateLimitSet(uint16 limitBps);
event ConcentrationFloorSet(uint256 floor);
/// @notice Governance changed the forward weight of an UNATTESTED past-due mark
/// (OWNER DECISION 2026-08-07).
/// @param bps The new weight, in bps of the executable senior charge.
event PastDueWeightSet(uint256 bps);
/// @notice A class crossed FROM within its concentration limit TO above it
/// (AUDIT FIX M-02). This is a book-shrink artefact: an amortising
/// repayment, a default write-down, or the retirement of an unfunded
/// facility removes exposure elsewhere, so an untouched class's SHARE of the
/// remaining book rises without that class growing. Such a decrease can never
/// be blocked (blocking it would let a concentration limit veto a loss being
/// realized, inverting the loss cascade), so the breach is reported, not
/// prevented — and no new exposure may be added to the class while it stands.
/// @param classId The class now above its limit.
/// @param exposure The class's exposure after the change (18-dec).
/// @param totalExposure The whole book's exposure after the change (18-dec).
/// @param limitBps The class's configured limit as a share of the book.
/// @param bookAboveFloor Whether the whole book is above the bootstrap floor. False
/// means this is ordinary genesis concentration on a book too small for the
/// relative limits to be the operative constraint (the absolute allowance
/// `limitBps * floor / BPS` is); alerting should filter on this rather than
/// treat a first facility at 100% of a tiny book as a risk incident.
event ConcentrationDrift(
uint256 indexed classId, uint256 exposure, uint256 totalExposure, uint16 limitBps, bool bookAboveFloor
);
/// @notice A class that was above its concentration limit is back within it — because
/// the book grew around it or its own exposure fell (AUDIT FIX M-02).
/// @param classId The class now within its limit.
/// @param exposure The class's exposure after the change (18-dec).
/// @param totalExposure The whole book's exposure after the change (18-dec).
/// @param limitBps The class's configured limit as a share of the book.
/// @param bookAboveFloor Whether the whole book is above the bootstrap floor.
event ConcentrationHealed(
uint256 indexed classId, uint256 exposure, uint256 totalExposure, uint16 limitBps, bool bookAboveFloor
);
/// @notice A borrower crossed FROM within its concentration limit TO above it
/// (AUDIT FIX M-02). Emitted for the borrower a write touches and for any id
/// passed to `syncConcentrationBreaches`; the borrower key set is unbounded and
/// not enumerable on-chain, but is fully recoverable from `ExposureRecorded`.
event BorrowerConcentrationDrift(
bytes32 indexed borrowerId, uint256 exposure, uint256 totalExposure, uint16 limitBps, bool bookAboveFloor
);
/// @notice A borrower that was above its concentration limit is back within it.
event BorrowerConcentrationHealed(
bytes32 indexed borrowerId, uint256 exposure, uint256 totalExposure, uint16 limitBps, bool bookAboveFloor
);
/// @notice A US state crossed FROM within its concentration limit TO above it.
event StateConcentrationDrift(
bytes32 indexed stateId, uint256 exposure, uint256 totalExposure, uint16 limitBps, bool bookAboveFloor
);
/// @notice A US state that was above its concentration limit is back within it.
event StateConcentrationHealed(
bytes32 indexed stateId, uint256 exposure, uint256 totalExposure, uint16 limitBps, bool bookAboveFloor
);
error Registry_UnknownClass(uint256 classId);
error Registry_ClassInactive(uint256 classId);
error Registry_BadParams();
/// @notice A configured class cannot change between receivable and marked-to-market
/// accounting. The model selects materially different valuation and remedy
/// paths and is fixed for the lifetime of a launch class.
error Registry_ModelImmutable(uint256 classId);
/// @notice The requested principal would push the book past the range in which the
/// concentration arithmetic is provably overflow-free. Fails loudly with a
/// decodable error rather than an arithmetic panic.
error Registry_PrincipalTooLarge();
/// @notice `setPastDueWeight` was asked for a weight of zero (which re-opens H-5/D5-03 by
/// disabling the only permissionless senior protection on receivables) or a weight of
/// `Config.BPS` or more (which restores the defect the weight exists to fix: an
/// unattested mark carrying the same forward weight as an attested declared default).
/// OWNER DECISION 2026-08-07. DO NOT DELETE EITHER BOUND.
/// @param bps The rejected weight.
error Registry_InvalidPastDueWeight(uint256 bps);
error Registry_ConcentrationExceeded(uint256 classId, uint256 wouldBe, uint256 limit);
error Registry_BorrowerConcentrationExceeded(bytes32 borrowerId, uint256 wouldBe, uint256 limit);
error Registry_StateConcentrationExceeded(bytes32 stateId, uint256 wouldBe, uint256 limit);
error Registry_ExposureUnderflow();
/// @notice Sets/updates a collateral class. Timelocked governance only.
/// @dev A class's collateral model is immutable after its first configuration.
function setClass(uint256 classId, ClassParams calldata p) external;
/// @notice Sets a per-borrower concentration limit overriding the global borrower limit.
function setBorrowerLimitOverride(bytes32 borrowerId, uint16 limitBps) external;
/// @notice Clears a per-borrower concentration limit override.
function clearBorrowerLimitOverride(bytes32 borrowerId) external;
/// @notice Class parameters (reverts for unknown classes).
function classParams(uint256 classId) external view returns (ClassParams memory);
/// @notice Reverts unless adding `principal` for (`classId`,`borrowerId`,`stateId`)
/// respects every concentration limit (class, borrower, state). View-only;
/// `recordExposure` performs the same checks at write time.
function checkConcentration(uint256 classId, bytes32 borrowerId, bytes32 stateId, uint256 principal)
external
view;
/// @notice Unfunded exposure already included in the ordinary registry book.
/// @dev Supplied by the bridge's complete, independently tracked Pending ledger. These
/// amounts are removed from both the funding denominator and its matching dimensions.
struct PendingExposure {
uint256 total;
uint256 classAmount;
uint256 borrowerAmount;
uint256 stateAmount;
}
/// @notice A Pending-ledger subtraction does not match the existing exposure book.
error Registry_InvalidPendingExposure();
/// @notice Checks admission against funded exposure plus the Pending facility itself.
/// @dev View-only; the bridge supplies its exact Pending ledger before any deployment.
/// Passing fabricated values to this public view grants no funding authority.
/// @param classId The facility's collateral class.
/// @param borrowerId Its authenticated borrower identity.
/// @param stateId Its state identity, or zero when not applicable.
/// @param principal The already recorded Pending principal being funded.
/// @param pending Complete Pending totals for the same identities.
function checkFundingConcentration(
uint256 classId,
bytes32 borrowerId,
bytes32 stateId,
uint256 principal,
PendingExposure calldata pending
) external view;
/// @notice Records an exposure increase (origination). Only CREDIT_ROLE (the
/// collateral/credit layer). Enforces all concentration limits.
function recordExposureIncrease(uint256 classId, bytes32 borrowerId, bytes32 stateId, uint256 principal) external;
/// @notice Records an exposure increase that came from PIK interest CAPITALISATION rather than
/// from an origination. Only CREDIT_ROLE. Books the exposure and reports every
/// concentration breach exactly as the origination path does, but does NOT revert on
/// one.
///
/// @dev WHY THIS IS NOT A HOLE IN THE CONCENTRATION LIMIT, and why it is not optional.
/// A concentration limit governs ADMISSION: it decides whether the book takes on a new
/// risk somebody chose to take. Compounding interest is not that. Nobody elects it, the
/// borrower cannot decline it, no capital moves, and the obligation was priced at
/// origination when the limit was checked. Routing it through `recordExposureIncrease`
/// meant a PIK book grew into its own limit with no adversary and then FROZE, and because
/// `ClaimBridge.nextPaymentDue` only advances inside `WaterfallEngine.capitalizePik`, the
/// freeze turned a borrower performing exactly as contracted into a permissionlessly
/// markable past-due facility, and through `DefaultManager.pastDueExposure` into pending
/// senior impairment. The protocol's own refusal became the credit event.
///
/// WHAT IS PRESERVED. The class must be known; the overflow bound that keeps the
/// concentration arithmetic safe still applies; the exposure is booked in full, which is
/// what keeps the facility WRITEABLE OFF (`realizeLoss` pairs its write-down with
/// `recordExposureDecrease`, which reverts `Registry_ExposureUnderflow` if exposure lags);
/// and every breach flag and drift event fires. Governance sees the limit crossed. The
/// limit keeps its whole observation function and loses only its ability to brick a
/// performing borrower.
///
/// `recordExposureDecrease` already carries this exact reasoning for the same reason:
/// "Reporting only - never a revert path."
///
/// WHAT THIS ADDS TO `CREDIT_ROLE`, stated because an auditor will ask. The role could
/// already move exposure in both directions: `recordExposureIncrease` upward subject to
/// the limits, and `recordExposureDecrease` downward with no check at all. This adds an
/// upward path that skips the limit, so a CREDIT_ROLE holder can now inflate a class past
/// its concentration ceiling. That moves NO VALUE - exposure is a reporting and
/// write-off-accounting quantity, not a balance - and it moves the book in the
/// CONSERVATIVE direction, making it read as more concentrated than it is. The role
/// remains a protocol-modules-only grant for the reasons recorded on
/// `recordExposureDecrease`, and this function does not change that requirement.
///
/// IF FOREST ROAD WANTS CAPITALISATION TO HARD-STOP AT THE LIMIT INSTEAD, that is a
/// one-line change back to `recordExposureIncrease` in `WaterfallEngine.capitalizePik`,
/// and it reinstates the denial of service knowingly rather than by accident.
function recordCapitalizedExposure(uint256 classId, bytes32 borrowerId, bytes32 stateId, uint256 principal)
external;
/// @notice Records an exposure decrease (repayment/writedown). Only CREDIT_ROLE.
function recordExposureDecrease(uint256 classId, bytes32 borrowerId, bytes32 stateId, uint256 principal) external;
/// @notice Current book exposure per class / borrower / state (18-dec).
function classExposure(uint256 classId) external view returns (uint256);
function borrowerExposure(bytes32 borrowerId) external view returns (uint256);
function stateExposure(bytes32 stateId) external view returns (uint256);
function totalBookExposure() external view returns (uint256);
/// @notice A class's current share of the whole book, in bps (0 on an empty book).
function classConcentrationBps(uint256 classId) external view returns (uint256);
/// @notice Whether a dimension's CURRENT share of the book exceeds its configured
/// limit — the standing disclosure fact, floor-independent (AUDIT FIX M-02).
function isOverConcentrated(uint256 classId, bytes32 borrowerId, bytes32 stateId)
external
view
returns (bool classOver, bool borrowerOver, bool stateOver);
/// @notice The forward weight, in bps, that an UNATTESTED permissionless past-due mark
/// (`DefaultManager.markPastDue`) carries in the conservative redemption NAV,
/// relative to an ATTESTED declared default (OWNER DECISION 2026-08-07).
/// @dev Governed credit-risk policy, so it lives with the advance rates and concentration
/// limits rather than in DefaultManager (which is EIP-170 constrained and contended).
/// Never returns zero: an unset slot reads `Config.DEFAULT_PAST_DUE_WEIGHT_BPS`.
/// @return bps The effective weight, strictly between 0 and `Config.BPS`.
function pastDueWeightBps() external view returns (uint256 bps);
/// @notice Applies the governed unattested-past-due weight to an executable senior charge.
/// @dev Called by `DefaultManager.pendingSeniorImpairment` on the past-due cohort's charge
/// AFTER the executable bound has been applied. Rounds UP (over-mark is the safe
/// direction). OWNER DECISION 2026-08-07 — DO NOT turn this into a pass-through.
/// @param amount The executable senior charge attributable to the past-due cohort.
/// @return weighted The discounted charge that enters the conservative redemption NAV.
function weightedPastDueImpairment(uint256 amount) external view returns (uint256 weighted);
/// @notice The TOTAL conservative senior mark: the attested cohort at full weight plus the
/// unattested past-due cohort, clamped to executable capacity and ramp-weighted.
/// @dev OWNER DECISION 2026-08-07. Clamps `pastDueSenior` to the senior absorption capacity
/// `realizeLoss` could actually reach today (`vaultAssets` less the attested cohort's prior
/// claim), THEN applies the governed weight, which itself ramps from
/// `pastDueWeightBps()` back to `Config.BPS` over one `Config.DEFAULT_REDEEM_COOLDOWN`.
/// Both the CLAMP-BEFORE-WEIGHT order and the ramp's expiry are load-bearing; see the
/// implementation NatSpec.
/// @param pastDueSenior The past-due cohort's post-junior senior residual.
/// @param residual The TOTAL post-junior senior residual (both cohorts), unweighted.
/// @param vault The `sUSDfr` vault whose `totalAssets()` is layer 3's hard ceiling in
/// `realizeLoss`. Read here rather than passed in as a number so the governed weight and
/// the ceiling it is applied to stay in one timelocked module; see the implementation
/// NatSpec, which also carries the recursion warning.
/// @param anchor `DefaultManager.pastDueReliefAnchor`. ZERO (unset) fails SAFE to full weight.
/// @return mark The total conservative senior impairment entering the redemption NAV.
function conservativeSeniorMark(uint256 pastDueSenior, uint256 residual, address vault, uint256 anchor)
external
view
returns (uint256 mark);
/// @notice The forward weight, in bps, an unattested past-due mark carries after `elapsed`
/// seconds of its relief ramp (OWNER DECISION 2026-08-07).
/// @dev Ramps linearly from `pastDueWeightBps()` at `elapsed == 0` to `Config.BPS` at
/// `elapsed >= Config.DEFAULT_REDEEM_COOLDOWN`, and stays at `Config.BPS` thereafter.
/// A read-only convenience for operations and reference models; the mark itself does NOT
/// route through it (see the implementation NatSpec for why).
/// @param elapsed Seconds since `DefaultManager.pastDueReliefAnchor`.
/// @return bps The effective weight, in `[pastDueWeightBps(), Config.BPS]`.
function pastDueRampWeightBps(uint256 elapsed) external view returns (uint256 bps);
/// @notice Governance sets the forward weight of an unattested past-due mark.
/// @dev Rejects 0 (re-opens H-5/D5-03) and `Config.BPS` or more (restores the defect).
/// @param bps The new weight, strictly between 0 and `Config.BPS`.
function setPastDueWeight(uint256 bps) external;
/// @notice Bitmap of classes currently above their limit; bit `classId - 1` set.
/// @dev Recomputed from the book on every call — never served from a cached slot, so it
/// cannot report a clean book in the window after an implementation upgrade.
function overConcentratedClasses() external view returns (uint256 bitmap);
/// @notice The borrower concentration limit actually in force for `borrowerId`.
/// @dev The global limit assumes a vertical has many borrowers. A SINGLE-BORROWER vertical
/// (Digital Assets, ADR-0015) makes the class and borrower dimensions measure the same
/// exposure, so governance may set a per-borrower override. Every admission, breach
/// and headroom read routes through this same number.
/// @param borrowerId The borrower key.
/// @return limitBps The effective limit in bps.
/// @return overridden True when a per-borrower override is set.
function effectiveBorrowerLimitBps(bytes32 borrowerId) external view returns (uint16 limitBps, bool overridden);
/// @notice Whether each supplied borrower currently holds more than the per-borrower limit
/// as a share of the book — its OWN limit where one is overridden. The key set is
/// unbounded on-chain; recover it from the `ExposureRecorded` stream and pass it in.
function overConcentratedBorrowers(bytes32[] calldata borrowerIds) external view returns (bool[] memory over);
/// @notice Whether each supplied state currently holds more than the per-state limit as
/// a share of the book. Zero ids read false.
function overConcentratedStates(bytes32[] calldata stateIds) external view returns (bool[] memory over);
/// @notice Recomputes and events every concentration transition for all five classes
/// plus the supplied borrower/state ids. Permissionless: it moves no value and
/// only publishes facts the views already expose, so anyone (a keeper, a risk
/// desk, the upgrade transaction itself) can announce a standing breach without
/// waiting for the next origination or repayment.
function syncConcentrationBreaches(bytes32[] calldata borrowerIds, bytes32[] calldata stateIds) external;
/// @notice The largest `principal` that `checkConcentration` would admit right now for
/// (`classId`,`borrowerId`,`stateId`) — the binding minimum across the class,
/// borrower and state dimensions. Zero for an unknown or inactive class.
function concentrationHeadroom(uint256 classId, bytes32 borrowerId, bytes32 stateId)
external
view
returns (uint256);
}
src/interfaces/IComplianceRegistry.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
/// @title IComplianceRegistry
/// @notice Compliance capability layer (ADR-0011, as amended by the 2026-07-14 directive):
/// a KYC allowlist consulted ONLY at the mint/redeem primary gate, and a narrow
/// sanctions blocklist consulted on transfers. The per-token transfer-allowlist
/// capability was removed — transfers are permissionless (sanctions-only). Policy
/// (who is eligible/sanctioned) is set by governance/counsel off this interface.
interface IComplianceRegistry {
/// @notice Emitted when an account's KYC allowlist status changes.
event AllowlistUpdated(address indexed account, bool allowed);
/// @notice Emitted when an account's sanctions/jurisdiction-block status changes.
event JurisdictionBlockUpdated(address indexed account, bool blocked);
/// @notice Timelocked governance changed an address's borrower-payout approval.
/// @dev This list is deliberately independent of the operational KYC allowlist.
event FundingRecipientApprovalUpdated(address indexed account, bool approved);
/// @notice True if `account` has passed KYC and may use the gated primary paths
/// (USDfr mint/redeem). Holding and transferring are permissionless.
function isAllowed(address account) external view returns (bool);
/// @notice True if `account` is on the sanctions/jurisdiction blocklist.
function isJurisdictionBlocked(address account) external view returns (bool);
/// @notice True only when timelocked governance approved `account` as a borrower-payout
/// destination and the account is not currently jurisdiction-blocked.
function isFundingRecipientAllowed(address account) external view returns (bool);
/// @notice True for a governance-designated internal protocol module.
function isProtocolExempt(address module) external view returns (bool);
/// @notice Transfer gate consulted by protocol tokens on every transfer. Transfers are
/// permissionless except for sanctioned (blocked) parties; burns are always
/// permitted; protocol modules are never treated as blocked.
/// @param token Retained for interface stability; no longer affects the result.
/// @param from Sender (zero on mint).
/// @param to Recipient (zero on burn).
/// @return True if the transfer may proceed.
function canTransfer(address token, address from, address to) external view returns (bool);
}
src/interfaces/IContinuousAccrual.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
/// @title IContinuousAccrual
/// @notice Reserve-owned accounting and exact delivery of previously accrued interest.
/// @dev Separate from the legacy reserve interface so activation is explicit. Amounts are
/// normalized to 18 decimals. Delivery changes physical balances, never economic ownership.
interface IContinuousAccrual {
/// @notice Modules bound to one independently backed chain instance.
/// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.
struct Modules {
address token;
address controller;
address vault;
address waterfall;
address bridge;
address registry;
address defaultManager;
}
/// @notice Constant-time accounting, capped at the first unprocessed schedule boundary.
/// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.
struct Snapshot {
uint256 gross;
uint256 unposted;
uint256 unissued;
uint256 seniorUnissued;
uint256 feeUnissued;
address feeRecipient;
uint64 accruedThrough;
bool enabled;
bool fresh;
}
/// @notice Vault-computed prices and permission for a neutral physical delivery.
/// @dev entryAssets includes any unvested assets; assets is the ordinary share-price base.
/// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.
struct PricingState {
uint256 assets;
uint256 entryAssets;
uint256 redemptionAssets;
uint256 performanceAssets;
uint256 feeAdjustedShares;
bool materializationAllowed;
}
/// @notice One immutable, same-transaction permit and coherent public price snapshot.
/// @dev Unselected amounts are zero. A zero/default inactive record grants no authority.
/// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.
struct Delivery {
uint256 nonce;
uint256 senior;
uint256 fee;
uint256 effectiveSupply;
uint256 backing;
uint256 recognizedBacking;
PricingState pricing;
address controller;
address vault;
address feeRecipient;
uint64 accruedThrough;
uint8 legs;
bool active;
}
/// @notice Reads the configured module identities, including before activation.
function accrualModules() external view returns (Modules memory);
/// @notice Reads recognized income and its outstanding physical posting/issuance.
function accrualSnapshot() external view returns (Snapshot memory);
/// @notice Reads the current delivery permit, or an inactive default record.
function accrualDelivery() external view returns (Delivery memory);
/// @notice Refuses a price-sensitive write at an unresolved accrual boundary or operation.
function requireAccrualFresh() external view;
/// @notice Delivers selected existing claims: senior=1, fee=2, both=3.
/// @dev No amount, destination, timestamp or fee rate is supplied by the caller.
function materializeAccrued(uint8 legs) external returns (uint256 senior, uint256 fee);
}
/// @notice Token continuation accepting only the bound reserve's current exact permit.
interface IAccrualToken {
/// @notice The immutable-once-configured accounting reserve, or zero before binding.
function accrualReserve() external view returns (address);
/// @notice Mints the selected legs of one unused, active delivery permit.
function mintAccrued(uint256 nonce) external;
}
/// @notice Controller continuation, callable only by its configured reserve.
interface IAccrualController {
/// @notice Relays one exact reserve-owned delivery permit to the token.
function mintAccrued(uint256 nonce) external;
}
/// @notice Vault views needed to admit a neutral delivery without a guarded write callback.
interface IAccrualVault {
/// @notice The immutable-once-configured accounting reserve, or zero before binding.
function accrualReserve() external view returns (address);
/// @notice Supplies a coherent price snapshot and current delivery admission state.
function accrualPricingState() external view returns (IContinuousAccrual.PricingState memory);
}
/// @title IReliefPricingCache
/// @notice Optional exact-discount preparation; it grants no financial authority.
interface IReliefPricingCache {
/// @notice Derives reusable discounts from current protocol state, without caller-supplied values.
function prepareReliefPricing() external;
}
Compiler settingsShow
{
"metadata": {
"bytecodeHash": "ipfs"
},
"libraries": {},
"optimizer": {
"runs": 100,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"forge-std/=lib/forge-std/src/",
"halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"solady/=lib/solady/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.