Skip to content

fix: Round vault share conversions in the vault's favor (fixCleanup3_6_0) - #8708

Open
muhammadsalah wants to merge 11 commits into
XRPLF:developfrom
muhammadsalah:ci/fix-vault-deposit-rounding
Open

muhammadsalah wants to merge 11 commits into
XRPLF:developfrom
muhammadsalah:ci/fix-vault-deposit-rounding

Conversation

@muhammadsalah

@muhammadsalah muhammadsalah commented Nov 9, 2026 •

Copy link
Copy Markdown

High Level Overview of Change

Supersedes #7824, which was closed and can't be reopened. The earlier review discussion is there.

Under the fixCleanup3_6_0 amendment, the vault's share/asset conversions for XRP and MPT vaults are computed exactly and rounded in the vault's favor, so a single depositor or withdrawer can no longer dilute the other shareholders through round-to-nearest:

  • Deposit: the shares minted round down and the assets charged for them round up, so the depositor pays at least the fair value of the shares.
  • Withdraw: the shares burned (withdraw by amount) round down and the assets paid for them round down, so the withdrawer receives at most the fair value of the shares.
  • Clawback: the same as withdraw, so the issuer recovers at most the fair value of the shares it burns.

Context of Change

The conversions computed assetsTotal * shares / sharesTotal in Number and quantized to the asset with round-to-nearest. On a vault holding an integral asset at a non-unit share price:

  • a deposit could be charged up to half a unit less than the shares are worth, and
  • a withdrawal or clawback could recover up to half a unit more than the shares are worth.

Either way, the remaining shareholders cover the difference.

Rounding each Number step up or down is not enough. Number keeps 19 digits, so with large totals a directed rounding mode can move an exact result by a whole unit. With AssetsTotal = SharesTotal = 1,000,000,000,000,007 (price exactly 1), a deposit of 123,456,789 has to charge 123,456,789, but AssetsTotal * shares needs 24 digits, and rounding up at every step charges 123,456,790. The deposit then fails with tecINTERNAL ("would take more than offered"). For XRP and MPT every operand is an integer, so the conversions now compute a * b / c in 128 bits and round once.

Changes, all behind fixCleanup3_6_0 (fixCleanup3_5_0 is already in 3.5.0-rc1):

  • The four conversion helpers take a VaultRounding argument (Legacy by default). FavorVault uses the exact integer path for XRP and MPT. IOU conversions keep the existing arithmetic, since an IOU result is not exact anyway and the fixCleanup3_4_0 scale clamps already round IOU amounts in the vault's favor.
  • VaultWithdraw and VaultClawback truncate the by-amount share count under the new gate too, so it no longer depends on fixCleanup3_4_0 being enabled.
  • When a share is worth less than one unit, a non-final VaultWithdraw whose rounded-down payout is zero, while the vault still has withdrawable value, fails with tecPRECISION_LOSS instead of burning shares for nothing. The final withdrawal is unaffected.
  • VaultClawback gets the same guard: a recovery that rounds down to zero from a non-empty vault fails with tecPRECISION_LOSS. Without it, burning shares while the vault balance stays the same would fail the clawback invariant.
  • VaultWithdraw::preclaim uses the same rounding so the withdrawal-limit check estimates the amount doApply will pay.
  • Clawback by the vault owner of an empty vault (burning shares only) is unchanged.

These address findings from Common Prefix's public formal verification of the XRPL vault and lending protocol (testVaultDepositOvervaluedShares). The withdraw payout is the symmetric case.

Thanks to @hmalinski for finding the large-totals edge case and proposing the exact integer approach, the new gate, the share truncation, and the zero-payout check.

API Impact

  • Public API: New feature (new methods and/or new fields)
  • Public API: Breaking change (in general, breaking changes should only impact the next api_version)
  • libxrpl change: assetsToSharesDeposit, sharesToAssetsDeposit, assetsToSharesWithdraw and sharesToAssetsWithdraw in include/xrpl/ledger/helpers/VaultHelpers.h each gain a defaulted VaultRounding parameter (source-compatible; the default preserves prior behavior).
  • Peer protocol change (must be backward compatible or bump the peer protocol version)

Before / After

Pool of 100 assets and 3 shares (MPT):

Operation Fair value Before After (fixCleanup3_6_0)
Deposit 34, mints 1 share 33.33 charged 33 charged 34
Withdraw 2 shares 66.67 paid 67 paid 66
Withdraw 50 assets without fixCleanup3_4_0 burns 2 shares, pays 67 burns 1 share, pays 33
Claw back 2 shares (or 67 assets) 66.67 recovers 67 recovers 66

