Msg.Sender Account | Contract Account in Solidity
Aim: to understand the difference between msg.sender account and contract account
This is code : https://github.com/veridelisi/basic-solidity/blob/main/09.msgsendercontractdepositwithdrawal.sol
This is our account : msg.sender, This account has 100 ether
First of all, you don’t need to specify address(this).balance
to receive funds directly to the contract. As long as a function is payable and you do not specify what to do with msg.value
, all funds wil directly go into the contract internal balance.
Deploy the contract !
You write “10” to the value section and click the “deposit” button.
You sent 10 ether from msg.sender to contract account
This is deposit function in the contract.
function deposit() public payable {
balances[msg.sender] += msg.value;
}
Click the getBalance and getBalance2 buttons.
getBalance function gives us the balance of the msg sender
getBalance returns msg.sender.balance
function getBalance() public view returns(uint256){
return msg.sender.balance;
}
getBalance2 function gives us the balance of the contract
function getBalance2() public view returns(uint256){
return address(this).balance;
}
Dont forget that this 10 ether is belong to the msg.sender .
Note: (msg.sender’s money in the contract and money amount in the contract)
Now we withdraw our money from the contract !
You write 10000000000000000000 to the withdraw_via_transfer
function withdraw_via_transfer(uint256 amount) public {
require(address(this).balance >= amount, “Invalid withdraw request”);
payable(msg.sender).transfer(amount);
balances[msg.sender] += amount;
}
Check it !
Click the getBalance and getBalance2 buttons.
Dr. Engin YILMAZ