Repository navigation
fix: Round vault share conversions in the vault's favor (fixCleanup3_6_0) - #8708
muhammadsalah wants to merge 11 commits into
Conversation
…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>
|
@mvadari PR is reopened here Please let me know if anything else I should be doing to ship this. |
There was a problem hiding this comment.
🔵 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
left a comment
There was a problem hiding this comment.
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>
|
@hmalinski thank you for the feedback, I have honored it |
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
🟡 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>
|
@BraedonKlock @BraedonKlock @mvadari |
|
@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>
There was a problem hiding this comment.
🔵 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
|
@mvadari what should I be doing next to push this forward? |
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
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>
| * FixedPrecision vault (LendingProtocolV1_2 on), each with and without the | ||
| * amendment. | ||
| */ | ||
| class VaultRounding_test : public VaultTestBase |


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_0amendment, 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:Context of Change
The conversions computed
assetsTotal * shares / sharesTotalinNumberand quantized to the asset with round-to-nearest. On a vault holding an integral asset at a non-unit share price:Either way, the remaining shareholders cover the difference.
Rounding each
Numberstep up or down is not enough.Numberkeeps 19 digits, so with large totals a directed rounding mode can move an exact result by a whole unit. WithAssetsTotal = SharesTotal = 1,000,000,000,000,007(price exactly 1), a deposit of 123,456,789 has to charge 123,456,789, butAssetsTotal * sharesneeds 24 digits, and rounding up at every step charges 123,456,790. The deposit then fails withtecINTERNAL("would take more than offered"). For XRP and MPT every operand is an integer, so the conversions now computea * b / cin 128 bits and round once.Changes, all behind
fixCleanup3_6_0(fixCleanup3_5_0is already in 3.5.0-rc1):VaultRoundingargument (Legacyby default).FavorVaultuses the exact integer path for XRP and MPT. IOU conversions keep the existing arithmetic, since an IOU result is not exact anyway and thefixCleanup3_4_0scale clamps already round IOU amounts in the vault's favor.VaultWithdrawandVaultClawbacktruncate the by-amount share count under the new gate too, so it no longer depends onfixCleanup3_4_0being enabled.VaultWithdrawwhose rounded-down payout is zero, while the vault still has withdrawable value, fails withtecPRECISION_LOSSinstead of burning shares for nothing. The final withdrawal is unaffected.VaultClawbackgets the same guard: a recovery that rounds down to zero from a non-empty vault fails withtecPRECISION_LOSS. Without it, burning shares while the vault balance stays the same would fail the clawback invariant.VaultWithdraw::preclaimuses the same rounding so the withdrawal-limit check estimates the amountdoApplywill pay.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
libxrplchange:assetsToSharesDeposit,sharesToAssetsDeposit,assetsToSharesWithdrawandsharesToAssetsWithdrawininclude/xrpl/ledger/helpers/VaultHelpers.heach gain a defaultedVaultRoundingparameter (source-compatible; the default preserves prior behavior).Before / After
Pool of 100 assets and 3 shares (MPT):
fixCleanup3_6_0)fixCleanup3_4_0Exact 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_0gating 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 withoutfixCleanup3_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 withfixCleanup3_4_0off), and share truncation withoutfixCleanup3_4_0. Clawback has the same coverage: the recovery rounding (all shares and by amount), the zero-recovery rejection, and share truncation withoutfixCleanup3_4_0.VaultHelpers_test: helper-level tests for MPT and XRP, including the large-totals case, withdraw conversions with a non-zeroLossUnrealizedunder bothWaiveUnrealizedLossvalues, and a check thatFavorVaultleaves IOU conversions unchanged.VaultBugs_testandLoanRounding_test: two pre-fixCleanup3_4_0bug repros now also disablefixCleanup3_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*andxrpl.app.Invariants*pass (38 suites, 186,832 tests, 0 failures).🤖 Generated with Claude Code