Skip to content
Verified contractExactBUSL-1.1

BridgeFundingLib

Address0x7eb38a79ae1ffc9173faa91d04a853b29670a2bf
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,367
Creation transaction
0x0a8b2f686c…2e0c3c49d0

42 files

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

src/libraries/BridgeFundingLib.sol

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

import {IContinuousAccrual} from "../interfaces/IContinuousAccrual.sol";
import {BridgeMixedInterestLib} from "./BridgeMixedInterestLib.sol";
import {Config} from "./Config.sol";
import {ClaimBridge} from "../ClaimBridge.sol";
import {IAttestationOracle} from "../interfaces/IAttestationOracle.sol";
import {ICollateralRegistry} from "../interfaces/ICollateralRegistry.sol";

/// @title BridgeFundingLib
/// @notice Complete Pending accounting and common attestation checks for funding admission.
/// @dev Linked calls execute in ClaimBridge's context. All authority remains on the host.
library BridgeFundingLib {
    /// @custom:storage-location erc7201:forestroad.storage.BridgeFunding
    struct State {
        uint256 total;
        mapping(uint256 classId => uint256) classes;
        mapping(bytes32 borrowerId => uint256) borrowers;
        mapping(bytes32 stateId => uint256) states;
        mapping(uint256 tokenId => bool) counted;
        uint256 cursor;
        uint256 ceiling;
        bool ready;
    }

    bytes32 private constant FUNDING_STORAGE_LOCATION =
        0xd3b8b20c0d084aa1204c145c498883d4da6ccda05e357b8e6c98fa3818193000;
    uint256 private constant KIND_COUNT = uint256(IAttestationOracle.AttestationKind.TermsAmended) + 1;
    uint256 private constant BIT_CREDIT_ISSUED = 1 << uint256(IAttestationOracle.AttestationKind.CreditIssued);

    function _state() private pure returns (State storage $) {
        assembly ("memory-safe") {
            $.slot := FUNDING_STORAGE_LOCATION
        }
    }

    /// @notice Starts an empty book during the host's fresh proxy initialization.
    /// @dev Never exposed as a callable initialization function on the host.
    function initialize() public {
        State storage s = _state();
        s.cursor = 1;
        s.ceiling = 1;
        s.ready = true;
    }

    /// @notice Requires the complete Pending prefix before admission or funding.
    function requireReady() public view {
        State storage s = _state();
        if (!s.ready) revert ClaimBridge.Bridge_FundingBookUnavailable(s.cursor, s.ceiling);
    }

    /// @notice Reports the bounded upgrade bootstrap, or the ready fresh-deployment state.
    /// @return ready Whether every historical facility has been classified.
    /// @return cursor The next historical facility to inspect.
    /// @return ceiling The captured exclusive origination frontier.
    function status() public view returns (bool ready, uint256 cursor, uint256 ceiling) {
        State storage s = _state();
        return (s.ready, s.cursor, s.ceiling);
    }

    /// @notice Classifies a bounded historical prefix after upgrading an existing proxy.
    /// @dev New originations and funding stay closed until completion. Cancellation remains
    ///      possible: an already counted cancellation subtracts once; an unscanned cancellation
    ///      is skipped when reached. No caller supplies balances or identities.
    /// @param $ The bridge's existing immutable facility records.
    /// @param limit Maximum records to inspect; must be between one and 100.
    function bootstrap(ClaimBridge.BridgeStorage storage $, uint256 limit) public {
        if (limit == 0 || limit > 100) revert ClaimBridge.Bridge_BadFundingBatch(limit);
        if ($.nextId == 0) revert ClaimBridge.Bridge_FundingBookUnavailable(0, 0);
        State storage s = _state();
        if (s.ready) return;
        if (s.ceiling == 0) {
            s.cursor = 1;
            s.ceiling = $.nextId;
        }
        uint256 remaining = s.ceiling - s.cursor;
        uint256 stop = s.cursor + (remaining < limit ? remaining : limit);
        for (uint256 id = s.cursor; id < stop; ++id) {
            if ($.facilities[id].state == ClaimBridge.LoanState.Pending) _record(s, $.facilities[id], id);
        }
        s.cursor = stop;
        s.ready = stop == s.ceiling;
        emit ClaimBridge.FundingBookBootstrapProgress(stop, s.ceiling, s.total, s.ready);
    }

    /// @notice Adds the newly recorded Pending facility before the NFT receiver callback.
    /// @param $ The bridge's facility records.
    /// @param id The new facility.
    function addPending(ClaimBridge.BridgeStorage storage $, uint256 id) public {
        requireReady();
        _record(_state(), $.facilities[id], id);
    }

    /// @notice Removes a cancelled or funded Pending row exactly once.
    /// @param $ The bridge's facility records before their state transition.
    /// @param id The departing Pending facility.
    function removePending(ClaimBridge.BridgeStorage storage $, uint256 id) public {
        State storage s = _state();
        if (!s.counted[id]) {
            if (!s.ready) return;
            revert ClaimBridge.Bridge_PendingFundingMismatch(id);
        }
        ClaimBridge.Facility storage f = $.facilities[id];
        uint256 amount = f.principal;
        s.total -= amount;
        s.classes[f.classId] -= amount;
        s.borrowers[f.borrowerId] -= amount;
        if (f.stateId != bytes32(0)) s.states[f.stateId] -= amount;
        delete s.counted[id];
    }

    /// @notice Rechecks funding against funded exposure plus this exact Pending facility.
    /// @param $ The bridge's authenticated registry and facility records.
    /// @param id The Pending facility about to receive capital.
    function checkFunding(ClaimBridge.BridgeStorage storage $, uint256 id) internal view {
        requireReady();
        State storage s = _state();
        if (!s.counted[id]) revert ClaimBridge.Bridge_PendingFundingMismatch(id);
        ClaimBridge.Facility storage f = $.facilities[id];
        ICollateralRegistry.PendingExposure memory pending = ICollateralRegistry.PendingExposure({
            total: s.total,
            classAmount: s.classes[f.classId],
            borrowerAmount: s.borrowers[f.borrowerId],
            stateAmount: f.stateId == bytes32(0) ? 0 : s.states[f.stateId]
        });
        $.registry.checkFundingConcentration(f.classId, f.borrowerId, f.stateId, f.principal, pending);
    }

    function _record(State storage s, ClaimBridge.Facility storage f, uint256 id) private {
        if (s.counted[id]) revert ClaimBridge.Bridge_PendingFundingMismatch(id);
        s.total += f.principal;
        s.classes[f.classId] += f.principal;
        s.borrowers[f.borrowerId] += f.principal;
        if (f.stateId != bytes32(0)) s.states[f.stateId] += f.principal;
        s.counted[id] = true;
    }

    /// @notice Verifies every required documentary fact and its exact signed terms binding.
    /// @dev Preserves the existing missing-fact-before-payload error precedence and mint-kind mask.
    /// @param $ The bridge's configured oracle and class masks.
    /// @param classId The authenticated collateral class.
    /// @param facilityId The facility whose facts must be current.
    /// @param termsHash The complete stored or staged signed terms commitment.
    function requireMintAttestations(
        ClaimBridge.BridgeStorage storage $,
        uint256 classId,
        uint256 facilityId,
        bytes32 termsHash
    ) public view {
        uint256 mask = $.requiredMintAttestations[classId];
        // An unset class must satisfy the same mandatory gate as a configured class.
        if (mask & BIT_CREDIT_ISSUED == 0) revert ClaimBridge.Bridge_BadAttestationMask(mask);
        // Preserve the original missing-attestation precedence: a present bit is checked before
        // any payload comparison, so a genuinely absent documentary fact remains
        // `Bridge_AttestationMissing` rather than looking like a malformed commitment.
        for (uint256 k = 0; k < KIND_COUNT; ++k) {
            if (mask & (1 << k) == 0) continue;
            IAttestationOracle.AttestationKind kind = IAttestationOracle.AttestationKind(uint8(k));
            (,, bool ok) = $.oracle.latestPayload(facilityId, kind);
            if (!ok) revert ClaimBridge.Bridge_AttestationMissing(classId, kind);
        }

        // ORDER IS LOAD-BEARING BELOW THIS LINE. DO NOT REORDER, AND DO NOT NARROW THE LOOP ABOVE.
        //
        // Both remaining `latestPayload` reads in this function DISCARD the `ok` flag, and that is
        // safe ONLY because of what the loop above has already done: it reverts
        // `Bridge_AttestationMissing` for EVERY bit set in `mask`, over the same
        // `0..KIND_COUNT-1` range these two reads are gated on, and this function is `view` so the
        // oracle cannot change underneath them. Under those three conditions a dropped `ok` cannot
        // hide an absent attestation, because an absent one has already reverted.
        //
        // Reorder these blocks above the loop, narrow the loop's range or its mask, or make this
        // function non-view, and BOTH reads below become real defects: a missing attestation would
        // read as `payload == bytes32(0)` and be compared against `termsHash` rather than refused.
        // Recorded 2026-09-10 during the first Slither triage on this tree, which dispositioned
        // these two `unused-return` findings as safe on exactly this reasoning. A property that
        // holds by ordering has to be stated where someone would break it.
        //
        // Check the existing terms-quorum limb first to preserve H-4's established error surface.
        // Documentary payloads are then checked below; P-32 adds those checks without changing the
        // diagnostics callers already receive for a mismatched CreditIssued bundle.
        if (mask & BIT_CREDIT_ISSUED != 0) {
            (bytes32 payload,,) = $.oracle.latestPayload(facilityId, IAttestationOracle.AttestationKind.CreditIssued);
            if (payload != termsHash) {
                revert ClaimBridge.Bridge_TermsNotAttested(facilityId, termsHash, payload);
            }
        }

        for (uint256 k = 0; k < KIND_COUNT; ++k) {
            if (mask & (1 << k) == 0) continue;
            IAttestationOracle.AttestationKind kind = IAttestationOracle.AttestationKind(uint8(k));
            if (_isDealIdentityKind(kind) && kind != IAttestationOracle.AttestationKind.CreditIssued) {
                (bytes32 payload,,) = $.oracle.latestPayload(facilityId, kind);
                if (payload != termsHash) {
                    revert ClaimBridge.Bridge_AttestationNotBoundToDeal(classId, kind, termsHash, payload);
                }
            }
        }
    }

    function _isDealIdentityKind(IAttestationOracle.AttestationKind kind) private pure returns (bool) {
        return kind == IAttestationOracle.AttestationKind.AssignmentExecuted
            || kind == IAttestationOracle.AttestationKind.UCCFiled
            || kind == IAttestationOracle.AttestationKind.CreditIssued;
    }
    /// @notice Revalidates the complete existing funding gate and the funded-only concentration book.
    /// @dev The host checks accrual freshness before entering this view. Time, class, terms,
    ///      documentary and valuation error precedence is preserved.
    /// @param $ The bridge's existing authenticated storage.
    /// @param tokenId The Pending facility about to be funded.

    function checkFundable(ClaimBridge.BridgeStorage storage $, uint256 tokenId) public view {
        if (tokenId == 0 || tokenId >= $.nextId) revert ClaimBridge.Bridge_UnknownToken(tokenId);
        ClaimBridge.Facility storage f = $.facilities[tokenId];
        if (f.state != ClaimBridge.LoanState.Pending) revert ClaimBridge.Bridge_NotPending(tokenId);
        ICollateralRegistry.ClassParams memory p = $.registry.classParams(f.classId);
        if (!p.active) revert ClaimBridge.Bridge_ClassInactive(f.classId);
        if (f.maturity <= block.timestamp) revert ClaimBridge.Bridge_FacilityMatured(tokenId);
        if (f.nextPaymentDue <= block.timestamp) revert ClaimBridge.Bridge_BadFacility();
        if (_accrualEnabled($)) _requireAccrualTerms(tokenId, f.pik, f.rateType, f.dayCountConvention);

        // AUDIT FIX (P-32): re-check every deal-identity attestation against the stored terms;
        // Valuation retains its mark payload and is checked below by its own freshness/value limb.
        bytes32 expected = BridgeMixedInterestLib.commitment(tokenId);
        if (expected == bytes32(0)) expected = _creditTermsHash(f);
        requireMintAttestations($, f.classId, tokenId, expected);

        if (p.model == ICollateralRegistry.CollateralModel.MarkedToMarket) {
            (uint256 value, uint64 asOf) = $.oracle.latestValuation(tokenId);
            if (asOf == 0 || block.timestamp - asOf > p.maxMarkAge) {
                revert ClaimBridge.Bridge_ValuationStale(tokenId, asOf, p.maxMarkAge);
            }
            uint256 maxByValue = value * f.ltvBps / Config.BPS;
            if (f.principal > maxByValue) revert ClaimBridge.Bridge_LtvExceedsValue(f.principal, maxByValue);
        }
        checkFunding($, tokenId);
    }

    function _creditTermsHash(ClaimBridge.Facility memory f) private pure returns (bytes32) {
        ClaimBridge.OriginationTerms memory t = ClaimBridge.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(t));
    }

    function _accrualEnabled(ClaimBridge.BridgeStorage storage $) private view returns (bool) {
        return $.accrualReserve != address(0) && IContinuousAccrual($.accrualReserve).accrualSnapshot().enabled;
    }

    function _requireAccrualTerms(
        uint256 tokenId,
        bool pik,
        ClaimBridge.RateType rateType,
        ClaimBridge.DayCountConvention dayCount
    ) private pure {
        if (
            rateType != ClaimBridge.RateType.Fixed || dayCount == ClaimBridge.DayCountConvention.Thirty360
                || (pik && dayCount != ClaimBridge.DayCountConvention.Actual360)
        ) revert ClaimBridge.Bridge_AccrualUnsupportedTerms(tokenId);
    }
}
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.