[Ethereum] how to send back token after received some eth

contract-deploymentcontract-designcontract-invocation

how to add this functionality into a token contract?
Function : whenever anyone sends any Ethereum to my contract address, any number more than 0 (even an amount like 0.000000001), I would like to send them back 1000 of my tokens, and send eth that can be contracted to a certain address?

Example contract like this : https://etherscan.io/address/0x55732acec59699e28bad93522684e0d241a64a35

thanks

Best Answer

One of the best prototypes of ERC20 token implementation is the OpenZeppelin's ERC20 implementation.

Follow it's guidelines and you'll archive to do it.

Related with your problem, the error that gives the other answer comes from the ERC20 implementation , if You've overridden the transfer() method and set only one parameter, you won't be able to do it.

Another problem is that msg.value is in wei, so as fas as a wei is indivisible, that may be causing errors too.

So doing it fast it'll be something like that:

contract MyToken {
    // ERC20 token implementation
}

contract SomeContract {
    address tokenAddress;
    MyToken token;
    token.approve(this( which is adress of SomeContract), X amount of tokens is able to donate has to be more than 1000 that is what you send)

    // Run this first, to tell the contract the address 
    // of your token smart contract
    function setTokenAddress(address _tokenAddress) public {
        tokenAddress = _tokenAddress;
        token = MyToken(_tokenAddress);
    }

    function GiveMeTokens() public payable {
        if (msg.value > 1) {
            token.transfer(msg.sender, 1000);
        }
    }
}

Use a standard ERC20 implementation and try again your method.

Related Topic