Open code423n4 opened 2 years ago
//new one
function worth_1() public pure returns (uint256) {
uint256 _value = 100;
uint256 _supply = 1;
uint256 _originalLiquidity = 1;
uint256 _amount;
if (_supply == 0) {
_amount = _value;
} else if (_originalLiquidity == 0) {
_amount = _value * _supply;
} else {
_amount = (_value * _supply) / _originalLiquidity;
}
return _amount;
}
//current one
function worth_2() public pure returns (uint256) {
uint256 _value = 100;
uint256 _supply = 1;
uint256 _originalLiquidity = 1;
uint256 _amount;
if (_supply > 0 && _originalLiquidity > 0) {
_amount = (_value * _supply) / _originalLiquidity;
} else if (_supply > 0 && _originalLiquidity == 0) {
_amount = _value * _supply;
} else {
_amount = _value;
}
return _amount;
}
//little bit of gas opt from worth_2
function worth_3() public pure returns (uint256) {
uint256 _value = 100;
uint256 _supply = 1;
uint256 _originalLiquidity = 1;
uint256 _amount;
if (_supply != 0 && _originalLiquidity != 0) {
_amount = (_value * _supply) / _originalLiquidity;
} else if (_supply != 0 && _originalLiquidity == 0) {
_amount = _value * _supply;
} else {
_amount = _value;
}
return _amount;
}
worth_1 => 21876 gas worth_2 => 21934 gas worth_3 => 21918 gas
Handle
Dravee
Vulnerability details
Impact
It's possible to save gas by optimizing the checks in conditional statements (
if
,else if
andelse
). This would save a few opcodes and avoid redundant checks.Proof of Concept
In
PoolTemplate.sol:worth()
, the code is as follows:The conditions checks can be optimized with the following (read the
@audit-info
comments for further information):Tools Used
VS Code
Recommended Mitigation Steps
Compact conditions in mentioned logic statements