I need some help to try to fix this issue. I'm building a lottery contract that uses a ERC20 created token and i get that error once i try to execute the BuyTicket function. This is all the changes i had made but i keep getting that error.

address public tokenAddress; //Custom Token Address


constructor(address payable _token) {
    lotteryOperator = msg.sender;
    expiration = block.timestamp + duration;
    tokenAddress = _token;
    lotteryId = 1;


function BuyTickets() public payable {

        msg.value % ticketPrice == 0,
            "the value must be multiple of ",
            " Ether"

    uint256 numOfTicketsToBuy = msg.value / ticketPrice;


    IERC20(tokenAddress).approve(msg.sender, numOfTicketsToBuy);
    IERC20(tokenAddress).transferFrom(msg.sender, address(this), numOfTicketsToBuy);


        numOfTicketsToBuy <= RemainingTickets(),
        "Not enough tickets available."

    for (uint256 i = 0; i < numOfTicketsToBuy; i++) {

I get that error when it calls the IERC20.


1 Answer 1



I think is worth looking at the ERC20 part. If my understanding of the flow is correct, your contract receives ether from a buyer and send tickets (ERC20) to the buyer.

this lines:

1- IERC20(tokenAddress).approve(msg.sender, numOfTicketsToBuy);
2- IERC20(tokenAddress).transferFrom(msg.sender, address(this), numOfTicketsToBuy);

actually are doing the following:

1- The contract approves the msg.sender, (the buyer) to transfer on behalf of the lottery contract the number of tokens required

2- The contract tries to transfer from the user to the contract the number of tokens.

Besides that, if you want to transfer tokens to the user, the contract must have tokens; I think two ways of doing this are mixed.

On the one hand, you would use line Nr 1 if you ask your buyer to transfer the tokens to him, (it means he will have to call the ERC20 contract directly), and in this case, you don't need the second line.

On the other, if you want to transfer the tokens directly to the buyer, you don't need to approve the user (you don't need then line 1) and you would change the second line to direct transfer, something like this:

  1- IERC20(tokenAddress).transfer(msg.sender, numOfTicketsToBuy);

Hope it helps!

  • Hi, thanks for your answer but i think i didn't cleared out correctly the problem. I have a lottery contract where i want the player to use my token to buy tickets. By default is uses native chain token, in this case is BNB. I want it to use my token instead of BNB.
    – katano
    Jan 15 at 14:54
  • ok, understood. then in this case the user should approve the contract in a first separate transaction and then the contract can do the transferFrom()
    – donoso.eth
    Jan 15 at 17:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.