Exact rates, and cases where round-to-nearest already rounds the safe way, are unchanged.

Test Plan

The test scenarios for the large-totals edge case, the zero-payout rejection and the fixCleanup3_6_0 gating come from @hmalinski, who found the edge case and described these tests in #7824.

  • VaultRounding_test (new): transaction-level tests on CashBasis and FixedPrecision MPT vaults, each with and without fixCleanup3_6_0: the deposit and withdraw dilution cases (by shares and by amount), the large-totals deposit and withdrawal, the zero-payout rejection on both withdraw branches (and with fixCleanup3_4_0 off), and share truncation without fixCleanup3_4_0. Clawback has the same coverage: the recovery rounding (all shares and by amount), the zero-recovery rejection, and share truncation without fixCleanup3_4_0.
  • VaultHelpers_test: helper-level tests for MPT and XRP, including the large-totals case, withdraw conversions with a non-zero LossUnrealized under both WaiveUnrealizedLoss values, and a check that FavorVault leaves IOU conversions unchanged.
  • VaultBugs_test and LoanRounding_test: two pre-fixCleanup3_4_0 bug repros now also disable fixCleanup3_6_0, which fixes them on its own; each gains a run showing that.

Local run (Release, asserts on): all Vault* suites, xrpl.tx.Loan*, xrpl.app.LoanBroker* and xrpl.app.Invariants* pass (38 suites, 186,832 tests, 0 failures).

🤖 Generated with Claude Code

muhammadsalah and others added 2 commits November 9, 2026 18:05
…der dilution

Under the fixCleanup3_5_0 amendment, round the vault's share->asset
conversions in the pool's favor so that a single depositor or withdrawer
can no longer dilute the other shareholders through round-to-nearest.

Deposit: sharesToAssetsDeposit() rounds the assets charged for freshly
minted shares Upward, so the depositor pays at least the fair value of
those shares. Round-to-nearest could undercharge, overvaluing the new
shares. VaultDeposit::doApply() passes Upward when the amendment is on.

Withdraw: sharesToAssetsWithdraw() rounds the assets paid for burned
shares Downward, so the withdrawer receives at most the fair value of
those shares. Round-to-nearest could overpay, dropping the assets-per-
share price for the remaining holders. VaultWithdraw::doApply() passes
Downward on both the fixed-asset and fixed-share branches, and preclaim
matches it so the withdrawal-limit check estimates the same amount.

This is complementary to, not subsumed by, fixCleanup3_4_0. That
amendment truncates the assets->shares leg of the withdrawal round trip
and clamps the resulting asset delta onto the posterior sfAssetsTotal
grid; it leaves the shares->assets quantization at round-to-nearest. The
clamp is also a no-op for integral assets - clampToAssetsTotalScale()
returns the magnitude unchanged when the asset is integral, and
roundToScale() is documented as a no-op for XRP and MPT - so on XRP- and
MPT-denominated vaults the payout is still quantized by
STAmount::canonicalize() under the ambient mode. The rounding modes added
here are therefore load-bearing for integral assets in both directions,
and for IOUs they only ever move the result the same way the
fixCleanup3_4_0 clamp already does.

Both helpers take a rounding mode defaulting to ToNearest to preserve
pre-amendment behavior; the quantization to the asset's precision honors
the mode for integral (XRP/MPT) and IOU assets alike. Clawback is left
unchanged. Direct unit tests on an MPT asset exercise each conversion
under ToNearest vs the pool-favoring mode.

testBugVaultLockedByPartialWithdraw's pre-fix scenario now disables
fixCleanup3_5_0 alongside fixCleanup3_4_0. The Downward payout rounding
floors the last-share withdrawal onto a representable amount, which keeps
the invariant satisfied even without the fixCleanup3_4_0 clamp, so the
scenario no longer reproduced the bug it is there to demonstrate.

This addresses catches found by the Common Prefix formal verification
public project.
Move the pool-favoring vault rounding to the fixCleanup3_6_0 gate, since
fixCleanup3_5_0 already shipped in 3.5.0-rc1, and replace directed Number
rounding with exact integer math for integral assets.

Rounding each Number step up or down is not enough: Number keeps 19
digits, so with large totals it can move an exact result by a whole
unit. With AssetsTotal = SharesTotal = 1'000'000'000'000'007, a deposit
of 123'456'789 was charged 123'456'790 and failed with tecINTERNAL
("would take more than offered").

