@0x/contracts-utils: LibMath._safeDiv() now throws a rich revert when dividing by zero.

This commit is contained in:
Lawrence Forman 2019-08-01 13:10:48 -04:00
parent 5a088690b2
commit d03f13a729
3 changed files with 20 additions and 6 deletions

View File

@ -10,7 +10,8 @@ library LibSafeMathRichErrors {
enum SafeMathErrorCodes { enum SafeMathErrorCodes {
UINT256_ADDITION_OVERFLOW, UINT256_ADDITION_OVERFLOW,
UINT256_MULTIPLICATION_OVERFLOW, UINT256_MULTIPLICATION_OVERFLOW,
UINT256_SUBTRACTION_UNDERFLOW UINT256_SUBTRACTION_UNDERFLOW,
UINT256_DIVISION_BY_ZERO
} }
// solhint-disable func-name-mixedcase // solhint-disable func-name-mixedcase

View File

@ -30,6 +30,13 @@ contract SafeMath {
pure pure
returns (uint256) returns (uint256)
{ {
if (b == 0) {
LibRichErrors._rrevert(LibSafeMathRichErrors.SafeMathError(
LibSafeMathRichErrors.SafeMathErrorCodes.UINT256_DIVISION_BY_ZERO,
a,
b
));
}
uint256 c = a / b; uint256 c = a / b;
return c; return c;
} }

View File

@ -1,4 +1,4 @@
import { AnyRevertError, BigNumber, SafeMathRevertErrors } from '@0x/utils'; import { BigNumber, SafeMathRevertErrors } from '@0x/utils';
const MAX_UINT256 = new BigNumber(2).pow(256).minus(1); const MAX_UINT256 = new BigNumber(2).pow(256).minus(1);
@ -29,16 +29,22 @@ export function safeSub(a: BigNumber, b: BigNumber): BigNumber {
export function safeMul(a: BigNumber, b: BigNumber): BigNumber { export function safeMul(a: BigNumber, b: BigNumber): BigNumber {
const r = a.times(b); const r = a.times(b);
if (r.isGreaterThan(MAX_UINT256)) { if (r.isGreaterThan(MAX_UINT256)) {
// Solidity implementation does not throw a reason. throw new SafeMathRevertErrors.SafeMathError(
throw new AnyRevertError(); SafeMathRevertErrors.SafeMathErrorCodes.Uint256MultiplicationOverflow,
a,
b,
);
} }
return r; return r;
} }
export function safeDiv(a: BigNumber, b: BigNumber): BigNumber { export function safeDiv(a: BigNumber, b: BigNumber): BigNumber {
if (b.isEqualTo(0)) { if (b.isEqualTo(0)) {
// Solidity implementation does not throw a reason. throw new SafeMathRevertErrors.SafeMathError(
throw new AnyRevertError(); SafeMathRevertErrors.SafeMathErrorCodes.Uint256DivisionByZero,
a,
b,
);
} }
return a.dividedToIntegerBy(b); return a.dividedToIntegerBy(b);
} }