Crowdsale contract failing when sending ether to `buyTokens` but the contract can receive ERC20 tokens

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();
    }
1 Like

Hi @John_Bradshaw,

Welcome to the community :wave:

Rather than create your own crowdsale contract you could inherit from OpenZeppelin Contracts. https://docs.openzeppelin.com/contracts/2.x/crowdsales

Please note, Crowdsale contracts have been removed in OpenZeppelin Contracts 3.x.

i tried that but half of the contracts are missing in node modules and on githib for open zeppelin. :frowning :frowning:

1 Like

Hi @John_Bradshaw,

The latest OpenZeppelin v2.x release is v2.5.1

To install OpenZeppelin Contracts 2.x you can specify the version:

npm install @openzeppelin/contracts@2.5.1

To look at the contracts in GitHub you can specify the v2.5.1 release tag: