Skip to content

Round the redeemCustom prorata bound with basketsNeeded - #1312

Merged
tbrent merged 6 commits into
4.3.0-audit-refresh-skip-delayfrom
fix/redeem-custom-prorata-rounding
Dec 1, 2026
Merged

tbrent merged 6 commits into
4.3.0-audit-refresh-skip-delayfrom
fix/redeem-custom-prorata-rounding

Conversation

@tbrent

@tbrent tbrent commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Stacked on #1320.

Summary

RToken.redeemCustom() bounds each withdrawal by the redeemer's prorata share of the BackingManager's balance. That share was balance * amount / totalSupply, which rounds separately from the reduction in basketsNeeded (basketsNeeded * amount / totalSupply). On a historical basket that gives a token more weight than the current one, the bound is what limits the withdrawal, and the two roundings could leave that balance a fraction of a token-wei lower relative to basketsNeeded than before the redemption. redeem() does not have this property, because its withdrawal is derived from the already-rounded basket amount.

This PR bounds the withdrawal by balance * baskets / basketsNeeded instead, where baskets is the amount basketsNeeded is reduced by. The share is taken of the balance truncated to 18 decimals, as Asset.bal() does, so it is a share of the same balance BasketHandler.basketsHeldBy() uses. After this change a custom redemption cannot lower the ratio of any balance to basketsNeeded, including for collateral with more than 18 decimals.

Changes

  • contracts/p0/RToken.sol: take the share of asset.bal() and shift to {qTok}, the same way quote() produces redemption amounts. The bound is now applied before the recipient balances are saved, as in P1.
  • contracts/p1/RToken.sol: the same expression as P0. To make room for it, the governance, notFrozen, and notTradingPausedOrFrozen checks are called through private functions, as StRSRP1 already does. Who can call what is unchanged.
  • contracts/facade/facets/ReadFacet.sol: redeemCustom() uses the same bound, so the facade quotes the exact withdrawal. redeem() is unchanged.
  • hardhat.config.ts: compile RTokenP1 with 145 optimizer runs, and drop the BackingManagerP1 override. See below. A per-file compiler override replaces the default settings, so the RToken override requests storageLayout explicitly; without it the upgrade-safety checks have no layout for that contract.
  • CHANGELOG.md: 4.3.0 entries.

Contract size

RTokenP1 was 24,555 bytes, 21 under the limit. The new bound brings it to 25,647 bytes at 200 optimizer runs and 25,215 at 1 run, so on its own it does not fit at any setting.

Each use of a modifier copies its body into the function. RTokenP1 used governance four times, and notFrozen and notTradingPausedOrFrozen twice each. Calling them through private functions saves 893 bytes at 200 runs, which leaves RTokenP1 at 24,754. 145 is the most runs that fits: 24,572 bytes at 145, 24,675 at 146.

BackingManagerP1 no longer needs its 100-run override. With the changes below this PR in the stack it is 24,333 bytes at the default 200 runs, so the override and its changelog line are removed.

One ordering difference follows from this: in redeemTo(), redeemCustom() and monetizeDonations() the frozen or paused check now runs after the reentrancy lock is taken instead of before. Either way the call reverts.

Behavior change

When the bound applies, a withdrawal can be smaller than before by dust. In sampling the difference was at most a few hundred wei for an 18-decimal token. The bound never pays more than before. A redemption whose only withdrawals were that dust now reverts with empty redemption. Redemptions where the bound does not apply are unchanged.

A facade built from this branch quotes the new bound. Against an RToken that has not been upgraded it can under-quote a custom redemption by that dust.

Testing

New tests in test/RToken.test.ts, for 6-, 18- and 21-decimal collateral, on P0 and P1: repeated custom redemptions on a historical basket must pay out exactly the share balance * baskets / basketsNeeded (of the balance at 18 decimals), must not lower the ratio of the balance to basketsNeeded, must leave the RToken fully collateralized, and must pay out exactly what ReadFacet.redeemCustom() quotes.

Checked that the new tests fail:

  • on the previous P0 and P1 code, for both 18 and 21 decimals
  • with the new RToken and the previous ReadFacet
  • for 21 decimals, with a bound of balance * baskets / basketsNeeded that does not truncate to 18 decimals

Ran on P0 and P1: RToken, Facade, Recollateralization, Main, Upgradeability, scenario/BadCollateralPlugin, and the #fast set.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Custom redemptions are limited by the backing collateral available for the baskets being redeemed, rather than by the redeemed share of the total token supply.
    • Redemption quotes now use the same basket-based calculation as withdrawals. Rounding may leave a small amount of dust unwithdrawn; attempting to redeem only that dust results in an “empty redemption” error.
    • For tokens with more than 18 decimals, the available withdrawal amount is rounded down to 18-decimal precision.
    • Facade quotes may differ when interacting with RToken versions older than 4.3.0.

redeemCustom() bounded each withdrawal by `balance * amount / totalSupply`,
which rounds separately from the reduction in basketsNeeded. On a historical
basket that over-weights a token, the bound applies and a redemption could
lower that balance's ratio to basketsNeeded by a fraction of a token-wei.

Bound by `balance * baskets / basketsNeeded` instead, where `baskets` is what
basketsNeeded is reduced by, and take the share of the balance truncated to
18 decimals, as Asset.bal() does. A custom redemption can then no longer
lower the ratio of any balance to basketsNeeded, including for tokens with
more than 18 decimals.

