Unary Plus Expression
Overview
- Severity: Medium
- Confidence: Medium
- Affected Versions: 0.4.x
What is the Unary Plus Expression vulnerability?
Certain older versions of Solidity allowed for a unary +
operator for mathematical expressions. This operator is liable to lead to potential accidental confusion in practice and is never strictly necessary, so it has been removed in newer versions of the language. In the case of older versions, its use should still be avoided to reduce the likelihood of an inadvertent logical error in a smart contract.
Further reading: Solidity Documentation: 0.5.0 Breaking Changes
Technical example of vulnerable code
// SPDX-License-Identifier: Unlicense
pragma solidity 0.4.0;
contract TokenVault {
mapping(address => uint256) public balances;
function deposit(uint256 amount) public {
// Typographical error: Intended to use += but mistakenly used =+
// In older versions of Solidity, this could compile but not update balances as intended.
balances[msg.sender] =+ amount; // Logical error due to misuse of unary + operator
// Other deposit logic + logging omitted for brevity
}
// Additional functions to withdraw or transfer tokens are omitted for brevity
}
In the example above, contract TokenVault
has a function deposit()
which is mean to track tokens deposited by various users; however, it transposes +=
into =+
, which will cause the +
to be interpreted as the unary operator, overwriting the balance each time for a given address rather than incrementing it on deposit.
Technical example of how to fix the vulnerability
// SPDX-License-Identifier: Unlicense
pragma solidity 0.4.0;
contract TokenVaultUpdated {
mapping(address => uint256) public balances;
function deposit(uint256 amount) public {
balances[msg.sender] += amount;
// Other deposit logic + logging omitted for brevity
}
// Additional functions to withdraw or transfer tokens are omitted for brevity
}
In the revised example above, contract TokenVaultUpdated
now uses the correct +=
operator for updating the balances
mapping, avoiding the unary plus operator which led to incorrect logic in the previous example.