Im trying to pay a contract address through metamask and have it call a buyTokens function but the transactions keep failing. The contract has enough tokens balance because because I sent the ERC20 tokens successfully to the contract address through metamask. It is only when I send ether to the contract address that it fails. I tried with the default gas limmit and tried it with gas set to 200000 in metamask. Please help me.
Im running on genache, local host
pragma solidity ^0.5.0;
import "./Token.sol";
// rate is 1 token = 0.01 ether
contract Crowdsale {
constructor() public {
rate = 100;
on = true;
}
Token public token;
address payable wallet;
uint256 public rate;
bool on;
event TokenPurchase(address recipient, uint256 numPaid, uint256 numTokensPurchased);
function buyTokens() public payable {
require(msg.value > 0 && on == true);
uint256 tokenAmount = _getTokenAmount(msg.value);
require(token.balanceOf(address(this)) >= tokenAmount);
token.transfer(msg.sender, tokenAmount);
emit TokenPurchase( msg.sender, msg.value, tokenAmount);
}
function () external payable{
buyTokens();
}