- Add VaultRounding {Legacy, FavorVault} to all four share<->asset
  conversions. With FavorVault and an XRP or MPT vault, compute a*b/c
  in 128 bits and round once: share counts and payouts down, deposit
  charges up. IOU conversions keep the existing arithmetic; their
  scale clamps already round in the vault's favor.
- VaultWithdraw truncates the withdraw-by-amount share count under
  fixCleanup3_6_0 as well, so it no longer depends on fixCleanup3_4_0.
- A non-final VaultWithdraw whose rounded-down payout is zero, while
  the vault still has withdrawable value, fails with tecPRECISION_LOSS
  instead of burning shares for nothing.

Tests: VaultRounding_test covers the dilution cases, the large-totals
edge case, the zero payout and the gating, on CashBasis and
FixedPrecision vaults. VaultHelpers_test covers the helpers on MPT and
XRP. Two pre-fixCleanup3_4_0 bug repros now also disable
fixCleanup3_6_0, which fixes them on its own.

Co-authored-by: Harry Malinski <138065872+hmalinski@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@muhammadsalah

Copy link
Copy Markdown
Author

@mvadari PR is reopened here
@hmalinski Thank you for the hint for the tests, I am open to any review or recommendations for sure!

Please let me know if anything else I should be doing to ship this.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Consensus-critical vault accounting changes across amendment combinations and lending interactions warrant independent domain review and transaction-level validation of impaired-loan and transfer-fee cases.

No open issues 🎉

What changed in this PR

This PR prevents shareholder dilution in XRP and MPT vaults by using exact integer conversions rounded in the vault’s favor under fixCleanup3_6_0. Legacy conversion behavior remains the default, and IOU conversion arithmetic and clawback behavior are unchanged.

Changes:

  • Add exact 128-bit conversions that floor share counts and withdrawal payouts, while rounding deposit charges up.
  • Apply amendment-gated rounding to deposits and withdrawals, align withdrawal-limit estimates, and reject non-final zero-value payouts.
  • Add regression coverage for dilution, large totals, zero payouts, and amendment combinations.
File Description
src/​test/​app/​vault/​VaultRounding_test.cpp Add transaction-level rounding and amendment-gating tests for both vault versions.
src/​test/​app/​vault/​VaultHelpers_test.cpp Test exact XRP/MPT conversions and unchanged IOU arithmetic.
src/​test/​app/​vault/​VaultBugs_test.cpp Update overshoot regression tests for the new amendment.
src/​test/​app/​lending/​LoanRounding_test.cpp Cover zero-payout rejection with different amendment combinations.
src/​libxrpl/​tx/​transactors/​vault/​VaultWithdraw.cpp Apply rounding, truncate shares, and guard against zero payouts.
src/​libxrpl/​tx/​transactors/​vault/​VaultDeposit.cpp Enable vault-favoring deposit conversions behind the amendment.
src/​libxrpl/​ledger/​helpers/​VaultHelpers.cpp Implement exact integer multiply-divide conversions with directed rounding.
include/​xrpl/​ledger/​helpers/​VaultHelpers.h Declare and document the defaulted VaultRounding parameters.

Review effort: Balanced

@hmalinski hmalinski left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for picking this back up. The exact integer path, the gate and the zero-payout check all look right to me. I also checked that the rounded-up deposit charge can never exceed the amount offered: the share count is floored from the amount, so the ceiling of its value is at most the amount. Two things:

1. Clawback still rounds to nearest.
VaultClawback.cpp:307, :327 and :349 still use the legacy conversion. The description notes this, and it leaves the same dilution in place.

Example: a vault holds 100 units with 3 shares outstanding. Clawing back 67 from a holder with 2 shares burns both shares and recovers 67, although they were worth 66⅔. The remaining share drops from 33⅓ to 33. The 3_4_0 truncation bounds recovery by the requested amount, and the AssetsAvailable clamp bounds it by what's available, but neither bounds it by fair value.

Changing just those three calls to FavorVault isn't quite enough. A recovery that floors to zero would burn shares without moving the vault balance, and the clawback invariant rejects that for a non-empty vault (VaultInvariant.cpp:1445-1449). So it needs explicit zero-recovery handling, like the new withdraw guard. I'm fine with it as a follow-up under the same amendment, or a sentence in the description on why it's out of scope. It would be nice to settle before 3_6_0 ships, so it doesn't need another amendment later.

