4

Is there any way for a contract to know when it gets sent a token? Does it help if it knows the address of the token? I'm making a contract that's meant to divvy up tokens among a group of people as they come in, and I'm wondering if that's possible or if it's something that'll have to be triggered remotely.

3

Conventionally a call to a token following the token API is a call against the token contract and not the token-owning contract, so you can't hook a function into it in the way that you can when your contract receives ETH. If you're in control of the token code you could put an extra callback in it, but obviously that's not an option if it's somebody else's token, and your users want to use the original token's address. (If they're happy paying the address you specify then you may be able to wrap the original token in a proxy token, but see below for why this may still not be the best strategy).

However, the token API does call for a Transfer event containing your contract's address when your contract is credited with funds, so you could make a daemon process outside Ethereum and have it listen for the event and fire off a transaction to your contract. This may sometimes actually be the right way to handle ETH receipts as well, as especially since the DAO debacle, "sending someone money someone runs their arbitrary code on your execution stack" is looking like a security anti-pattern, and people try to avoid it by forwarding too little gas to do anything except log an event.

For similar reasons if the goal is to divvy up the money received by a contract among multiple people, you may be better off following the withdrawal pattern, where you simply keep track of how much of the balance of each token held by the contract is owed to each person, and they each call their own transactions against your contract to withdraw the tokens it controls on their behalf. See this example in the Solidity docs for an example of the withdrawal pattern.

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.