I'm trying to deploy a smart contract that allows users to buy tokens that can be used to pay fees on its platform.

In case someone is going to send ETH directly to the contract address without calling a public function I want to provide a fallback that automatically buys tokens by calculating the amount from the value sent by the user.

The code is as follows.

pragma solidity >=0.4.22 <0.9.0;

import "./BEP20Token.sol";

contract DappTokenSale {
    address payable admin;
    BEP20Token public tokenContract;
    uint256 public tokenPrice;
    uint256 public tokensSold;

    event Sell(address _buyer, uint256 _amount);

    constructor (BEP20Token _tokenContract, uint256 _tokenPrice) public {
        admin = msg.sender;
        tokenContract = _tokenContract;
        tokenPrice = _tokenPrice;

    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        // Solidity only automatically asserts when (div)iding by 0
        require(b > 0, errorMessage);
        uint256 c = a / b;
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold

        return c;

    function multiply(uint x, uint y) internal pure returns (uint z) {
        require(y == 0 || (z = x * y) / y == x);

    function buyTokens(uint256 _numberOfTokens) public payable {
        require(msg.value == multiply(_numberOfTokens, tokenPrice));
        require(tokenContract.balanceOf(address(this)) >= _numberOfTokens);
        require(tokenContract.transfer(msg.sender, _numberOfTokens));

        tokensSold += _numberOfTokens;

        emit Sell(msg.sender, _numberOfTokens);

    function() external payable { 
        uint256 _numberOfTokens = div(msg.value, tokenPrice, 'Division by zero');

If I send ether to the contract deployed on Ganache I receive the following error:

Error while formatting outputs from RPC '{"value":{"code":-32603,"data":{"message":"VM Exception while processing transaction: revert","code":-32000,"data":{"0x4ac3ca04afe9549e2576c012ed81b8414d92c2b19ec8365c1d52ef31275a7d15":{"error":"revert","program_counter":720,"return":"0x"}

I have almost zero experience with solidity but I guess the fallback function doesn't get called and Ganache throws an error and reverts.

I tried to use the newer fallback syntax. fallback() external payable {...} but get a compile error ParserError: Expected identifier but got '('.

The solidity version being used by truffle is 0.5.0.

1 Answer 1


You are missing the fallback function. Solidity 0.5 the fallback function was a function without a name.

contract Test {
    event Payment(address sender, uint amount)

    // Fallback function solc v0.5 style
    function() external payable {
        emit Payment(msg.sender, msg.value);

Your Answer

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

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