function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
    allowed[msg.sender][_spender] = _value;
    Approval(msg.sender, _spender, _value);

    if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
    return true;

What does if condition do? What is the use of bytes4, byte32 and _spender.call?

  • bytes4 is the 32-bit Solidity function signature for receiveApproval(address,uint256,address,bytes)

  • This calls the function receiveApproval() in the target address. If the target address does not have this function the condition ensures the transaction fails - this the approveAndCall can only call contracts with receiveApproval() interface - not normal Ethereum accounts or incompatible smart contract

  • extraData can pass context information to the target contract what this call is about


The main use is to call a smart contract and let it know you are sending tokens. This is because in general a smart contract will not be triggered when ERC20 tokens are sent to it (transferring tokens is just a change in the balance of the token contract).

To let a contract know you approve a number of tokens for it and then call a function in it. The target contract will respond by using transferFrom to get the tokens and attention your call.

In general this will be the way to, for instance, exchange tokens for a service (swap tokens, buy products, etc.)

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.