Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

safeMulDiv round #1187

Merged
merged 3 commits into from
Aug 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions contracts/libraries/Fixed.sol
Original file line number Diff line number Diff line change
Expand Up @@ -577,8 +577,6 @@ library FixLib {
uint256 pow2 = c & (0 - c);

uint256 c_256 = uint256(c);
// Warning: Should not access c below this line

c_256 /= pow2;
lo /= pow2;
lo += hi * ((0 - pow2) / pow2 + 1);
Expand All @@ -597,7 +595,7 @@ library FixLib {
if (rounding == CEIL) {
if (mm != 0) result_256 += 1;
} else if (rounding == ROUND) {
if (mm > ((c_256 - 1) / 2)) result_256 += 1;
if (mm > ((c - 1) / 2)) result_256 += 1; // intentional: use pre-divided c here
}
}

Expand Down
10 changes: 10 additions & 0 deletions test/libraries/Fixed.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1145,6 +1145,16 @@ describe('In FixLib,', () => {
await caller.safeMulDiv(MAX_UINT192.div(fp(2)).sub(1), fp(1), MAX_UINT192, CEIL)
).to.equal(1)
})

it('regression test -- safeMulDiv with ROUND', async () => {
// ROUND was rounding up for _most_ values, instead of half of them
// here we test that 0.1, 0.01, ...0.000000000000001 etc are all rounded down

for (let i = 0; i < 18; i++) {
const amt = fp(`1e-${i + 1}`)
expect(await caller.safeMulDiv(amt, fp(1).add(1), fp(1), ROUND)).to.equal(amt)
}
})
})

describe('safeDiv_', () => {
Expand Down
Loading