# When to use safemath library

I use safemath in (more or less) any contract where the number input could be malicious. But I have a contract that only handles ether. You can transfer ether to the contract. The ether amount can not be malicious (as far as I know).

So, I am wondering, when do I really NEED to use safemath. Adding safemath also adds some complexity, thus more gas is required.

• Certainly the amount of ether sent can be malicious (since an attacker controls it), but whether or not that can have an adverse effect on your contract can't be determined without looking at the contract. Jan 7 '18 at 14:26
• Well, but the amount has to be positive as well as it is bound to the global limits. So I doubt that the amount can be malicious. Or is there a way to manipulate the ETH Amount?
– kn1g
Jan 7 '18 at 16:00
• You might, for example, multiply the amount of ether by some value. Or perhaps accounts need to send you x ether before receiving some reward, and you subtract the amount sent from x (leading to integer underflow). As I said, it's impossible to know without seeing the code. Jan 7 '18 at 16:06
• Well that is the only "complex" math uint256 varA = msg.value/1000*varB; varC += varA; varD += msg.value - varA; But I got your point. Code can be buggy. You never know...
– kn1g
Jan 7 '18 at 16:17
• Depending on `varB`, `varA` could potentially overflow or `varD` could potentially underflow. Again, it's impossible to tell you whether or not you have potential overflows/underflows without seeing the code. Jan 7 '18 at 16:21

If the only maths you need to do is adding sums of Ether obtained from `msg.value` to other sums of Ether obtained from `msg.value`, it shouldn't be necessary to use SafeMath, since the `msg.value` is bounded by the number of Ether in existence, which is well below the range that can be represented by a `uint256`.