2. Helper tests with nonzero unrealized loss.
Every FavorVault helper case uses makeVaultAndIssuance, which sets sfLossUnrealized to 0 (VaultHelpers_test.cpp:603), and WaiveUnrealizedLoss::No. Both withdraw helpers feed AssetsTotal − LossUnrealized into the integer path, so it has to be a whole number. Could you add XRP/MPT helper cases with LossUnrealized > 0, a non-zero payout, and both WaiveUnrealizedLoss values? LoanRounding_test already covers the impaired zero-payout and fully-impaired cases through the transactors, so those don't need repeating.

FYI: #8358 changes these helpers to take VaultEntryR const&, which needs a view to construct. Whichever PR lands second will need a small rebase, including the helper tests that pass raw SLEs.

Happy to approve once item 2 is in and item 1 is either handled or noted as a follow-up.

VaultClawback converted shares to assets with round-to-nearest, so an
issuer could recover more than the shares it burned were worth, and the
remaining shareholders covered the difference. Under fixCleanup3_6_0 it
uses the same exact, vault-favoring conversions as VaultWithdraw, and
truncates the by-amount share count without depending on
fixCleanup3_4_0.

A recovery that rounds down to zero from a non-empty vault now fails
with tecPRECISION_LOSS. Burning shares without debiting the vault would
otherwise fail the clawback invariant.

Also declare the rounding parameter const in the conversion helper
definitions, and add helper tests with a non-zero LossUnrealized under
both WaiveUnrealizedLoss values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@muhammadsalah

Copy link
Copy Markdown
Author

@hmalinski thank you for the feedback, I have honored it
@BraedonKlock thank you for the review, I have honored it

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The API-visible rounding changes and new tecPRECISION_LOSS outcomes for withdrawals and clawbacks lack the required API-CHANGELOG.md entry under Unreleased.

1 open issue

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The all-shares clawback path uses legacy rounding when fixCleanup3_6_0 is enabled and fixCleanup3_1_3 is disabled, recovering excess assets and diluting the remaining holder.

1 open issue
1 resolved since last review

Review effort: Balanced

Without fixCleanup3_1_3, a zero-amount clawback takes a separate path
that converted shares to assets with the default round-to-nearest, even
when fixCleanup3_6_0 was enabled. The two amendments can be enabled in
either order, so an issuer could still recover more than the burned
shares were worth, diluting the remaining shareholders.

Pass the fixCleanup3_6_0 rounding mode on that path too. Its missing
clamp to AssetsAvailable is unchanged and remains fixCleanup3_1_3's
concern.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues were identified for the amendment-gated vault rounding changes.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@muhammadsalah

Copy link
Copy Markdown
Author

@BraedonKlock @BraedonKlock @mvadari
What should be next steps to ship this?

@BraedonKlock

Copy link
Copy Markdown
Contributor

@muhammadsalah A maintainer will need to review the PR before it can be merged. This may take some time, as there's a fair amount of work involved in reviewing PRs. 😄

The conversion on the pre-fixCleanup3_1_3 path ran outside the overflow
handler, so an overflow_error escaped the transactor. Under
fixCleanup3_6_0 it now returns tecPATH_DRY like the other conversion
paths; without the amendment the exception still propagates, for ledger
replay compatibility.

Also give favorVaultMulDiv descriptive parameter names.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@xrplf-bot
xrplf-bot requested a balanced review from Copilot November 18, 2026 16:17

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Consensus-critical vault arithmetic changes span independent amendment combinations and persisted versions, requiring human validation of replay compatibility and financial invariants because native tests could not be run.

No open issues 🎉

Review effort: Balanced

@muhammadsalah

Copy link
Copy Markdown
Author

@mvadari what should I be doing next to push this forward?
@BraedonKlock thank you once again for the review + comments

@codecov

codecov Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.40260% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/libxrpl/ledger/helpers/VaultHelpers.cpp 93.1% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

muhammadsalah and others added 3 commits November 23, 2026 21:28
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add a test that an MPT vault conversion whose exact quotient exceeds
int64 throws std::overflow_error, and exclude the unreachable
non-integral return in toExactUInt from coverage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The new vault rounding suite splits coverage already handled by existing vault tests, contrary to repository guidance to extend those suites instead.

1 open issue

Review effort: Balanced

* FixedPrecision vault (LendingProtocolV1_2 on), each with and without the
* amendment.
*/
class VaultRounding_test : public VaultTestBase

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants