I want to implement something like this: Test conditions for making ethers transfers between accounts. 3 accounts
I am having difficulty with the transfer functions.
I want to implement something like this: Test conditions for making ethers transfers between accounts. 3 accounts
I am having difficulty with the transfer functions.
To send Ether in solidity, you just need to do:
recipient.transfer(amount);
Where recipient is a variable of type address. Notice that this can be both an externally-owned account (normally a human being) or a smart contract.
For instance, to send money from the contract balance to the sender of the transaction, you do:
msg.sender.transfer(amount);
Where msg.sender is poly filled by solidity and it's the account which signed the transaction sent to the contract.
You can read more about this in the docs:
There is no way to write a contract to spend from someone else's account. A contract can receive funds, hold funds, account for funds and send funds.
An ATM is possibly the simplest scaffold to think about. "Clients" can deposit and withdraw funds. The funds "mingle" inside the ATM where there is one grand total (funds on hand a.k.a. address(this).balance). The ATM's job is to handle accounting so it releases all the money owed to individuals but no more than it should.
pragma solidity 0.4.25;
contract ATM {
mapping(address => uint) public balances; // balances of all users
event LogDeposit(address sender, uint amount);
event LogWithdrawal(address receiver, uint amount);
// send money to the contract
function depositFunds() public payable returns(bool success) { // we accept all funds
require(msg.value > 0); // needs to make sense
balances[msg.sender] += msg.value; // credit the sender account
emit LogDeposit(msg.sender, msg.value); // emit event
return true; // return success
}
// take money from the contract
function withdrawFunds(uint amount) public returns(bool success) {
require(amount > 0); // needs to make sense
require(balances[msg.sender] >= amount); // requester is owed money?
balances[msg.sender] -= amount; // debit requester account
emit LogWithdrawal(msg.sender, amount); // emit event
msg.sender.transfer(amount); // send funds
return true; // return success
}
}
In case it isn't clear, the public mapping means that anyone can check the balance owed to any address. This means Alice and Bob can check the funds held by the contract. They can use the withdrawFunds() function to pull their funds out.
In the case that you want a contract to mediate trade between Alice and Bob, you need Alice and Bob to transfer assets into the safe-keeping of the contract. Then, when triggering events happen, update internal accounting. For technical reasons, it's generally best to use a "withdrawal pattern" as in the ATM example. Alice and Bob would interact with the contract to request their funds if they want to remove them from the contract.
Hope it helps.
reverterrors? – Paul Razvan Berg Nov 23 '18 at 21:19