1

I'm looking into writing a contract that can accept an (unknown in advance) ERC20 tokens, from several different users. Is there a way to detect, or at least verify, that a user has deposited the token with my contract?

2

See TokenTraderFactory.sol#L286-L321 where the function takerSellAsset(...) is used for a user to send their tokens to the TokenTrader contract:

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);
    }
}

This is one of the three contracts behind https://cryptoderivatives.market/ .

A Maker calls the TokenTraderFactory to creates a TokenTrader contract. The Maker can then deposit tokens with the TokenTrader contract to sell to a buyer (Taker). The maker can also deposit ethers with the TokenTrader contract to buy tokens from a seller (Taker).

For a Taker to sell their tokens to the Maker's contract, the Taker will have to call the token contracts approve(...) function to approve the transfer of the tokens to the TokenTrader contract. The Taker then calls the TokenTrader's takerSellAsset(...) function and this will call the token contract's transferFrom(...) function to move the tokens from the Taker to the TokenTrader address.

A user could just call the token contract's transfer(...) function to transfer their tokens to your contract, but there is no automated way to detect that this has been done from within your contract, and to determine what the source of the token is.

0

Found the answer to my question: ERC20 defines the approve function that allows users to pre-approve a 3rd party (in this case, my contract) to spend funds using transferFund.

Therefore, one can define on their contract a method of the following form:

// Allows a user to pay this contract in tokens. User must call the approve method on the token contract first.
function contribute(int256 howMuch) {
  bool success =  (ERC20TokenContract.trasferFrom(msg.sender, this.address, howMuch));
  // ...
}

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.