I am writing a smart contract that allows users to stake ERC20 tokens and get a discount on a product they buy in the store.

At first, the user will transfer tokens to the contract and then based on the amount they transferred, the discount will be calculated and tokens will be staked for some time. I need to find a way to track token amount sent to the contract. Something like msg.tokenValue

How to do something like that?

  • Declare event Event(uint256 amount), and upon transfer, emit Event with the specified amount. Sep 12, 2018 at 14:39

1 Answer 1


You can't, within the transaction that transfers the tokens.

Token transfers will not invoke code within your contract, unlike ether transfers.

Your options are:

  1. Ask the user to transfer the tokens first, then ask them to make another tx to your contract, within which you can call token.balanceOf to check the balance. Note that this will not work if multiple users transfer tokens to a single contract on your side, since you cannot differentiate who sent how much.
  2. Ask the user to approve your contract to withdraw a certain amount of tokens from the user's balance, and then make a tx to your contract. Your contract can then use the token's transferFrom function to move the tokens, and perform some work after that.

If the tokens you care about support approveAndCall, that is also an option you can use to achieve the same effect in a single transaction.

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.