Jim Parsnip
Jim Parsnip

Reputation: 25

Solidity Subtracting msg.value or address(this).balance

I'm simplifying this down but let's say I have a payable function called myFunction. After a transaction is made (via React) I want to update the number property of a struct within the contract called myStruct using basic math. Let's say I want to calculate it as 1 minus the new contract balance.

function myFunction() public payable {
  myStruct.number = 1 - address(this).balance;
}

If I send a 0.01 ETH to this function on a new contract with a 0 balance, myStruct.number renders out as 15792089237316195423570985008687907853269984665640564039457574007913129639937

I can't for the life of me figure out why. If I do basic math without using address(this).balance or msg.value then it's fine and renders correctly. But every time I try to involve either of those, I get these wild results.

Help would be much appreciated!

Upvotes: 1

Views: 2307

Answers (2)

Jacopo Mosconi
Jacopo Mosconi

Reputation: 1062

I guess myStruct.number is a uint. by declaring uint you are declaring a 256-bit int that accepts only positive numbers.

when you send 0.01 ETH to the contract balance, you are actually receiving 10000000000000000 WEI (you must remember that 1 ETH is formed by 1e18 WEI)

calling

address(this).balance

you will get 10000000000000000 as a result, so you're trying to do

1 - 10000000000000000

and since uint only accepts positive numbers, you get that result.

I suggest you use the SafeMath library to avoid these errors https://docs.openzeppelin.com/contracts/2.x/api/math

Upvotes: 1

Erim Varış
Erim Varış

Reputation: 94

Hey you have to use SafeMath library. Solidity works different than other languages on variables.

using SafeMath for uint256;

Also import SafeMath.sol from Openzeppelin's library, then you can continue with much more accurate results.

Upvotes: 0

Related Questions