Hi I have a token that I am trying to use as payment for a smart contract and to pay out. How can I do that in solidity where payment is not ether but rather my token?


For a smart contract to receive tokens and know that the tokens have been received, you need a two step process.

  1. myToken.approve(receivingContractAddress, numberOfTokens)
  2. receivingContract.receive(numberOfTokens)

    This function then calls myToken.transferFrom(msg.sender, receivingContractAddress, numberOfTokens) to receive the tokens from the sender.

This is the method used in the TokenTrader on https://cryptoderivatives.market where the TokenTrader contract can buy tokens using the following function from https://github.com/bokkypoobah/TokenTrader/blob/master/contracts/TokenTraderFactory.sol#L286-L321 :

// Taker sells asset tokens for ethers by:
// 1. Calling the asset's approve() method with the following parameters
//    _spender            is the address of this contract
//    _value              is the number of tokens to be sold
// 2. Calling this takerSellAsset() method with the following parameter
//    etherValueOfTokens  is the ether value of the asset tokens to be sold
//                        by the taker
// The TakerSoldAsset() event is logged with the following parameters
//   seller                  is the seller's address
//   amountOfTokensToSell    is the amount of the asset tokens being
//                           sold by the taker
//   tokensSold              is the number of the asset tokens sold
//   etherValueOfTokensSold  is the ether value of the asset tokens sold
// This method was called sell() in the old version
function takerSellAsset(uint256 amountOfTokensToSell) {
    if (buysTokens || msg.sender == owner) {
        // Maximum number of token the contract can buy
        // Note that buyPrice has already been validated as > 0
        uint256 can_buy = this.balance / buyPrice;
        // Token lots available
        // Note that units has already been validated as > 0
        uint256 order = amountOfTokensToSell / units;
        // Adjust order for funds available
        if (order > can_buy) order = can_buy;
        if (order > 0) {
            // Extract user tokens
            if (!ERC20(asset).transferFrom(msg.sender, address(this), order * units)) throw;
            // Pay user
            if (!msg.sender.send(order * buyPrice)) throw;
        TakerSoldAsset(msg.sender, amountOfTokensToSell, order * units, order * buyPrice);

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.