Skip to content
Verified contractExactBUSL-1.1

ClaimBridge

Address0x657ba879f436cfe7dd2675f05e1699765bb30a0c
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,370
Creation transaction
0x0037e622c1…228f9f8823

42 files

The source code is large: one file is shown at a time. Choose a file in the list.

src/ClaimBridge.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;

import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {ERC721Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";

import {IAttestationOracle} from "./interfaces/IAttestationOracle.sol";
import {ICollateralRegistry} from "./interfaces/ICollateralRegistry.sol";
import {Config} from "./libraries/Config.sol";
import {LossEventIds} from "./libraries/LossEventIds.sol";
import {Roles} from "./libraries/Roles.sol";
import {IContinuousAccrual} from "./interfaces/IContinuousAccrual.sol";
import {IAccrualExposure} from "./interfaces/IAccrualExposure.sol";
import {IAccrualBridge} from "./interfaces/IAccrualLifecycle.sol";
import {BridgeAccrualLib} from "./libraries/BridgeAccrualLib.sol";
import {BridgeFundingLib} from "./libraries/BridgeFundingLib.sol";
import {BridgeMixedInterestLib} from "./libraries/BridgeMixedInterestLib.sol";

/// @title ClaimBridge - tokenized facility positions (the CALIBER analog, ADR-0006)
/// @notice Each ERC-721 token is the on-chain position of record for one identified,
///         lien-perfected facility. THE SYNCHRONIZED MINT GATE (CLAUDE.md section 1.3): a
///         facility cannot mint unless every attestation kind required for its class is
///         currently satisfied, and the deal-identity attestations (`AssignmentExecuted`,
///         `UCCFiled` and `CreditIssued`) commit to EXACTLY the terms being minted (AUDIT
///         FIX H-4 / P-32 - full payload binding; `Valuation` retains its mark payload), AND all on-chain
///         conditions hold (class active, LTV and maturity within class parameters, every
///         concentration limit respected - checked atomically through the registry).
///         Attestations that merely EXIST at a facility id are not sufficient: they must
///         attest to this obligor, this class, this amount, this tenor and this lien.
///         Escrow release is contractually
///         conditioned off-chain on the existence of this token (legal wrapper section 3).
///
///         Positions are transfer-restricted: facilities are held by protocol/SPV
///         custody addresses; transfers require governance execution, and DEFAULTED or
///         ACCELERATED positions are frozen entirely.
contract ClaimBridge is
    Initializable,
    ERC721Upgradeable,
    PausableUpgradeable,
    ReentrancyGuardUpgradeable,
    AccessControlUpgradeable,
    UUPSUpgradeable,
    IAccrualBridge
{
    enum RateType {
        Fixed,
        Variable
    }

    enum DayCountConvention {
        Actual360,
        Actual365,
        Thirty360
    }

    enum LoanState {
        Pending, // minted, awaiting funding
        Active, // funded, performing
        Amortizing, // in scheduled repayment
        Repaid, // closed, made whole
        Defaulted, // default declared - token frozen
        Accelerated, // waterfall shifted to acceleration - token frozen
        Cancelled, // AUDIT FIX (M-02): pending facility retired before funding - NFT burned
        Resolved // AUDIT FIX (M-03): defaulted facility worked out to full principal recovery

    }

    struct Facility {
        uint256 classId;
        bytes32 borrowerId; // stable pseudonymous borrower key (off-chain KYB record)
        bytes32 stateId; // US state key for tax-credit classes (zero elsewhere)
        uint256 principal; // 18-dec
        uint16 ltvBps;
        // Contractual annual rate for THIS facility, supplied and signed per facility.
        uint16 interestRateBps;
        uint64 maturity; // absolute timestamp
        address fundingRecipient; // attested destination; the servicer cannot redirect funding
        uint64 paymentInterval; // contractual seconds between scheduled payments
        uint64 nextPaymentDue; // absolute due date used by permissionless past-due marking
        RateType rateType;
        DayCountConvention dayCountConvention;
        bool renewable;
        bytes32 paymentScheduleHash; // full amortization schedule
        bytes32 rateIndexRef; // required for variable-rate facilities
        bytes32 renewalTermsHash; // required when renewable
        bytes32 offchainRef; // UCC filing / SPV-series / escrow reference hash
        LoanState state;
        /// @notice Whether this facility contractually CAPITALISES unpaid interest (PIK).
        /// @dev TAIL-APPENDED 2026-09-08. Set once at origination and never amended: `Amendment`
        ///      deliberately does not carry it, so a cash-pay facility can never be converted into a
        ///      capitalising one by a later signature. Converting the other way would also be a
        ///      restructuring, and a restructuring should be a new facility rather than a flag flip.
        ///
        ///      IT IS IN THE TERMS HASH, so it is signed by the `CreditIssued` quorum along with the
        ///      rate. Without it `WaterfallEngine.capitalizePik` had nothing to distinguish a PIK
        ///      facility from an ordinary cash-pay one, and any address could force PIK accounting
        ///      onto the cash-pay book: the interest was capitalised into `deployed` AND then paid
        ///      again in cash through `distribute`, leaving a phantom receivable that only a real
        ///      charge against curator first-loss could ever clear.
        bool pik;
    }

    struct OriginationTerms {
        uint256 classId;
        bytes32 borrowerId;
        bytes32 stateId;
        uint256 principal;
        uint16 ltvBps;
        uint16 interestRateBps;
        uint64 maturity;
        address fundingRecipient;
        uint64 paymentInterval;
        uint64 nextPaymentDue;
        RateType rateType;
        DayCountConvention dayCountConvention;
        bool renewable;
        bytes32 paymentScheduleHash;
        bytes32 rateIndexRef;
        bytes32 renewalTermsHash;
        bytes32 offchainRef;
        /// @notice Whether this facility contractually capitalises unpaid interest. Signed.
        bool pik;
    }

    struct Amendment {
        uint16 interestRateBps;
        uint64 maturity;
        uint64 paymentInterval;
        uint64 nextPaymentDue;
        RateType rateType;
        DayCountConvention dayCountConvention;
        bool renewable;
        bytes32 paymentScheduleHash;
        bytes32 rateIndexRef;
        bytes32 renewalTermsHash;
    }

    /// @custom:storage-location erc7201:forestroad.storage.ClaimBridge
    struct BridgeStorage {
        ICollateralRegistry registry;
        IAttestationOracle oracle;
        uint256 nextId;
        mapping(uint256 tokenId => Facility) facilities;
        // per-class required attestation kinds for minting (bitmask over
        // IAttestationOracle.AttestationKind)
        mapping(uint256 classId => uint256) requiredMintAttestations;
        // Permanent continuous source, appended after all historical bridge fields.
        address accrualReserve;
        // R13-M1: every accepted receipt or amendment invalidates older signed amendments.
        mapping(uint256 tokenId => uint256) servicingNonce;
    }

    // keccak256(abi.encode(uint256(keccak256("forestroad.storage.ClaimBridge")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant BRIDGE_STORAGE_LOCATION =
        0xc9c2da543a2a10e4b712709fb6548fb2c0c97cecbac3457453966d18f1663f00;

    /// @dev AUDIT FIX (section 3.1 reconstructability): carries the full originated terms so
    ///      the register - including WHEN principal is due (`maturity`) and WHICH
    ///      perfected lien backs it (`offchainRef`) - is reconstructable purely from
    ///      events, not only from the mutable `facility()` view.
    event Originated(uint256 indexed tokenId, uint256 indexed classId, bytes32 indexed borrowerId, bytes32 termsHash);
    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 state to which future amendments must bind.
    event ServicingStateAdvanced(uint256 indexed tokenId, uint256 nonce);
    event StateChanged(uint256 indexed tokenId, LoanState from, LoanState to);
    event RequiredAttestationsSet(uint256 indexed classId, uint256 kindsMask);
    /// @notice Governance permanently bound this bridge's authenticated accrual source.
    event AccrualReserveSet(address indexed reserve);
    /// @notice Governance permanently bound the borrower-payout policy used at origination.
    event BorrowerPayoutRegistrySet(address indexed registry);
    event MixedInterestOriginationPrepared(uint256 indexed tokenId, bytes32 indexed termsHash);
    /// @notice Exact staged cash/PIK metadata; activated only by a later matching origination or amendment log.
    event MixedInterestTermsStaged(
        uint256 indexed facilityId,
        bytes32 indexed actionId,
        bytes32 indexed termsHash,
        uint16 cashRateBps,
        uint16 pikRateBps,
        uint64 cashPaymentInterval,
        uint64 nextCashPaymentDue,
        uint64 pikCapitalizationInterval,
        uint64 nextPikCapitalization
    );
    event MixedInterestOriginationCancelled(uint256 indexed tokenId);
    event MixedInterestAmendmentPrepared(
        uint256 indexed tokenId, bytes32 indexed amendmentId, bytes32 indexed termsHash
    );

    /// @dev Number of `IAttestationOracle.AttestationKind` values. The mint-gate setter and the
    ///      `originate` gate loop BOTH derive from this, so a future kind cannot be accepted by
    ///      governance while remaining unread by the gate (PM-R-09).
    uint256 private constant KIND_COUNT = 9;
    /// @dev Every valid attestation-kind bit set.
    uint256 private constant KINDS_MASK_ALL = (1 << KIND_COUNT) - 1;
    /// @dev AUDIT FIX (H-4): the `CreditIssued` bit. This kind is the TERMS attestation -
    ///      the 2-of-n quorum that authorizes an amount for a counterparty - so it is
    ///      mandatory in every class's mint gate and its payload is bound in `originate`.
    uint256 private constant BIT_CREDIT_ISSUED = 1 << uint256(uint8(IAttestationOracle.AttestationKind.CreditIssued));

    error Bridge_ZeroAddress();
    /// @notice A mint-gate mask carried bits outside the known `AttestationKind` range, or was
    ///         empty. Either would leave the gate weaker than it reads (PM-R-09).
    /// @param kindsMask The rejected mask.
    error Bridge_BadAttestationMask(uint256 kindsMask);
    error Bridge_BadFacility();
    /// @notice Funding admission requires the complete historical Pending ledger.
    /// @param cursor Next unclassified historical facility.
    /// @param ceiling Captured exclusive origination frontier.
    error Bridge_FundingBookUnavailable(uint256 cursor, uint256 ceiling);
    /// @notice A bounded Pending bootstrap needs a batch between one and 100.
    /// @param supplied The rejected batch size.
    error Bridge_BadFundingBatch(uint256 supplied);
    /// @notice A Pending facility was missing from, or duplicated in, its tracked ledger.
    /// @param tokenId The inconsistent facility.
    error Bridge_PendingFundingMismatch(uint256 tokenId);
    /// @notice A bounded, on-chain-derived Pending classification batch completed.
    /// @param cursor Next historical facility to inspect.
    /// @param ceiling Captured exclusive origination frontier.
    /// @param pendingPrincipal Complete prefix's remaining Pending principal.
    /// @param ready Whether the captured prefix is fully classified.

    event FundingBookBootstrapProgress(uint256 cursor, uint256 ceiling, uint256 pendingPrincipal, bool ready);

    /// @notice Legacy PIK coupon dates can change only after migration to the native lifecycle.
    error Bridge_LegacyPikScheduleRequiresMigration(uint256 tokenId);
    error Bridge_AttestationMissing(uint256 classId, IAttestationOracle.AttestationKind kind);
    /// @notice AUDIT FIX (H-4): the currently-satisfied `CreditIssued` attestation at this
    ///         facility id does not commit to THESE terms. Either no terms were attested, or
    ///         the attested terms describe a different obligor/class/amount/tenor/lien.
    /// @param facilityId The facility id the gate read.
    /// @param expected The terms hash of the facility being originated/funded.
    /// @param attested The terms hash actually carried by the attestation (zero if none).
    error Bridge_TermsNotAttested(uint256 facilityId, bytes32 expected, bytes32 attested);
    /// @notice A deal-identity attestation is present but commits to different terms.
    /// @param classId The collateral class whose mint gate failed.
    /// @param kind The deal-identity attestation kind.
    /// @param expected The terms hash of the facility being originated/funded.
    /// @param attested The terms hash carried by the attestation.
    error Bridge_AttestationNotBoundToDeal(
        uint256 classId, IAttestationOracle.AttestationKind kind, bytes32 expected, bytes32 attested
    );
    error Bridge_ValuationStale(uint256 tokenIdOrZero, uint64 asOf, uint64 maxAge);
    error Bridge_LtvExceedsValue(uint256 principal, uint256 maxByValue);
    error Bridge_InvalidTransition(uint256 tokenId, LoanState from, LoanState to);
    error Bridge_PositionFrozen(uint256 tokenId);
    error Bridge_TransferRestricted();
    error Bridge_UnknownToken(uint256 tokenId);
    error Bridge_FacilityMatured(uint256 tokenId);
    error Bridge_ClassInactive(uint256 classId);
    error Bridge_NotPending(uint256 tokenId);
    error Bridge_TermsAmendmentNotAttested(uint256 tokenId);
    error Bridge_FacilityEventNamespaceExhausted(uint256 nextId);
    /// @notice The continuous accounting source cannot be replaced after binding.
    error Bridge_AccrualAlreadyBound();
    /// @notice Only the bound source can advance its signed PIK capitalization schedule.
    error Bridge_AccrualReserveOnly(address caller);
    /// @notice A live continuous facility must use the supported fixed-rate day-count scope.
    error Bridge_AccrualUnsupportedTerms(uint256 tokenId);
    /// @notice A continuous PIK schedule advances only through its accounting source or signed amendment.
    error Bridge_AccrualDueManaged(uint256 tokenId);
    /// @notice A mixed facility must retain both legs through its dedicated lifecycle entry point.
    error Bridge_MixedLifecycleRequired(uint256 tokenId);
    /// @notice Activation requires the enabled, fresh and version-matched continuous system.
    error Bridge_MixedInterestUnavailable();

    uint16 public constant MAX_INTEREST_RATE_BPS = 10_000;
    bytes32 private constant _MIXED_INTEREST_VERSION = keccak256("forestroad.mixed-interest.v1");

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    /// @notice Initializes the position register.
    /// @param admin Governance timelock.
    /// @param guardian Emergency pauser.
    /// @param upgrader Upgrade authority (timelock).
    /// @param registry The collateral registry (class params + concentration).
    /// @param oracle The attestation oracle (mint gate; ADR-0007 trust note applies).
    function initialize(address admin, address guardian, address upgrader, address registry, address oracle)
        external
        initializer
    {
        if (
            admin == address(0) || guardian == address(0) || upgrader == address(0) || registry == address(0)
                || oracle == address(0)
        ) revert Bridge_ZeroAddress();
        __ERC721_init("Forest Road Facility", "frFACILITY");
        __Pausable_init();
        __ReentrancyGuard_init();
        __AccessControl_init();
        __UUPSUpgradeable_init();
        _grantRole(DEFAULT_ADMIN_ROLE, admin);
        _grantRole(Roles.GUARDIAN_ROLE, guardian);
        _grantRole(Roles.UPGRADER_ROLE, upgrader);
        BridgeStorage storage $ = _storage();
        $.registry = ICollateralRegistry(registry);
        $.oracle = IAttestationOracle(oracle);
        $.nextId = 1;
        BridgeFundingLib.initialize();
    }

    /// @notice Completes bounded classification of historical Pending facilities after an upgrade.
    /// @dev Permissionless and derived only from immutable on-chain facility identities/face.
    ///      Originations and funding remain closed until the complete captured prefix is indexed.
    /// @param maxFacilities Number to inspect this call, from one to 100.
    function bootstrapFundingBook(uint256 maxFacilities) external nonReentrant {
        _requireAccrualIdle();
        BridgeFundingLib.bootstrap(_storage(), maxFacilities);
    }

    /// @notice Reports the complete Pending ledger and any unfinished historical bootstrap.
    /// @return ready Whether new admission and funding can use the complete ledger.
    /// @return cursor The next historical facility to inspect.
    /// @return ceiling The captured exclusive origination frontier.
    function fundingBookStatus() external view returns (bool ready, uint256 cursor, uint256 ceiling) {
        return BridgeFundingLib.status();
    }

    // -- governance -------------------------------------------------------

    /// @notice Permanently binds the reserve after the underlying token has bound that same source.
    /// @param reserve The already configured reserve proxy for this bridge's native module routes.
    function setAccrualReserve(address reserve) external onlyRole(DEFAULT_ADMIN_ROLE) {
        BridgeStorage storage $ = _storage();
        if ($.accrualReserve != address(0)) revert Bridge_AccrualAlreadyBound();
        BridgeAccrualLib.validate(reserve, address($.registry), address($.oracle));
        IAccrualExposure(reserve).requireAccrualIdle();
        $.accrualReserve = reserve;
        emit AccrualReserveSet(reserve);
    }

    /// @notice The permanent accounting source, or zero before continuous accrual is bound.
    function accrualReserve() external view returns (address) {
        return _storage().accrualReserve;
    }

    /// @notice Permanently binds the timelock-managed borrower-payout registry.
    function setBorrowerPayoutRegistry(address registry) external onlyRole(DEFAULT_ADMIN_ROLE) {
        // The library returns the bound address only to keep the delegatecall compact. Binding
        // either validates, stores and emits, or reverts; the host has no second value to check.
        BridgeMixedInterestLib.bindBorrowerPayoutRegistry(registry);
    }

    /// @notice Irreversibly enables new mixed facilities after every accounting module matches.
    function enableMixedInterest() external onlyRole(DEFAULT_ADMIN_ROLE) {
        BridgeStorage storage $ = _storage();
        address reserve = $.accrualReserve;
        if (reserve == address(0) || !IContinuousAccrual(reserve).accrualSnapshot().enabled) {
            revert Bridge_MixedInterestUnavailable();
        }
        IContinuousAccrual(reserve).requireAccrualFresh();
        IAccrualExposure(reserve).requireAccrualIdle();
        BridgeAccrualLib.activateMixed(reserve);
        BridgeMixedInterestLib.enable();
    }

    /// @notice Exact cross-module version used by activation and downgrade checks.
    function mixedInterestVersion() external pure returns (bytes32) {
        return _MIXED_INTEREST_VERSION;
    }

    function mixedInterestEnabled() external view returns (bool) {
        return BridgeMixedInterestLib.enabled();
    }

    /// @notice Stages the current next id's encoded common and leg terms for attester review.
    /// @dev `encoded` is `abi.encode(OriginationTerms, InterestLegTerms)`. No facility or exposure
    ///      exists until the ordinary `originate` call presents the exact common terms.
    function prepareMixedOrigination(bytes calldata encoded)
        external
        onlyRole(Roles.ORIGINATOR_ROLE)
        whenNotPaused
        nonReentrant
        returns (uint256 tokenId, bytes32 termsHash)
    {
        _requireAccrualFresh();
        tokenId = _storage().nextId;
        termsHash = BridgeMixedInterestLib.stageOrigination(tokenId, encoded);
        emit MixedInterestOriginationPrepared(tokenId, termsHash);
    }

    function cancelPreparedMixedOrigination() external onlyRole(Roles.ORIGINATOR_ROLE) nonReentrant {
        _requireAccrualIdle();
        uint256 tokenId = _storage().nextId;
        BridgeMixedInterestLib.clearPreparedOrigination(tokenId);
        emit MixedInterestOriginationCancelled(tokenId);
    }

    /// @notice Stages both prospective leg schedules for exact attester review.
    /// @dev `encoded` is `abi.encode(Amendment, InterestLegTerms)`. Staging alone does not
    ///      checkpoint, amend or otherwise change a live facility.
    function prepareMixedAmendment(uint256 tokenId, bytes32 amendmentId, bytes calldata encoded)
        external
        onlyRole(Roles.ORIGINATOR_ROLE)
        whenNotPaused
        nonReentrant
        returns (bytes32 termsHash)
    {
        _requireAccrualFresh();
        Facility storage f = _facility(_storage(), tokenId);
        if (!BridgeMixedInterestLib.configured(tokenId)) revert Bridge_MixedLifecycleRequired(tokenId);
        if (f.state != LoanState.Active && f.state != LoanState.Amortizing) revert Bridge_BadFacility();
        if (amendmentId == bytes32(0)) revert Bridge_BadFacility();
        termsHash = BridgeMixedInterestLib.stageAmendment(tokenId, amendmentId, encoded);
        emit MixedInterestAmendmentPrepared(tokenId, amendmentId, termsHash);
    }

    /// @notice Sets the attestation kinds required to mint a facility of `classId`
    ///         (bitmask over AttestationKind). Timelocked governance only.
    /// @dev AUDIT FIX (PM-R-09). Previously ANY `uint256` was stored, while `originate` only ever
    ///      reads bits `0..KIND_COUNT-1`. A mask carrying a high bit therefore READ stricter than
    ///      it behaved - the silent fail-open class this protocol has been bitten by before. Two
    ///      rejections now, both fail-loud:
    ///        - bits outside the known `AttestationKind` range: a governance typo can no longer
    ///          silently widen the mint gate;
    ///        - an EMPTY mask: a zero gate makes the section 1.3 "NFT mint gate" invariant vacuous for
    ///          that class (a facility could mint with NO attested off-chain fact at all).
    ///          `Validate.s.sol` already asserts every class's gate is non-zero; this makes the
    ///          contract enforce what validation merely checked after the fact.
    ///
    ///      AUDIT FIX (H-4): a mask omitting `CreditIssued` is now rejected as well. `originate`
    ///      binds the facility's TERMS to the `CreditIssued` payload unconditionally, so a class
    ///      whose declared gate omitted that bit would read weaker than it behaves - and, before
    ///      the binding existed, such a class (the digital-assets class) had NO attested amount
    ///      or counterparty at all.
    /// @param classId The collateral class.
    /// @param kindsMask Bitmask over `AttestationKind`; must be within `KINDS_MASK_ALL` and
    ///        must include the `CreditIssued` bit.
    function setRequiredMintAttestations(uint256 classId, uint256 kindsMask) external onlyRole(DEFAULT_ADMIN_ROLE) {
        _requireAccrualIdle();
        if (kindsMask & ~KINDS_MASK_ALL != 0 || kindsMask & BIT_CREDIT_ISSUED == 0) {
            revert Bridge_BadAttestationMask(kindsMask);
        }
        _storage().requiredMintAttestations[classId] = kindsMask;
        emit RequiredAttestationsSet(classId, kindsMask);
    }

    // -- origination (THE synchronized mint gate) -------------------------

    /// @notice Mints the position NFT for an underwritten facility - ONLY if every
    ///         off-chain condition (required attestations, with every deal-identity quorum
    ///         committing to EXACTLY these terms) AND on-chain condition (class params,
    ///         LTV, maturity, concentration) holds. Escrow releases off-chain only after
    ///         this token exists.
    /// @dev AUDIT FIX (H-4) - FULL PAYLOAD BINDING. The gate previously proved only that
    ///      attestations EXISTED at the facility id it was about to mint; it never proved
    ///      they attested to the facility's TERMS. Two consequences, both measured:
    ///        - SEQUENCE DESYNC: `nextId` only advances on a SUCCESSFUL mint, so a reverted
    ///          or reordered origination left a fully-attested bundle sitting at the id the
    ///          next call would read. A completely unattested borrower could then originate
    ///          against another obligor's attestations (and, for a marked-to-market class,
    ///          against another obligor's appraisal).
    ///        - UNBOUNDED PRINCIPAL: for the four Receivable classes nothing on-chain bound
    ///          the amount at all - `ltvBps <= maxLtvBps` is a ratio with no denominator -
    ///          so a bundle diligenced for a $500k receivable could mint any principal.
    ///      Both close by requiring the deal-identity payloads to equal
    ///      `creditTermsHash(...)` over the exact terms being minted. `Valuation` is excluded
    ///      because its payload is the mark. This reuses the
    ///      `latestPayload` primitive already used by the attestation consumers. Note the attested principal IS the on-chain principal bound:
    ///      the amount is now a signed term, not an originator-chosen input, so the LTV
    ///      ratio's denominator (`principal * BPS / ltvBps`) is attested too.
    /// @param holder Custody address for the position (SPV series custodian).
    /// @param terms Complete contractual and operational facility terms.
    /// @return tokenId The minted facility id.
    function originate(address holder, OriginationTerms calldata terms)
        external
        onlyRole(Roles.ORIGINATOR_ROLE)
        whenNotPaused
        nonReentrant
        returns (uint256 tokenId)
    {
        _requireAccrualFresh();
        Facility memory f = _facilityFrom(terms);
        BridgeStorage storage $ = _storage();
        bytes32 termsHash = BridgeMixedInterestLib.commitment($.nextId);
        if (termsHash == bytes32(0)) termsHash = keccak256(abi.encode(terms));
        else termsHash = BridgeMixedInterestLib.preparedOrigination($.nextId, abi.encode(terms));
        return _originate(holder, f, termsHash);
    }

    /// @dev The external ABI deliberately exposes each signed term separately. Packing them
    ///      into the already-storage-compatible `Facility` shape here keeps the gate below
    ///      Solidity's stack limit without weakening or duplicating any validation.
    function _originate(address holder, Facility memory f, bytes32 termsHash) private returns (uint256 tokenId) {
        BridgeStorage storage $ = _storage();
        BridgeFundingLib.requireReady();
        bool mixed = BridgeMixedInterestLib.configured($.nextId);
        if (holder == address(0)) revert Bridge_ZeroAddress();
        // Facility defaults and protocol custody incidents share SGrove's uint256 event key.
        // Confining sequential facility ids to the lower half makes the upper incident namespace
        // structurally disjoint without changing any existing id or increment semantics.
        if (!LossEventIds.isFacilityEvent($.nextId)) {
            revert Bridge_FacilityEventNamespaceExhausted($.nextId);
        }
        if (
            // State concentration is meaningful for tax-credit facilities only. A tax-credit
            // origination must carry a state key; every other class must carry none, or the
            // registry's state dimension is either bypassed or polluted by an unrelated class.
            // THE SCHEDULE MUST CONTAIN AT LEAST ONE WHOLE INTERVAL BEFORE ITS FIRST PAYMENT.
            // `WaterfallEngine.fund` anchors the PIK cursor at `nextPaymentDue - paymentInterval`
            // so the capitalisation clock and the payment schedule agree by construction; with
            // an interval longer than the first due date that subtraction underflows and `fund`
            // reverts with a bare `Panic(0x11)`, stranding a fully attested facility in `Pending`
            // with no diagnostic. The cursor write is unconditional, so a CASH-PAY facility was
            // bricked by it too. Rejecting the terms here fails closed at the earliest point
            // instead, and every legitimate schedule already satisfies it: `nextPaymentDue` is an
            // absolute timestamp and `paymentInterval` a duration.
            f.principal == 0 || f.borrowerId == bytes32(0) || f.fundingRecipient == address(0) || f.interestRateBps == 0
                || f.interestRateBps > MAX_INTEREST_RATE_BPS || f.paymentInterval == 0
                || (!mixed && f.paymentInterval > f.nextPaymentDue) || f.paymentScheduleHash == bytes32(0)
                || f.offchainRef == bytes32(0)
                || ((f.classId == Config.CLASS_FILM_TAX_CREDITS) == (f.stateId == bytes32(0)))
        ) revert Bridge_BadFacility();

        // The returned `true` keeps the linked delegatecall free of solc's codeless-target guard.
        // Admission depends on the call completing; every refusal reverts with the recipient.
        BridgeMixedInterestLib.requireFundingRecipientAllowed(f.fundingRecipient);

        // -- on-chain conditions -------------------------------------------
        ICollateralRegistry.ClassParams memory p = $.registry.classParams(f.classId);
        if (f.ltvBps == 0 || f.ltvBps > p.maxLtvBps) revert Bridge_BadFacility();
        if (f.maturity <= block.timestamp || f.maturity > block.timestamp + p.maxMaturity) {
            revert Bridge_BadFacility();
        }
        if (f.nextPaymentDue <= block.timestamp || f.nextPaymentDue > f.maturity) revert Bridge_BadFacility();
        if (f.rateType == RateType.Variable && f.rateIndexRef == bytes32(0)) revert Bridge_BadFacility();
        if (f.rateType == RateType.Fixed && f.rateIndexRef != bytes32(0)) revert Bridge_BadFacility();
        if (f.renewable != (f.renewalTermsHash != bytes32(0))) revert Bridge_BadFacility();
        // PIK ONLY SERVICES FIXED / ACTUAL-360, SO REFUSE THE COMBINATION AT THE DOOR.
        // `WaterfallEngine._planPik` reverts `Waterfall_PikRateTypeUnsupported` and
        // `Waterfall_PikDayCountUnsupported` for anything else, and `capitalizePik` is the ONLY
        // writer of `nextPaymentDue` for a PIK facility. Without this check a PIK facility could be
        // created, or amended into, a shape whose crank can never run: the schedule would stop
        // advancing immediately and the borrower would become permissionlessly markable past due,
        // for a term combination the PROTOCOL has not implemented rather than anything they did.
        //
        // `pik` is set once at origination and `Amendment` deliberately does not carry it, so the
        // two sides of this check can never be amended apart. Added 2026-09-10 after an adversarial
        // round found the resulting freeze as the SEVENTH member of the PIK liveness family; the
        // sheltering half of the fix is in `WaterfallEngine.pikCrankBlockedByProtocol`, and this is
        // the half that stops the state arising at all.
        if (f.pik && (f.rateType != RateType.Fixed || f.dayCountConvention != DayCountConvention.Actual360)) {
            revert Bridge_BadFacility();
        }
        // AND THE THIRD SCOPE CONDITION, WHICH THE FIRST VERSION OF THIS GATE MISSED. `_planPik`
        // enforces THREE things, not two: Fixed, Actual-360, and a RECEIVABLE class. Gating only
        // the first two let a PIK facility be originated and FUNDED into a marked-to-market class,
        // where it could then take interest in neither form: every `capitalizePik` reverts
        // `Waterfall_PikClassNotReceivable`, and `distribute` refuses any PIK facility carrying an
        // interest leg. A funded loan that can never earn or receive a wei, with nothing anywhere
        // saying so. `CLASS_DIGITAL_ASSETS` is MarkedToMarket and active on this instance too, so
        // this was reachable rather than theoretical, and it CANNOT be repaired afterwards: `pik`
        // is written once at origination and the class is not amendable. Found by an adversarial
        // round 2026-09-10, measured on a 500,000e18 digital-asset facility.
        if (f.pik && p.model != ICollateralRegistry.CollateralModel.Receivable) revert Bridge_BadFacility();

        // -- off-chain conditions: required attestations, all satisfied NOW -
        // AUDIT FIX (P-32): every deal-identity attestation is bound to the same terms hash.
        // Valuation is deliberately excluded: its payload is the mark, not a deal identity.
        BridgeFundingLib.requireMintAttestations($, f.classId, $.nextId, termsHash);

        // -- marked-to-market extension (ADR-0015): fresh mark, value-bounded draw -
        if (p.model == ICollateralRegistry.CollateralModel.MarkedToMarket) {
            (uint256 value, uint64 asOf) = $.oracle.latestValuation($.nextId);
            if (asOf == 0 || block.timestamp - asOf > p.maxMarkAge) {
                revert Bridge_ValuationStale(0, asOf, p.maxMarkAge);
            }
            uint256 maxByValue = value * f.ltvBps / Config.BPS;
            if (f.principal > maxByValue) revert Bridge_LtvExceedsValue(f.principal, maxByValue);
        }

        // -- concentration: enforced atomically in the registry ------------
        $.registry.recordExposureIncrease(f.classId, f.borrowerId, f.stateId, f.principal);

        tokenId = $.nextId++;
        $.facilities[tokenId] = f;
        BridgeFundingLib.addPending($, tokenId);
        _safeMint(holder, tokenId);
        emit Originated(tokenId, f.classId, f.borrowerId, termsHash);
    }

    /// @notice Re-validates that a PENDING facility still satisfies its origination gate
    ///         immediately before funding (AUDIT FIX M-01). Origination checks are
    ///         point-in-time; a facility can sit pending while state decays. This re-runs
    ///         the time-sensitive gates - class still active, maturity and the first payment
    ///         due date not passed, every required attestation STILL satisfied (a revoked one
    ///         now blocks funding), and
    ///         for a marked-to-market class the mark still fresh and the draw still within
    ///         the value bound - so capital never deploys against stale/expired state.
    ///         Reverts on the first failure; `WaterfallEngine.fund` calls it before deploying.
    /// @dev AUDIT FIX (H-4): re-runs the TERMS BINDING too, against the terms actually stored on
    ///      the token. Fixing only `originate` would leave the funding path open - this function
    ///      repeated the same existence-only read, so a facility whose `CreditIssued` quorum was
    ///      revoked and re-attested to different terms could still draw capital.
    /// @param tokenId The pending facility about to be funded.
    function checkFundable(uint256 tokenId) external view {
        _requireAccrualFresh();
        BridgeFundingLib.checkFundable(_storage(), tokenId);
    }

    /// @notice Retires a PENDING facility that will never be funded (AUDIT FIX M-02):
    ///         atomically reverses its recorded book exposure and burns the position NFT,
    ///         so an abandoned or erroneous origination cannot permanently consume
    ///         class/borrower/state/total concentration headroom. Pending only - a funded
    ///         facility must run its lifecycle. Originator-gated (symmetric with mint).
    function cancelPending(uint256 tokenId) external onlyRole(Roles.ORIGINATOR_ROLE) nonReentrant {
        _requireAccrualIdle();
        BridgeStorage storage $ = _storage();
        Facility storage f = _facility($, tokenId);
        if (f.state != LoanState.Pending) revert Bridge_NotPending(tokenId);
        BridgeFundingLib.removePending($, tokenId);
        // release exposure BEFORE burning: same-tx reversal keeps the concentration book
        // and the NFT set describing the same reality (registry decrease is CREDIT_ROLE,
        // which the bridge already holds for origination's increase).
        $.registry.recordExposureDecrease(f.classId, f.borrowerId, f.stateId, f.principal);
        f.state = LoanState.Cancelled;
        emit StateChanged(tokenId, LoanState.Pending, LoanState.Cancelled);
        _burn(tokenId);
    }

    // -- lifecycle state machine ------------------------------------------

    /// @notice Advances a facility's lifecycle. Only the credit layer (CREDIT_ROLE -
    ///         WaterfallEngine/DefaultManager in Phase E). Transitions are a strict
    ///         guarded machine; anything else reverts.
    function transitionState(uint256 tokenId, LoanState to) external onlyRole(Roles.CREDIT_ROLE) nonReentrant {
        _requireAccrualIdle();
        BridgeStorage storage $ = _storage();
        Facility storage f = _facility($, tokenId);
        LoanState from = f.state;
        bool ok = (from == LoanState.Pending && to == LoanState.Active)
            || (from == LoanState.Active && to == LoanState.Amortizing)
            || ((from == LoanState.Active || from == LoanState.Amortizing) && to == LoanState.Repaid)
            || ((from == LoanState.Active || from == LoanState.Amortizing) && to == LoanState.Defaulted)
            || (from == LoanState.Defaulted && to == LoanState.Accelerated)
        // AUDIT FIX (M-03): a defaulted/accelerated facility that recovers its full
        // outstanding principal closes out to Resolved and unfreezes the position.
        || ((from == LoanState.Defaulted || from == LoanState.Accelerated) && to == LoanState.Resolved);
        if (!ok) revert Bridge_InvalidTransition(tokenId, from, to);
        if (from == LoanState.Pending) {
            BridgeFundingLib.requireReady();
            BridgeFundingLib.removePending($, tokenId);
        }
        f.state = to;
        emit StateChanged(tokenId, from, to);
    }

    /// @notice Whether a credit operation can presently update the bridge's guarded schedule.
    /// @dev A temporary operation lock is not evidence that a borrower missed a payment.
    function creditOperationIdle() external view returns (bool) {
        return !_reentrancyGuardEntered();
    }

    /// @notice Advances the due date after an exact, attested payment.
    function setNextPaymentDue(uint256 tokenId, uint64 nextDue) external onlyRole(Roles.CREDIT_ROLE) nonReentrant {
        _requireAccrualIdle();
        BridgeMixedInterestLib.setCashDue(tokenId, nextDue);
    }

    /// @notice Invalidates signed amendments before the bound servicing operation makes external calls.
    /// @dev A failed receipt rolls this advance back atomically. This adds no pause gate to repayment.
    /// @param tokenId Known facility whose trusted credit module is processing a receipt.
    function recordServicingReceipt(uint256 tokenId) external onlyRole(Roles.CREDIT_ROLE) nonReentrant {
        _requireAccrualIdle();
        _facility(_storage(), tokenId);
        BridgeMixedInterestLib.advanceServicingState(tokenId);
    }

    /// @inheritdoc IAccrualBridge
    /// @dev This reserve-only continuation runs during bounded keeper accounting. It deliberately
    ///      has no source-idle or freshness gate; it cannot amend terms, invent a maturity extension,
    ///      alter cash due dates or accept the coordinator's terminal zero sentinel.
    function setAccruedPaymentDue(uint256 tokenId, uint64 nextDue) external {
        BridgeMixedInterestLib.setPikDue(tokenId, nextDue);
    }

    /// @notice Applies a quorum-attested servicing amendment or renewal.
    function amendTerms(uint256 tokenId, bytes32 amendmentId, Amendment calldata a)
        external
        onlyRole(Roles.ORIGINATOR_ROLE)
        whenNotPaused
        nonReentrant
    {
        _requireAccrualFresh();
        BridgeMixedInterestLib.amendTerms(tokenId, amendmentId, abi.encode(a));
    }

    // -- views ------------------------------------------------------------

    /// @notice Full facility record (reverts for unknown tokens).
    function facility(uint256 tokenId) external view returns (Facility memory) {
        return _facility(_storage(), tokenId);
    }

    /// @notice Version of the accepted servicing history; never inferred from wall-clock time.
    /// @param tokenId Known facility to query.
    /// @return Current receipt/amendment generation, starting at zero for existing facilities.
    function servicingNonce(uint256 tokenId) external view returns (uint256) {
        BridgeStorage storage $ = _storage();
        _facility($, tokenId);
        return $.servicingNonce[tokenId];
    }

    /// @notice Current one-leg amendment payload, including the standing terms and servicing version.
    /// @dev Obtain this before signing. Any intervening payment or amendment requires a fresh payload.
    /// @param tokenId Known one-leg facility to amend.
    /// @param amendmentId Identity of the proposed amendment.
    /// @param a Exact prospective terms to be attested.
    /// @return Payload for the existing TermsAmended quorum attestation.
    function amendmentTermsHash(uint256 tokenId, bytes32 amendmentId, Amendment calldata a)
        external
        view
        returns (bytes32)
    {
        _facility(_storage(), tokenId);
        if (BridgeMixedInterestLib.configured(tokenId)) revert Bridge_MixedLifecycleRequired(tokenId);
        return BridgeMixedInterestLib.singleAmendmentHash(tokenId, amendmentId, abi.encode(a));
    }

    /// @notice Current two-leg amendment payload; the matching plan must still be staged before use.
    /// @param tokenId Known mixed-interest facility to amend.
    /// @param amendmentId Identity of the proposed amendment.
    /// @param encoded ABI-encoded Amendment and InterestLegTerms tuple.
    /// @return Payload for the existing TermsAmended quorum attestation.
    function mixedAmendmentTermsHash(uint256 tokenId, bytes32 amendmentId, bytes calldata encoded)
        external
        view
        returns (bytes32)
    {
        _facility(_storage(), tokenId);
        if (!BridgeMixedInterestLib.configured(tokenId)) revert Bridge_MixedLifecycleRequired(tokenId);
        return BridgeMixedInterestLib.amendmentHash(tokenId, amendmentId, encoded);
    }

    /// @notice The `CreditIssued` payload an attester quorum must sign to authorize a facility
    ///         on EXACTLY these terms (AUDIT FIX H-4). Attester tooling and the mint gate derive
    ///         the commitment from this one function, so they cannot drift apart.
    /// @dev The facility id is NOT in the preimage because it is the oracle record's key and is
    ///      already covered by the EIP-712 digest (`AttestationOracle.attest` hashes
    ///      `a.facilityId`). The per-facility interest rate IS in the preimage: pricing is a
    ///      signed loan term, not a collateral-class parameter.
    /// @param terms Complete contractual and operational facility terms.
    /// @return The terms commitment.
    function creditTermsHash(OriginationTerms calldata terms) external pure returns (bytes32) {
        return keccak256(abi.encode(terms));
    }

    function mixedInterestTerms(uint256 tokenId)
        external
        view
        returns (BridgeMixedInterestLib.InterestLegTerms memory)
    {
        _facility(_storage(), tokenId);
        return BridgeMixedInterestLib.terms(tokenId);
    }

    function isMixedInterest(uint256 tokenId) external view returns (bool) {
        _facility(_storage(), tokenId);
        return BridgeMixedInterestLib.configured(tokenId);
    }

    function _facilityFrom(OriginationTerms calldata terms) private pure returns (Facility memory f) {
        f.classId = terms.classId;
        f.borrowerId = terms.borrowerId;
        f.stateId = terms.stateId;
        f.principal = terms.principal;
        f.ltvBps = terms.ltvBps;
        f.interestRateBps = terms.interestRateBps;
        f.maturity = terms.maturity;
        f.fundingRecipient = terms.fundingRecipient;
        f.paymentInterval = terms.paymentInterval;
        f.nextPaymentDue = terms.nextPaymentDue;
        f.rateType = terms.rateType;
        f.dayCountConvention = terms.dayCountConvention;
        f.renewable = terms.renewable;
        f.paymentScheduleHash = terms.paymentScheduleHash;
        f.rateIndexRef = terms.rateIndexRef;
        f.renewalTermsHash = terms.renewalTermsHash;
        f.offchainRef = terms.offchainRef;
        f.pik = terms.pik;
        f.state = LoanState.Pending;
    }

    /// @notice Required mint-attestation mask for a class.
    function requiredMintAttestations(uint256 classId) external view returns (uint256) {
        return _storage().requiredMintAttestations[classId];
    }

    /// @notice Wired module addresses (post-deploy validation aid).
    function modules() external view returns (address registry, address oracle) {
        BridgeStorage storage $ = _storage();
        return (address($.registry), address($.oracle));
    }

    /// @notice Total facilities ever originated.
    function totalOriginated() external view returns (uint256) {
        return _storage().nextId - 1;
    }

    // -- guardian ---------------------------------------------------------

    /// @notice Pauses origination. Emergency use only.
    function pause() external onlyRole(Roles.GUARDIAN_ROLE) {
        _requireAccrualIdle();
        _pause();
    }

    /// @notice Unpauses origination.
    function unpause() external onlyRole(Roles.GUARDIAN_ROLE) {
        _requireAccrualIdle();
        _unpause();
    }

    // -- internals --------------------------------------------------------

    /// @dev Transfer restriction: positions move only under governance execution
    ///      (custody changes are legal events), and NEVER while frozen
    ///      (Defaulted/Accelerated) - the on-chain half of the dual-record freeze.
    function _update(address to, uint256 tokenId, address auth) internal override returns (address from) {
        _requireAccrualIdle();
        BridgeStorage storage $ = _storage();
        address owner = _ownerOf(tokenId);
        if (owner != address(0)) {
            LoanState st = $.facilities[tokenId].state;
            if (st == LoanState.Defaulted || st == LoanState.Accelerated) revert Bridge_PositionFrozen(tokenId);
            if (to != address(0) && !hasRole(DEFAULT_ADMIN_ROLE, msg.sender)) revert Bridge_TransferRestricted();
        }
        return super._update(to, tokenId, auth);
    }

    /// @dev AUDIT FIX (P-32). Requires every selected mint-gate attestation to be currently
    ///      satisfied. AssignmentExecuted, UCCFiled and CreditIssued are deal identity facts and
    ///      must carry the exact `creditTermsHash`; Valuation is intentionally left on its own mark
    ///      payload and checked by the marked-to-market branch.
    function _facility(BridgeStorage storage $, uint256 tokenId) private view returns (Facility storage f) {
        if (tokenId == 0 || tokenId >= $.nextId) revert Bridge_UnknownToken(tokenId);
        f = $.facilities[tokenId];
    }

    function supportsInterface(bytes4 interfaceId)
        public
        view
        override(ERC721Upgradeable, AccessControlUpgradeable)
        returns (bool)
    {
        return super.supportsInterface(interfaceId);
    }

    /// @dev Token approvals cannot change during a source accounting or delivery callback.
    function _approve(address to, uint256 tokenId, address auth, bool emitEvent) internal override {
        _requireAccrualIdle();
        super._approve(to, tokenId, auth, emitEvent);
    }

    /// @dev Operator approvals share the same callback boundary as ownership changes.
    function _setApprovalForAll(address owner, address operator, bool approved) internal override {
        _requireAccrualIdle();
        super._setApprovalForAll(owner, operator, approved);
    }

    /// @dev Includes initial grants before binding and governed grants afterwards.
    function _grantRole(bytes32 role, address account) internal override returns (bool) {
        _requireAccrualIdle();
        return super._grantRole(role, account);
    }

    /// @dev Includes revocation and a holder's own role renunciation.
    function _revokeRole(bytes32 role, address account) internal override returns (bool) {
        _requireAccrualIdle();
        return super._revokeRole(role, account);
    }

    /// @dev An upgrade cannot replace lifecycle accounting during a protected source operation.
    function _authorizeUpgrade(address implementation) internal view override onlyRole(Roles.UPGRADER_ROLE) {
        _requireAccrualIdle();
        if (BridgeMixedInterestLib.enabled()) BridgeAccrualLib.validateMixedImplementation(implementation);
    }

    /// @dev Admissions and prospective economic amendments require the authoritative current book.
    function _requireAccrualFresh() private view {
        address reserve = _storage().accrualReserve;
        if (reserve != address(0)) IContinuousAccrual(reserve).requireAccrualFresh();
    }

    /// @dev Recovery, governance and custody changes need an idle source, independent of keeper lag.
    function _requireAccrualIdle() private view {
        address reserve = _storage().accrualReserve;
        if (reserve != address(0)) IAccrualExposure(reserve).requireAccrualIdle();
    }

    function _storage() private pure returns (BridgeStorage storage $) {
        assembly {
            $.slot := BRIDGE_STORAGE_LOCATION
        }
    }
}
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.