Search code examples
ethereumblockchainsoliditysmartcontractschainlink

Allowance failed when attempting to transfer LINK tokens


I'm creating a smart contract where users can create NFT raffles. I will be using Chainlink VRF for getting provably fair results. For this, the user who creates the raffle needs to supply the contract with LINK tokens. I'm attempting to transfer these tokens using an allowance.

  function initRaffle(address _tokenContract, uint256 _tokenId, uint256 _ticketPrice) external {
      require(_ticketPrice > 0, "Ticket price must be bigger than 0");
      require(LINKToken.balanceOf(msg.sender) >= ChainlinkFee, "Insufficient LINK supplied");
      require(LINKToken.allowance(msg.sender, address(this)) >= ChainlinkFee, "Allowance failed");

Running initRaffle results in Allowance failed. I've checked and the LINKToken.balanceOf(msg.sender) is bigger than the fee, so that shouldn't be the problem. The LINKToken.balanceOf(address(this)) is 0.

What's going wrong? And how do I create a working function for having the user transfer (fee amount) link tokens to the contract.


Solution

  • The user needs to invoke approve(yourContractAddress, feeAmount) directly on the LINKToken contract (not through your contract). This sets the allowance.

    You can then use transferFrom() to pull tokens (up to the allowed amount) from the user's wallet.

    bool success = LINKToken.transferFrom(msg.sender, address(this), ChainlinkFee);