DIGVJSS
DIGVJSS

Reputation: 499

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.

Upvotes: 1

Views: 669

Answers (2)

Tim Hysniu
Tim Hysniu

Reputation: 1540

If these are ERC20 tokens then you will need to do the accounting yourself. I would suggest that you have separate contracts handling this.

Here is an example which can be re-purposed to work with your use case.

The idea is to send one ERC20 token to a contract which performs the exchange calculation, and then moves funds from one token to another.

If the exchange rate from DAI to AUD does not fluctuate then you can have this exchange rate as a constant in the contract. Most likely this will fluctuate though, in which case exchanging will be a bit more complicated.

Decentralized exchanges like UniSwap handle the exchanges automatically using an algorithm that uses the available liquidity as input. Doing something like this is a pretty involved process.

The other alternative is you to have an approve function that can be invoked by a specific signer. This signer could be a centralized service that is part of the exchange workflow.

Alternatively you can use oracles to regularly update the exchange rates between two tokens but this is going to cost gas and unless you have a lot of volume might not be the most cost effective option.

Upvotes: 1

DIGVJSS
DIGVJSS

Reputation: 499

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

Upvotes: 1

Related Questions