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.
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.
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
transferFrom methods in the ERC20 standard are designed for cases like this.