0

Good night, can anyone write an example contract that does ether transfer from contract to address?

Or preferably from address to address, but within the contract?

I have this:

function () payable {
   //
}

function withdraw () public { msg.sender.transfer (0x4b0897b0513fdc7c541b6d9d7e929c4e5364d2db); }

function deposit (uint256 amount) payable public { require (msg.value == amount); }


Teste remix

but how can I validate this? all the operations I do are always from my address to the contract and never from the contract to my address.

Ismael
  • 30,570
  • 21
  • 53
  • 96
  • Your transfer line is misunderstood. It goes address.transfer(amount). Since msg.sender is a value of type address, you can use the transfer method. The transfer method expects one argument, the amount (in wei) and it can only be drawn from the contract's funds on hand. – Rob Hitchens May 30 '18 at 03:07

1 Answers1

0

Contracts are limited to sending funds actually "in" the contract and there is no way to program a contract to spend from another wallet.

Try this.

pragma solidity ^0.4.21;

contract PiggyBank {

    address public owner;

    event LogDeposit(address sender, uint amount);
    event LogWithdrawal(address sender, uint amount);

    function PiggyBank() public {
        owner = msg.sender; // only the owner will be permitted to withdraw funds
    }

    function deposit() public payable returns(bool success) {
        emit LogDeposit(msg.sender, msg.value);
        return true;
    }

    /**
     * This is NOT needed, but for learning purposes, a convenience ... 
     * Anyone can check the balance at any address at any time, without this assistance.
     */
    function getBalance() public view returns(uint balance) {
        return address(this).balance;
    }

    function withdraw(uint amount) public returns(bool success) {
        require(msg.sender==owner);
        emit LogWithdrawal(msg.sender, amount);
        msg.sender.transfer(amount);
        return true;
    }

}

Hope it helps.

Rob Hitchens
  • 55,151
  • 11
  • 89
  • 145