2

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

How can I make a function receive something else than ether, for example an ERC20 token?

2

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 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.