Vault value-conservation invariant is a no-op for the entire lending flow (Version:3.2.0)
Vault value-conservation invariant is a no-op for the entire lending flow (medium). VaultInvariant.cpp:1049-1054 — ttLOAN_SET / ttLOAN_MANAGE / ttLOAN_PAY are literally // TBD → return true. Loan transactions move real vault assets and mutate sfAssetsAvailable/sfAssetsTotal, yet are exempted from ValidVault. The only "funds conserved" / "pseudo balance agrees" checks on that path are #if !NDEBUG asserts (no-ops in Release). And unlike LoanBrokerInvariant (which cross-checks its cover pool against the broker pseudo-account's real balance), no production invariant ever ties the vault's sfAssetsAvailable to the vault pseudo-account's held balance. Not a live exploit today, but the last line of defense is switched off for the most complex value flow in the system — any present-or-future loan-accounting desync commits to hashed ledger state undetected. Still // TBD on develop.
Thank you for raising this issue @YogiBearXRP .
We are aware of the missing Invariants for the Lending Protocol transactions, and are working on introducing the invariants. Stay tuned!
@Tapanito, thank you for confirming that work on the missing lending invariants is underway. We are looking to contribute here. Does the approach below parallel the solution you are developing? We would appreciate your advice on whether an external PR would be useful, which portion we should own, and how you would prefer us to coordinate before implementation.
Proposed solution
The lending cases in ValidVault::finalize() currently return true for ttLOAN_SET, ttLOAN_MANAGE, and ttLOAN_PAY. We propose replacing those no-op branches with invariants derived independently from the transactors.
The invariant should not reproduce the full loan algorithm. Duplicating payment schedules, interest calculations, fees, default calculations, and every intermediate value would create a second implementation of the same business logic. A matching defect in both implementations could then pass unnoticed. Instead, the invariant should enforce accounting identities that must hold across the committed Vault, LoanBroker, Loan, and pseudo-account state under both accrual and cash-basis accounting.
1. Bind sfAssetsAvailable to the real vault holding
For every successful transaction that modifies a vault, the posterior state should satisfy:
Vault.sfAssetsAvailable
== accountHolds(vault pseudo-account, Vault.sfAsset)
The balance should use the same semantics as ValidLoanBroker:
accountHolds(
view,
vault.pseudoId,
vault.asset,
FreezeHandling::IgnoreFreeze,
AuthHandling::IgnoreAuth,
j)
This must be a production invariant rather than an XRPL_ASSERT inside a transactor. It catches assets transferred without updating sfAssetsAvailable, field changes without transfers, transfers to the wrong pseudo-account, representable rounding discrepancies, and future transaction paths that leave the Vault object inconsistent with its actual holding.
For XRP and MPT assets, equality should be exact. For IOUs, comparison should use the canonical stored STAmount representation. We should not introduce an arbitrary epsilon.
2. Enforce a common Vault and LoanBroker delta identity
For a lending transaction, define posterior minus prior deltas:
DeltaA = Delta Vault.sfAssetsAvailable
DeltaT = Delta Vault.sfAssetsTotal
DeltaD = Delta LoanBroker.sfDebtTotal
All current lending transitions satisfy:
DeltaA = DeltaT - DeltaD
This holds under both accounting versions.
For LoanSet under accrual accounting:
DeltaA = -principal
DeltaT = recognized interest
DeltaD = principal + recognized interest
Under cash-basis accounting:
DeltaA = -principal
DeltaT = 0
DeltaD = principal
For LoanPay, the identity reduces to principal plus interest transferred to the vault. Broker fees are intentionally excluded because they are sent to the broker owner or cover pool and do not alter the vault pseudo-account balance.
For default, let E be total default exposure and C be first-loss capital transferred from the broker:
DeltaA = C
DeltaT = -(E - C)
DeltaD = -E
Therefore DeltaT - DeltaD = C = DeltaA. Impairment, unimpairement, and a valid no-op LoanManage have zero deltas for all three fields, so the same identity still holds.
This identity checks cross-object conservation without reimplementing loanOriginationDeltas(), loanPaymentDeltas(), or the full default formula.
3. Validate object cardinality and linkage
The invariant must not combine a vault delta with an unrelated loan or broker.
For ttLOAN_SET, require:
- Exactly one Vault is modified.
- Exactly one Loan is created.
- The Loan points to one LoanBroker through
sfLoanBrokerID. - The LoanBroker points to the modified Vault through
sfVaultID. - The Loan did not exist in the prior state.
- Broker and Vault identities are immutable.
For ttLOAN_PAY and non-no-op ttLOAN_MANAGE, require:
- Exactly one existing Loan is modified.
- Its
sfLoanBrokerIDis unchanged. - Its LoanBroker points to the modified Vault.
- At most one LoanBroker and one Vault participate in the accounting transition.
- No unrelated object contributes to the calculated deltas.
LoanManage without a management flag is explicitly allowed to succeed without modifying a Vault and should remain exempt from a must-modify requirement.
4. Validate sfLossUnrealized transitions
The current structural range check proves only:
0 <= sfLossUnrealized
sfLossUnrealized <= sfAssetsTotal - sfAssetsAvailable
It does not prove that the change corresponds to the affected Loan. The invariant should capture the Loan before and after the transaction and calculate pre-transition exposure using the version-aware helper:
loanVaultExposure(beforeVaultSle, beforeLoanSle)
Required transitions at the Vault's canonical scale:
- Impair:
DeltaLossUnrealized = +pre-transition exposure, with no change to available assets, total assets, or broker debt. - Unimpair:
DeltaLossUnrealized = -pre-transition exposure, with no change to those accounting fields. - Default of an impaired Loan: remove exactly the pre-default exposure from
sfLossUnrealized. - Default of an unimpaired Loan: leave
sfLossUnrealizedunchanged. - Payment of an impaired Loan:
LoanPayfirst callsunimpairLoan(), so it must clear the impaired flag and remove the pre-payment exposure. - Payment of an unimpaired Loan and
LoanSet: leavesfLossUnrealizedunchanged.
For default, the posterior Loan should also have zero principal outstanding, total value outstanding, management fee outstanding, payment remaining, and next payment due date, with the default flag set.
5. Use protocol rounding rules rather than tolerance
sfAssetsTotal, sfAssetsAvailable, sfDebtTotal, and sfLossUnrealized are Number values, and IOU fields can have different exponents. The transactors also use adjustImpreciseNumber() because a broker can own loans at different scales.
The invariant should:
- Compute deltas from the actual before and after SLEs.
- Select the canonical comparison scale using the posterior Vault scale and existing cleanup-amendment behavior.
- Use
roundToAsset()consistently. - Check the rounded residual:
roundToAsset(asset, DeltaA - (DeltaT - DeltaD), vaultScale) == 0
- Require exact equality for XRP and MPT assets.
- Reject every representable IOU discrepancy.
- Avoid percentage or absolute tolerances that could allow drift to accumulate across transactions.
The exact posterior pseudo-account balance check remains necessary. The rounded delta identity is not a substitute for binding sfAssetsAvailable to the actual holding.
6. Suggested implementation shape
We propose extending ValidVault with lightweight Loan and LoanBroker snapshots:
struct LoanSnapshot
{
uint256 key;
uint256 brokerID;
std::uint32_t flags;
Number principalOutstanding;
Number totalValueOutstanding;
Number managementFeeOutstanding;
std::uint32_t paymentRemaining;
};
struct BrokerSnapshot
{
uint256 key;
uint256 vaultID;
AccountID pseudoId;
Number debtTotal;
Number coverAvailable;
};
visitEntry() would capture before and after values for ltVAULT, ltLOAN, ltLOAN_BROKER, and the XRP, trust-line, or MPT holding associated with the vault pseudo-account.
finalize() would then:
- Run the existing universal Vault checks.
- Resolve and validate Loan to LoanBroker to Vault linkage.
- Check the posterior pseudo-account holding.
- Check
DeltaA = DeltaT - DeltaD. - Apply transaction-specific Loan state and unrealized-loss checks.
- Emit a distinct fatal diagnostic for each failed relationship.
- Return
falseso the existing invariant-failure and fee-only retry behavior handles the transaction.
Keeping this in ValidVault initially gives the smallest change because the missing transaction branches already exist there. If the implementation becomes too large, the lending portion could be extracted into a ValidLendingAccounting invariant while sharing snapshot and rounding helpers.
7. Test matrix
Happy-path and deliberately corrupted post-state tests should cover:
- XRP, IOU, and MPT vault assets.
- Legacy accrual and cash-basis Vault versions.
- IOUs at exponent and precision boundaries.
- Origination with and without interest and origination fees.
- Regular, late, full, and overpayments.
- Broker fees sent to the owner and redirected to the cover pool.
- Impair, unimpair, payment-triggered unimpair, and default.
- Zero, partial, and full first-loss coverage.
- Default of both impaired and unimpaired Loans.
- Valid no-op
LoanManage.
Injected corruption tests should prove rejection when:
sfAssetsAvailablechanges without a transfer.- A transfer occurs without changing
sfAssetsAvailable. - The pseudo-account receives one representable unit too much or too little.
sfAssetsTotalorsfDebtTotalis independently corrupted.sfLossUnrealizedis not added or removed on the required transition.- An impaired payment clears the Loan flag without clearing the loss.
- A Loan is linked to a broker associated with another Vault.
- Multiple brokers or Vaults are modified by one Loan transaction.
- A required Loan or Vault modification is missing.
- A sub-scale IOU difference is genuinely unrepresentable, while a one-unit representable discrepancy is rejected.
Each negative test should verify invariant failure and confirm that only the permitted fee effect survives.
8. Activation and compatibility
This changes transaction acceptance and is consensus sensitive. If Lending Protocol has not activated on a persistent network, these checks could be included in the initial feature implementation. Otherwise, they should be gated behind a dedicated fix amendment.
Before activation, existing Vault state should be scanned to confirm that every sfAssetsAvailable value matches the corresponding pseudo-account holding. If historical state already contains discrepancies, activation requires a deterministic repair transition or an explicit compatibility rule so affected Vaults are not stranded.
Proposed PR boundary
The first PR could implement:
- Loan and LoanBroker snapshots in
ValidVault. - Cardinality and linkage validation.
- Posterior
sfAssetsAvailableto pseudo-account balance binding. - The
DeltaA = DeltaT - DeltaDidentity. - XRP, IOU, and MPT corruption tests.
The sfLossUnrealized transition checks can be included in the same PR if that remains reviewable, or immediately afterward using the same snapshots and rounding infrastructure.
@Tapanito, does this parallel the approach your team is already taking? We would like to contribute the implementation and tests, but do not want to duplicate active work. Please let us know whether this scope is useful, whether you would prefer a smaller first PR, and which amendment or compatibility assumptions we should follow before proceeding.
@Tapanito @a1q123456 — following up on this. #7732 added the Loan/LoanBroker-side checks, but on current develop ValidVault::finalize still returns true for ttLOAN_PAY and ttLOAN_MANAGE, and ttLOAN_SET only gets the closed-vault phase gate, so in a release build nothing binds the change in sfAssetsAvailable to the vault pseudo-account's actual balance change for the lending transactions (the conservation checks in LoanPay.cpp are XRPL_ASSERTs).
I'd like to help with a narrow piece of this — the delta form of item 1 in @exocognosis's proposal above: for ttLOAN_SET/ttLOAN_PAY/ttLOAN_MANAGE, require ΔAssetsAvailable to equal the pseudo-account delta that visitEntry already collects (the same checkTotalsAddUp rule deposit/withdraw/clawback use) — exact for FixedPrecision vaults, within one unit for IOU on Legacy/CashBasis vaults — with negative cases in InvariantsVault_test and the lending suites run as the no-false-positive check.
Two questions before I write anything: would you take an external PR for this, or is it already covered by the work moving invariants into the transactors (#6618, #7435–#7437)? And if it's wanted, which amendment should gate the Legacy/CashBasis part — fixCleanup3_5_0 is already in the 3.5.0 rc, so a later cleanup fix or a dedicated one?
Sorry for the late Response, I was at Ripple Swell all last week, and was on the road.
On Mon, Oct 26, 2026 at 12:52 PM hmalinski @.***> wrote:
hmalinski left a comment (XRPLF/rippled#7690) https://github.com/XRPLF/rippled/issues/7690#issuecomment-6421931918
@Tapanito https://github.com/Tapanito @a1q123456 https://github.com/a1q123456 — following up on this. #7732 https://github.com/XRPLF/rippled/pull/7732 added the Loan/LoanBroker-side checks, but on current develop ValidVault::finalize still returns true for ttLOAN_PAY and ttLOAN_MANAGE, and ttLOAN_SET only gets the closed-vault phase gate, so in a release build nothing binds the change in sfAssetsAvailable to the vault pseudo-account's actual balance change for the lending transactions (the conservation checks in LoanPay.cpp are XRPL_ASSERTs).
I'd like to help with a narrow piece of this — the delta form of item 1 in @exocognosis https://github.com/exocognosis's proposal above: for ttLOAN_SET/ttLOAN_PAY/ttLOAN_MANAGE, require ΔAssetsAvailable to equal the pseudo-account delta that visitEntry already collects (the same checkTotalsAddUp rule deposit/withdraw/clawback use) — exact for FixedPrecision vaults, within one unit for IOU on Legacy/CashBasis vaults — with negative cases in InvariantsVault_test and the lending suites run as the no-false-positive check.
Two questions before I write anything: would you take an external PR for this, or is it already covered by the work moving invariants into the transactors (#6618 https://github.com/XRPLF/rippled/pull/6618, #7435 https://github.com/XRPLF/rippled/pull/7435–#7437 https://github.com/XRPLF/rippled/pull/7437)? And if it's wanted, which amendment should gate the Legacy/CashBasis part — fixCleanup3_5_0 is already in the 3.5.0 rc, so a later cleanup fix or a dedicated one?
— Reply to this email directly, view it on GitHub https://github.com/XRPLF/rippled/issues/7690?email_source=notifications&email_token=BRQBOTNTJ6VMRRR5W2LJVK35V56M5A5CNFSNUABFM5UWIORPF5TWS5BNNB2WEL2JONZXKZKDN5WW2ZLOOQXTMNBSGE4TGMJZGE4KM4TFMFZW63VHNVSW45DJN5XKKZLWMVXHJLDGN5XXIZLSL5RWY2LDNM#issuecomment-6421931918, or unsubscribe https://github.com/notifications/unsubscribe-auth/BRQBOTKQFKRV7KEEDC25S7L5V56M5AVCNFSNUABDKJSXA33TNF2G64TZHMZDOMRUGE3DOO2JONZXKZJ3GQ3TQOBWGQ3TMNZVUF3AE . Triage notifications, keep track of coding agent tasks and review pull requests on the go with GitHub Mobile for iOS https://github.com/notifications/mobile/ios/BRQBOTPGLDIBZ25KWUGW4I35V56M5A5CNFSNUABFM5UWIORPF5TWS5BNNB2WEL2JONZXKZKDN5WW2ZLOOQXTMNBSGE4TGMJZGE4KM4TFMFZW63VHNVSW45DJN5XKKZLWMVXHJKTGN5XXIZLSL5UW64Y and Android https://github.com/notifications/mobile/android/BRQBOTI3QTLKQAS5SDH7NJ35V56M5A5CNFSNUABFM5UWIORPF5TWS5BNNB2WEL2JONZXKZKDN5WW2ZLOOQXTMNBSGE4TGMJZGE4KM4TFMFZW63VHNVSW45DJN5XKKZLWMVXHJLTGN5XXIZLSL5QW4ZDSN5UWI. Download it today! You are receiving this because you were mentioned.Message ID: @.***>
-- James K Ryckman
@hmalinski's read matches mine. #7732 covered the Loan and LoanBroker side, but on current develop nothing in a release build binds the AssetsAvailable delta for LOAN_PAY or LOAN_MANAGE, and LOAN_SET gets only the closed-vault gate. The delta form he describes is item 1 of the proposal above, and I am glad to see it picked up. Happy to support his PR with review against the original proposal, or to take a piece myself if the maintainers prefer to split it. Either way, an answer on whether external PRs are wanted here would help.
Thanks @exocognosis, review against the original proposal would be welcome once there's something to look at.
@Tapanito @a1q123456 I'm putting together the delta form of item 1 from my earlier comment: for the three lending transactions, the change in sfAssetsAvailable has to match the pseudo-account's balance change under the same checkTotalsAddUp rule deposit, withdraw and clawback use. It comes with invariant tests that corrupt each side. I'll open it as a draft PR so there's something concrete to discuss, unless you'd rather it waited for #8586 and the FixedPrecision work to settle, or it's already covered on your side. Either way I'll shape it to fit.
@exocognosis @YogiBearXRP — opened a draft PR for item 1 of the proposal: https://github.com/XRPLF/rippled/pull/8719.
It binds ΔAssetsAvailable to the change in the vault pseudo-account's holding for LoanSet/LoanPay/LoanManage, as an object-level check in ValidVault::finalize (the form @Tapanito suggested in the #7732 review), gated on fixCleanup3_6_0. XRP/MPT are exact; IOU uses the same one-unit rounding the deposit/withdraw/clawback check uses on Legacy/CashBasis. The broader items (DebtTotal reconciliation, LossUnrealized/CoverAvailable, Loan→Broker→Vault linkage) are left as follow-ups.
Thanks for the clear write-up and for raising this — happy to narrow, split, or rebase onto the maintainers' own invariant work if that's preferred.