When a method is payable, it's possible to send ether to the contract while calling it, and the function can check the amount sent through msg.value.

How can I make a function receive something other than ether, such as an ERC20 token?

1 Answer 1


An ERC20 token is just another contract. The ERC20 standard gives you two functions that work together to help pay a contract: approve() and transferFrom().

If the token contract is called "token" and the contract you're trying to pay is called "store", the process looks like this:

  1. The user calls token.approve(store, amount); This gives store permission to transfer amount of the user's tokens.
  2. The user calls store.buy();, which calls token.transferFrom() to perform the actual transfer.

The buy() function might look like this:

function buy() external {
    require(token.transferFrom(msg.sender, this, amount));
    // having now received <amount> tokens from the sender, deliver whatever was
    // purchased, etc.
  • Your buy() function needs a parameter uint256 amount. Commented Sep 10, 2022 at 23:33
  • is it address(this) instead of this?
    – anniex
    Commented Apr 2, 2023 at 14:39

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.