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?



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));

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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.