- P0 takes the share of asset.bal() and shifts to {qTok}. P1 computes the
  same value in {qTok} to save bytecode.
- ReadFacet.redeemCustom() and ReadFacet.redeem() (`available`) use the same
  bound, so the facade quotes the exact withdrawal.
- Compile RTokenP1 with 141 optimizer runs, the most that keeps it under the
  contract size limit (24551 bytes).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Explain Change →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review

No actionable comments were generated in the recent review.

Walkthrough

RToken custom-redemption caps and facade quotes now use basket shares instead of RToken supply shares. P1 redemption caps account for token decimals. Tests cover historical-basket redemptions with 6-, 18-, and 21-decimal collateral.

Changes: Basket-based redemption

Layer / File(s) Summary
Apply basket-based redemption bounds
contracts/p1/RToken.sol, contracts/p0/RToken.sol, contracts/facade/facets/ReadFacet.sol, hardhat.config.ts, CHANGELOG.md
P0 and P1 custom redemptions and facade quotes calculate withdrawal caps from the backing manager’s asset balance and the redeemed share of baskets. The P1 cap uses the asset’s decimals. The RToken compiler override uses 145 optimizer runs unless NO_OPT is set. Compiler overrides request storage-layout output. The changelog documents the bound, rounding behavior, and possible facade quote differences for older RToken versions.
Route checks through private helpers
contracts/p1/RToken.sol
P1 redemption, basket, donation, throttle, and mandate functions now call private helpers that apply the existing modifier checks.
Test historical-basket redemptions
test/RToken.test.ts
Tests exercise 25 redemptions against a historical basket with collateral using 6, 18, and 21 decimals. They compare facade quotes with received amounts and check the basket-based share, balance ratio, and basket collateralization.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Possibly related PRs

  • reserve-protocol/protocol#1298: Both PRs change Solidity compiler settings for P1 contracts. PR #1298 adds a 100-run optimizer override for BackingManager.sol, while this change applies 145 optimizer runs to RToken.sol and removes the BackingManager override.

Suggested reviewers: akshatmittal, julianmrodri

Merge Risk: Minimal · previous review 1e434

This change aligns the redeemCustom withdrawal bound and the facade quote with the reduction in basketsNeeded. No concrete merge-blocking defect was found. One thing to confirm before release: that BackingManagerP1 still fits under the deployed contract-size limit after its optimizer override was removed.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: the redeemCustom prorata withdrawal bound is now rounded using basketsNeeded. The changeset changes that bound in P0, P1, and ReadFacet, and the objectives describe th…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: the redeemCustom prorata withdrawal bound is now rounded using basketsNeeded. The changeset changes that bound in P0, P1, and ReadFacet, and the objectives describe the same change. The title is specific and matches the primary change.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 45e50682-5260-4098-89ff-0bf9366408e6
Commits

Reviewing files that changed from the base of the PR and between 9e3b385 and 1e434ae.

Files selected for processing: 3

  • CHANGELOG.md
  • hardhat.config.ts
  • test/RToken.test.ts
Files skipped from review as they are similar to previous changes: 1

  • CHANGELOG.md

Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 1 remain after this review.

tbrent and others added 4 commits November 24, 2026 00:41
…t for overrides

- ReadFacet.redeem(): restore the original available calculation. RToken.redeem()
  has no prorata bound, so there is nothing to mirror, and the facade serves
  older RTokens too.
- hardhat.config: per-file compiler overrides replace the default settings, so
  request storageLayout for them explicitly (RToken and BackingManager).
- Tests: cover 6 decimals and assert the exact prorata share.
- Changelog: note dust-only redemptions revert with empty redemption.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Replaces the unchecked exponent in the redeemCustom prorata bound with a
checked loop, and restates the comments around it. Same result. A checked
exponent does not fit at any optimizer setting; the loop fits at 126 runs
(24,544 bytes).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Use asset.bal().muluDivu().shiftl_toUint() for the prorata bound, replacing the
raw-unit form. To make room, call the governance, notFrozen, and
notTradingPausedOrFrozen checks through private functions, as StRSRP1 does.
RTokenP1 is 24,572 bytes at 145 optimizer runs.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…prorata-rounding

Stack on #1320.

- CHANGELOG: keep both sides.
- hardhat.config: drop the BackingManagerP1 compiler override. With the stack it
  is 24,333 bytes at the default 200 optimizer runs. RTokenP1 is unaffected and
  stays at 145 runs (24,572 bytes).
- Tests: call the overloaded refreshBasket() by full signature.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@tbrent
tbrent changed the base branch from master to 4.3.0-audit-refresh-skip-delay November 30, 2026 20:04
@akshatmittal
akshatmittal added this pull request to stack #1318 November 30, 2026 22:21
…prorata-rounding

Brings in the base branch's latest commits so the stack lines up. They net
to no code change, so this branch's tree is unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@tbrent
tbrent merged commit bd01378 into master Dec 1, 2026
16 of 17 checks passed
@tbrent
tbrent deleted the fix/redeem-custom-prorata-rounding branch December 1, 2026 17:31
tbrent added a commit that referenced this pull request Dec 1, 2026
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
tbrent added a commit that referenced this pull request Dec 1, 2026
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
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.

2 participants