I am a bit confused about the difference between msg.value and address(this).balance, I read some QnA here , like this page. From what I read, I understood that each time a payable function is called address(this).balance is incremented by msg.value. This is not the case for my code below, each time my payable function receiveMoney
is called my address(this).balance is same as msg.value , even on subsequent and consecutive calls getBalance()
is always equal to balanceReceived
.I expected that for instance, if 1 ether was sent when receiveMoney()
is called msg.value should be 1 and address(this).balance should also be 1, then if receiveMoney()
is called the second time with 2 ether sent, msg.value should become 2 while address(this).balance becomes incremented by msg.value(2) to 3. In my own case the second call returned msg.value as 3 and address(this).balance as 3 too. Please I need clarification on this.
pragma solidity ^0.5.13;
contract SendMoneyExample{
uint public balanceReceived;
// this receiveMoney will recieve money from the address that called the smart contract to the
//smart contract
function receiveMoney() public payable{
balanceReceived += msg.value;
}
function getBalance() public view returns(uint){
return address(this).balance;
}
}
call
ing the contract locally