Skip to content

Commit 0051db1

Browse files
Add zero-division checks to stdMath.percentDelta overloads (#735)
### PR Description - **What**: Add explicit zero-divisor guards to `stdMath.percentDelta(uint256,uint256)` and `stdMath.percentDelta(int256,int256)`. - **Why**: Prevents runtime division-by-zero and makes failure mode explicit and predictable. - **How**: Added `require` checks with a concise error message and brief comments. --------- Co-authored-by: zerosnacks <[email protected]> Co-authored-by: zerosnacks <[email protected]>
1 parent a8f2815 commit 0051db1

File tree

2 files changed

+6
-2
lines changed

2 files changed

+6
-2
lines changed

src/StdMath.sol

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ library stdMath {
2929
}
3030

3131
function percentDelta(uint256 a, uint256 b) internal pure returns (uint256) {
32+
// Prevent division by zero
33+
require(b != 0, "stdMath percentDelta(uint256,uint256): Divisor is zero");
3234
uint256 absDelta = delta(a, b);
3335

3436
return absDelta * 1e18 / b;
@@ -37,6 +39,8 @@ library stdMath {
3739
function percentDelta(int256 a, int256 b) internal pure returns (uint256) {
3840
uint256 absDelta = delta(a, b);
3941
uint256 absB = abs(b);
42+
// Prevent division by zero
43+
require(absB != 0, "stdMath percentDelta(int256,int256): Divisor is zero");
4044

4145
return absDelta * 1e18 / absB;
4246
}

test/StdMath.t.sol

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ contract StdMathTest is Test {
125125
assertEq(stdMath.percentDelta(5000, uint256(2500)), 1e18);
126126
assertEq(stdMath.percentDelta(7500, uint256(2500)), 2e18);
127127

128-
vm.expectRevert(stdError.divisionError);
128+
vm.expectRevert("stdMath percentDelta(uint256,uint256): Divisor is zero");
129129
stdMathMock.exposed_percentDelta(uint256(1), 0);
130130
}
131131

@@ -163,7 +163,7 @@ contract StdMathTest is Test {
163163
assertEq(stdMath.percentDelta(5000, int256(2500)), 1e18);
164164
assertEq(stdMath.percentDelta(7500, int256(2500)), 2e18);
165165

166-
vm.expectRevert(stdError.divisionError);
166+
vm.expectRevert("stdMath percentDelta(int256,int256): Divisor is zero");
167167
stdMathMock.exposed_percentDelta(int256(1), 0);
168168
}
169169

0 commit comments

Comments
 (0)