I am trying to develop forsage like MLM using ethereum smart contract. But I like to use ERC20 token for registration payment and dividends. The ERC20 token is already deployed. I have to use deployed ERC20 token in MLM smart contract for registration payment and dividends. If we are using ether instead of token, we can use payable for registration payment and address.transfer method for sending dividends. How to do the same for ERC20. For example in case of ether, the registration payment will be like,

function registration(address referrerAddress) private {
    require(msg.value == 0.05 ether, "registration cost 0.05");

Suppose I am expecting 5 token as registration fee, how to write this logic. We can send ether to receiver like,


How to do the same in case of ERC20 token.

2 Answers 2


Change this:

function registration() private {
    require(msg.value == 0.05 ether, "registration cost 0.05");

To this:

function registration() private {
    require(erc20Token.allowance(msg.sender, address(this)) >= X, "registration cost X");
    require(erc20Token.transferFrom(msg.sender, address(this), X));

Where X is the desired registration amount of tokens in decimal resolution (for example, if your token decimals is 8 and the desired registration amount is 0.05 tokens, then the value of X should be 5000000).

You can even get rid of the first line (calling allowance), and it will still work the same way, except for reverting with a different error-message upon failure.

  • You beat me to it :) But your answer is missing information about calling approve Dec 2, 2020 at 19:32
  • @LauriPeltonen: Yeah I did :) ... Was intending that part though, but I guess it has slipped my mind at some point... Dec 2, 2020 at 19:34

The general problem is that the receiver has no way of knowing when it has received tokens so it can't perform any action when it receives tokens.

This is why there are two extra functions in the ERC20 standard: approve and transferFrom. Assuming that A is the user with the tokens, B is the contract which should get the tokens and T is the token contract, here's how you use them in your scenario:

  1. A calls T's approve function, giving B as the receiver. This gives allowance for B to get certain amount of tokens from A.

  2. A calls some function in B, such as getMyTokens. This function calls T's transferFrom function to get the tokens from A. Once this succeeds, the same function can do extra logic.

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.