1

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;
} 

 


}
2
  • I suspect you are not issuing a real transaction, but calling the contract locally Feb 7, 2022 at 15:50
  • I don't understand what you mean, can you explain? Am working with remix Feb 8, 2022 at 16:26

1 Answer 1

1

This code makes sense. I would expect balancedReceived == address(this).balance

In this instance, msg.value is the amount on top of the tx fees sent to the smart contract. The contract balance (address(this).balance) is getting incremented by msg.value then you increment balancedReceived by the same amount, so they should be equal.

1
  • You are right, I just noticed that. I am now convinced that address(this). balance>=msg.value. Feb 8, 2022 at 16:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.