1

Is there a way to detect when my contract receive tokens? I don’t own the token contract, I only want to know the address and amount of token sent to my contract.

1 Answer 1

3

If you know which token your contract expects to receive, you can listen for a Transfer event issued by the token contract. (Not your contract!)

The standard ERC20 Transfer event looks like this:

event Transfer(address indexed _from, address indexed _to, uint _value);

...so listen to the token contract for an event where _to is the address of your contract.

If you don't have a specific contract in mind and you want to know when ownership of any token is transferred to your contract, you would theoretically need to listen for any Transfer event from any contract on the blockchain with your contract's address in the _to field. Unfortunately the available tools will mostly assume that you want to listen to the events of a particular contract, so this may be difficult to do in practice.

The above approach only works for a process outside the blockchain, that is able to listen for logs. Most commonly this would be JavaScript code using the watch and listen functions in web3.js. If you want your Solidity contract code to respond to an ERC 20 transfer then you're probably out of luck; A standard ERC20 token won't call your contract's code for you in the way that a normal ETH transfer would. In theory you might be able to incentivize someone to listen for the events and send a transaction to relay that information to your contract, possibly with a merkle proof to show that they really saw what they are suggesting in the logs, but this wouldn't be trivial to do. Alternatively you may be able to set up a workflow such that the user calls your contract to make the transaction happen, and your contract in turn calls the token contract; That way your contract knows about the transfer because it directed the transfer itself. The approve and transferFrom methods in the ERC20 standard are designed for cases like this.

2
  • Thank you for your answer. That was what I thought. Unfortunately, I want the contract to be completely decentralized and the token contract didn’t implement approve. Commented Jul 24, 2017 at 11:25
  • One more option might be to wrap the original token contract with a more advanced proxy contract that implements approve, or other code you need. However, you'd have to get your users using your proxy contract. Commented Jul 24, 2017 at 11:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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