is there a contract example which allows to exchange one erc20 for another?

i have 2 tokens

i want to exchange from tokenA to tokenB 1:1 and keep 1% as a fee

the sender should just make a normal erc20-send to the contracts address and receive back the other token.

the contract will have a pool of tokens, A and B

if someone pays 1 tokenA to the contract, the contract should send 0.99 tokenB back to the sending address and keep 0.01 tokenA in the pool.

i saw uniswap is doing something like this but with variable rates and more complex.

please point me to an example of such a contract or even point me to some good solidity programmer who could make this for me.

thanks for your time

1 Answer 1


It is fairly easy if you assume some simplifications:

  • both tokens have the same decimals
  • no error checking
  • Swap contract have enough funds of tokenB
function swapA(uint256 amountA) {

    // Tranfer tokens from sender to this contract
    tokenA.transferFrom(msg.sender, address(this), amountA);

    // Calculate fees
    uint256 fee = amountA / 100;
    uint256 amountB = amountA - fee;

    // Transfer amount minus fees to sender
    tokenB.transfer(msg.sender, amountB);
  • wow thank you, thats already a nice starting place. Sep 23, 2019 at 8:13

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.