0

Question: Is it possible to upload tokens on a contract and then distribute it to whoever sends ETH to that contract (not create a token as if it is an ICO, but preload already existing one). For e.g. 10 token x for 1eth?

Also is this the way decentralised exchanges works?

Thanks

1 Answer 1

1

Yes, this is certainly possible. If all goes as planned, we'll publish a blog post on https://programtheblockchain.com next week showing exactly how to do this.

For a simplified, one-off contract, something like this would work:

address owner = msg.sender;
IERC20Token token = IERC20Token(0x...);
uint256 rate = 10;  // 1 wei == 10 token units
function buyTokens() public payable {
    uint256 tokenAmount = msg.value * rate;
    require(token.transferFrom(owner, tokenAmount, msg.sender));
    require(owner.transfer(msg.value));
}

You would need to allow the number of tokens you're selling to this smart contract first.

And yes, this is essentially how decentralized exchanges work.

1
  • snarx, programtheblockchain.com has really high quality content! Thank you, looking forward for a blog post next week!
    – Pandation
    Commented Feb 23, 2018 at 15:23

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.