How to auto transfer funds to a beneficiary(admin) on every tx in crowdsale contract

I am trying to use the “forwardFunds()” function to automatically transfer ETH contributed to the admin wallet address “contract deploying address” upon sending the tokens to the buyer but it is failing. Why @abcoathup and please give me a sample code correcting my mistake. Thanks in Advance.

Here is my crowdsale contract.

pragma solidity ^0.5.0;

import "./sampleToken.sol";

contract sampleTokenSale {
    address payable admin;
    sampleToken public tokenContract;
    uint256 public tokenPrice;
    uint256 public tokensSold;

    event Sell(address _buyer, uint256 _amount);

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

    function buyTokens(uint256 _numberOfTokens) public payable {
        require(
            msg.value == _numberOfTokens * tokenPrice,
            "Number of tokens does not match with the value"
        );
        require(
            tokenContract.balanceOf(address(this)) >= _numberOfTokens,
            "Contract does not have enough tokens"
        );
        require(
            tokenContract.transfer(msg.sender, _numberOfTokens),
            "Some problem with token transfer"
        );
        tokensSold += _numberOfTokens;
        emit Sell(msg.sender, _numberOfTokens);

        _forwardFunds();
        _postValidatePurchase(admin);
    }

    function _forwardFunds() internal {
    admin.transfer(msg.value);
  }

    function endSale() public {
        require(msg.sender == admin, "Only the admin can call this function");
        require(
            tokenContract.transfer(
                msg.sender,
                tokenContract.balanceOf(address(this))
            ),
            "Unable to transfer tokens to admin"
        );
        // destroy contract
        selfdestruct(admin);
    }
}
1 Like

Hi @defi,

I am not sure why your code is failing. You may want to use a Crowdsale from OpenZeppelin Contracts 2.x rather than create your own: https://docs.openzeppelin.com/contracts/2.x/crowdsales

As an aside, I suggest looking at: Points to consider when creating a fungible token (ERC20, ERC777)

Thanks @abcoathup for the reply. My contract code worked, I was just refreshing the browser to see the results.

1 Like