I've made an ERC20 token (TaylorSwiftCoin, aka SWFT), and I'm attempting to make a very basic smart contract. I'm running this on the Dune TestNet, and I simply want this smart contract to take 100 of these SWFT coins, and in return, display a message (this is just as a proof of concept for a project).
My code is as follows:
pragma solidity ^0.8.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol";
contract PurchaseTicket {
IERC20 public constant token = IERC20(0xfd3a409a40A00E99AAbE072e304a540aa25Fd4e9);
uint256 public constant ticketPrice = 100;
string public constant successMessage = "Transaction successful. The following is your ticket number: 34824312.";
address public owner;
constructor() {
owner = msg.sender;
}
function purchase() public payable returns (string memory) {
require(token.transferFrom(msg.sender, address(this), ticketPrice), "Token transfer failed.");
return successMessage;
}
function withdrawTokens() public payable {
require(msg.sender == owner, "Only the owner can withdraw tokens.");
uint256 contractBalance = token.balanceOf(address(this));
require(token.transfer(owner, contractBalance), "Token withdrawal failed.");
}
}
The problem is that the purchase() function always gives this error:
Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending? Returned error: {"jsonrpc":"2.0","error":"Execution reverted","id":422342247361384}
and if I force send the transaction, I get the error: false Transaction mined but execution failed.
The withdrawTokens() function works however, and gives no such error. And I have been approving the contract using the ERC20 token's approve() function.
Does anyone have any insight into why this is happening, and if so, how to fix it?
require(token.allowance(msg.sender, address(this)) >= ticketPrice)