5
pragma solidity ^0.4.0;

contract exchange {
    mapping (address => uint256) public balances;
    event PaymentDone(string s);

    function Channel( uint value) payable {
        balances[msg.sender] -=value;
        balances[this] +=value;
    }

    function CloseChannel( address to,uint value) {
        if (to.send(value)) {
            PaymentDone("Done");
        }
    }
}
8

Yes. I renamed a lot of stuff while I worked it out.

This contract accepts ETH deposits and keeps track of who deposited. it holds the ETH. Then, it lets the depositors withdraw to themselves, or transfer to someone else. It doesn't let depositors overdraw their accounts.

No testing, so no warranty ;-)

pragma solidity ^0.4.11;

contract Exchange {

    mapping (address => uint256) public balances;

    event LogDeposit(address sender, uint amount);
    event LogWithdrawal(address receiver, uint amount);
    event LogTransfer(address sender, address to, uint amount);

    function deposit() payable returns(bool success) {
        balances[msg.sender] +=msg.value;
        LogDeposit(msg.sender, msg.value);
        return true;
    }

    function withdraw(uint value) returns(bool success) {
        if(balances[msg.sender] < value) throw;
        balances[msg.sender] -= value;
        msg.sender.transfer(value);
        LogWithdrawal(msg.sender, value);
        return true;
    }

    function transfer(address to, uint value) returns(bool success) {
        if(balances[msg.sender] < value) throw;
        balances[msg.sender] -= value;
        to.transfer(value);
        LogTransfer(msg.sender, to, value);
        return true;
    }
}

Almost forgot. To withdraw from the above example, Truffle syntax would look something like:

var exchange;
Exchange.deployed().then(function(instance) { exchange = instance; });

var amount = 10; // for example
exchange.withdraw(amount); // a good start, but look into promises and .then

Hope it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.