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 {
            msg.value == _numberOfTokens * tokenPrice,
            "Number of tokens does not match with the value"
            tokenContract.balanceOf(address(this)) >= _numberOfTokens,
            "Contract does not have enough tokens"
            tokenContract.transfer(msg.sender, _numberOfTokens),
            "Some problem with token transfer"
        tokensSold += _numberOfTokens;
        emit Sell(msg.sender, _numberOfTokens);


    function _forwardFunds() internal {

    function endSale() public {
        require(msg.sender == admin, "Only the admin can call this function");
            "Unable to transfer tokens to admin"
        // destroy contract
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:

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

I have a question about your crowdsale contract. Did you use it in prod? and did you audit it?