Search code examples
blockchainethereumsolidityether

Exchange ERC20 token with other ERC20 token


I have 2 ERC20 tokens. The contract are designed as standard ERC20. Here are the 2 tokens to take as an example -

AUDC --> Contract address: (0xContractAUDC)
         Wallet Address:   (0xWalletAUDC)
DAI  --> Contract address: (0xContractDAI)
         Wallet Address:   (0xWalletDAI)

I want to transfer some DAI from wallet 0xWalletDAI to 0xWalletAUDC to receive converted AUDC in return (I have private keys of both the wallets).

Looking for some help to know how this can be implemented. I would try to be helpful with more information if needed.

I am using ethers.js v4.0 to interact with blockchain.


Solution

  • I found out the solution to implement this using ethers.js -

    const ethers = require('ethers');
    
    let provider = ethers.getDefaultProvider();
    
    // WALLETS
    const DAIUserWalletObj = new ethers.Wallet(DAIUserPrivateKey, provider);
    const AUDCWalletObj = new ethers.Wallet(AUDCPrivateKey, provider);
    
    //CONTRACTS
    const contractDAI = new ethers.Contract(DAIContractAddress, DAIContractABI, provider);
    constractDAI = contractDAI.connect(DAIUserWalletObj);
    const contractAUDC = new ethers.Contract(AUDCContractAddress, AUDCContractABI, provider);
    contractAUDC = contractAUDC.connect(AUDCWalletObj);
    
    let overRide = { gasLimit: 7500000 }
    let numDAITokens = 20;  // Just for example
    let numOfAUDCTokens = 40; // Just for example
    const receipt1 = await contractDAI.transfer(AUDCContractAddress, numDAITokens, overRide);
    const receipt2 = await contractAUDC.transfer(DAIUserWalletAddress, numOfAUDCTokens, overRide);
    console.log(receipt1);
    console.log(receipt2);