[Ethereum] token sell and buy prices

contract-designcontract-development

Hi for a while now i have been testing ethereum capabilities and there is something i wanted to test and i cant figure how to do. When creating a contract of a custom token (using the code given in the ethereum official site) there is a sell price to set and a buy price for a token, in what way can i use this to give a token sell price of another token?

What I mean is, is there a way to give token A price in token B? essentialy making it possible to a user who have Token B to buy token A? and could a contract hold more than 1 kind of a token? like a contract that holds both token A and B? and maybe even more?

Best Answer

The Token contract has a function that allows the token owner to approve an address for a certain amount. This other address will be able to send up to this amount of the approver's tokens:

function approve(address _spender, uint256 _value) {}

So let's say you have 2 people Alice and Bob. Alice has 3 TokenA and Bob has 4 TokenB. They agree to exchange them. You create the re-usable Trade contract to make that happen.

contract Trade {
    function exchange(address alice, 
                    address tokenA,
                    uint qtyTokenA,
                    address bob,
                    address tokenB,
                    uint qtyTokenB) 
        returns (bool success) {
        success = Token(tokenA).transferFrom(alice, bob, qtyTokenA)
            && Token(tokenB).transferFrom(bob, alice, qtyTokenB);
        if (!success) throw;
    }
}

In TokenA, Alice approves the trade contract for 3. In TokenB, Bob approves the trade contract for 4. Then someone calls the exchange function with the proper values.

I understand that, as it stands, there is a security risk whereby Carol calls the method before others, to steal from Alice. IRL, you would have Alice and Bob to both approve the exchange function call.

Related Topic