11

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

13

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. } 
2
  • Your buy() function needs a parameter uint256 amount. Commented Sep 10, 2022 at 23:33
  • is it address(this) instead of this? Commented Apr 2, 2023 at 14:39

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.