I want to make a smart contract, where you can instantly swap your Ether to ERC20 token.

What I do have now:

pragma solidity >=0.4.16 <0.7.0;

contract Swap {
    address owner;
    address constant tokenAddress = address(
        0x14eb2ab8e6d09000a98e3166b3cc994375071f69 //ERC20 token address
    uint8[] validTokenAmounts = [2, 16, 32];
    uint256 constant tokenPrice = 75000000000000;

    function isTokenAmountValid(uint8 tokenAmount) private view returns (bool) {
        for (uint8 i; i < validTokenAmounts.length; i++) {
            if (tokenAmount == validTokenAmounts[i]) {
                return true;
        return false;

    function swap(uint8 amount) public payable {
            msg.value >= amount * tokenPrice,
            "You sent incorrect amount of Ether"

        ??transfer()?? // Here I don't know what how to send ERC20 tokens

I have a second question too - how do I deploy contract with XXX amount of ERC20 tokens in smart contract? It's my first time with smart contracts, I hope you will find time to help me.

Thanks :)

  • Does your contract have a balance at token 0x14eb2ab8e6d09000a98e3166b3cc994375071f69? Apr 13, 2020 at 12:23
  • @goodvibration, yes, I want to deploy contract with let's say 10 000 tokens (I don't know how to do it yet, but I'll try). Let's assume that I have those token in contract
    – ethArek
    Apr 13, 2020 at 13:10

1 Answer 1


This contract is what is called "ICO contracts" or Crowdsale contracts in Ethereum language.

To deploy tokens on a contract

  1. Create a token by deploying a contract

  2. Initial token supply is minted on some Ethereum account

  3. You do a normal transfer() of these tokens to the token swap contract

  4. Token swap contract itself can then transfer() right amount of tokens to the purchaser from its internal supply

require(newToken.transferFrom(address(this), whom, amount) == true, "Could not send tokens to the buyer");
  • Thanks for the answer! However I want to make a swap for already existing token.
    – ethArek
    Apr 13, 2020 at 17:23
  • Just transfers tokens you need to swap on the smart contract, you can skip steps 1 and 2. Apr 14, 2020 at 15:51

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.