Hey @thecil,
Thank you for that. I’m still not quite clear though… sorry…
For clarity I’m looking at the bank contract provided by Filip :
pragma solidity 0.8.0;
pragma abicoder v2;
import "./Ownable.sol";
import "./SafeMath.sol";
contract Bank is Ownable {
using SafeMath for uint256;
mapping(address => uint) balance;
address[] customers;
event depositDone(uint amount, address indexed depositedTo);
function deposit() public payable returns (uint) {
balance[msg.sender] = balance[msg.sender].add(msg.value);
emit depositDone(msg.value, msg.sender);
return balance[msg.sender];
}
function withdraw(uint amount) public onlyOwner returns (uint){
require(balance[msg.sender] >= amount);
balance[msg.sender] = balance[msg.sender].sub(msg.value);
payable(msg.sender).transfer(amount);
return balance[msg.sender];
}
function getBalance() public view returns (uint){
return balance[msg.sender];
}
function contractBalance() public view returns (uint){
return address(this).balance;
}
function transfer(address recipient, uint amount) public {
require(balance[msg.sender] >= amount, "Balance not sufficient");
require(msg.sender != recipient, "Don't transfer money to yourself");
uint previousSenderBalance = balance[msg.sender];
_transfer(msg.sender, recipient, amount);
assert(balance[msg.sender] == previousSenderBalance - amount);
}
function _transfer(address from, address to, uint amount) private {
balance[from] -= amount;
balance[to] += amount;
}
}
I assume for the ETH to move from the contract to the msg.sender address this method
payable(msg.sender).transfer(amount);
is responsible for moving the ETH and the internal balance is handled by the balance mapping
mapping(address => uint) balance;
Correct?
I have a problem though:
Here is the withdrawal function from the bank contract that Filips provided, however without making it payable I get an error :
function withdraw(uint amount) public onlyOwner returns (uint){
require(balance[msg.sender] >= amount);
balance[msg.sender] = balance[msg.sender].sub(msg.value);
payable(msg.sender).transfer(amount);
return balance[msg.sender];
}
This is the error.
TypeError: “msg.value” and “callvalue()” can only be used in payable public functions. Make the function “payable” or use an internal function to avoid this error.
–> Dawie_Laptop/Remix Exercises/BANK 2.0/Bank_Fillip.sol:24:55:
|
24 | balance[msg.sender] = balance[msg.sender].sub(msg.value);
| ^^^^^^^^^
If you have some insight for me I’d much appreciate it. Obviously, this is a fundamental part of Solidity that I want to fully understand.