This might be a basic question, but still dealing with conceptual stuff about ethereum and solidity.
Original question was: How does solidity send() & transfer() know about contract ether? Editing it to: Why function that does transfer without a mapping fails?
If a contract wants to hold ether you create a payable function that receives the msg.value.
To withdraw ether you would specify a function with the intended address destination and amount.
However when I test the second statement it only seems to be true if I use a mapping. On the example below not concerned about security, so this code would not apply to real life.
If I do another function that does not a mapping, no error is returned, and although it succeds performing the transaction, no ETHER is trully withdrawn.
To me both are the same, one keeps a track of addresses and the other one does not, however the transfer is the same.
So based on this behavior is where my confusion stems on how a function to withdraw knows it is ether belonging to the contract. To deposit we have "payable" but no equivalent to withdraw.
I know one could do msg.sender.transfer(address(this).balance) where address(this) refers to the contract.
pragma solidity >=0.5.0 <0.6.0;
contract CheckBehavior {
mapping(address => uint256) _deposits;
function depo() public payable{
_deposits[msg.sender]= msg.value;
}
//not working
function withdrawA(uint256 _amt) public {
msg.sender.transfer(_amt);
}
//not working , I would expect this to work fine as withdrawWithGas()
function withdrawB(address payable payee, uint256 _amt) public {
payee.transfer(_amt);
}
//Works. My understanding is that the mapping is a security pattern to avoid re-entrancy, as
this keeps track of addresses and one can condition based on it
function withdrawWithGas(address payable payee) public {
uint256 payment = _deposits[payee];
_deposits[payee] = 0;
payee.transfer(payment);
}
}
First image is the transaction of the deposit, money reflects as subtracted fine on remix.
Second image is transaction of withdrawA, which does transact but does not give me any ether. If I use instead the last one it works.