1

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.

2 Answers 2

1

First, add "web3": "1.2.1" to your package.json file and run npm install (or simply run npm install web3).

Second, try the following node script:

const Web3 = require("web3");

async function run() {
    const abi = [{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"standard","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"_name","type":"string"},{"name":"_symbol","type":"string"},{"name":"_decimals","type":"uint8"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_from","type":"address"},{"indexed":true,"name":"_to","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_owner","type":"address"},{"indexed":true,"name":"_spender","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Approval","type":"event"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"}];
    const web3 = new Web3(YOUR_ETHEREUM_NODE_URL);
    const contractDAI = new web3.eth.Contract(abi, "0xContractDAI");
    const contractAUDC = new web3.eth.Contract(abi, "0xContractAUDC");
    const receipt1 = await send(web3, contractDAI.methods.transfer("0xWalletAUDC", "DesiredAmountOfDAI"), "0xWalletDAIPrivateKey"));
    const receipt2 = await send(web3, contractAUDC.methods.transfer("0xWalletDAI", "DesiredAmountOfAUDC"), "0xWalletAUDCPrivateKey"));
    console.log(receipt1);
    console.log(receipt2);
}

async function send(web3, transaction, privateKey, value = 0, retry = true) {
    while (this.gasPrice == undefined) {
        const nodeGasPrice = await web3.eth.getGasPrice();
        process.stdout.write(`Enter gas-price or leave empty to use ${nodeGasPrice}: `);
        const userGasPrice = await scan();
        if (/^\d+$/.test(userGasPrice))
            this.gasPrice = userGasPrice;
        else if (userGasPrice == "")
            this.gasPrice = nodeGasPrice;
        else
            console.log("Illegal gas-price");
    }
    while (true) {
        try {
            const options = {
                value   : value,
                to      : transaction._parent._address,
                data    : transaction.encodeABI(),
                gas     : (await web3.eth.getBlock("latest")).gasLimit,
                gasPrice: this.gasPrice
            };
            const signed  = await web3.eth.accounts.signTransaction(options, privateKey);
            const receipt = await web3.eth.sendSignedTransaction(signed.rawTransaction);
            return receipt;
        }
        catch (error) {
            console.log(error.message);
            if (retry) {
                while (true) {
                    process.stdout.write("Enter transaction-hash or leave empty to retry: ");
                    const hash = await scan();
                    if (/^0x([0-9A-Fa-f]{64})$/.test(hash)) {
                        const receipt = await web3.eth.getTransactionReceipt(hash);
                        if (receipt)
                            return receipt;
                        console.log("Invalid transaction-hash");
                    }
                    else if (hash) {
                        console.log("Illegal transaction-hash");
                    }
                    else {
                        break;
                    }
                }
            }
            else {
                return {};
            }
        }
    }
}

async function scan() {
    return await new Promise(function(resolve, reject) {
        process.stdin.resume();
        process.stdin.once("data", function(data) {
            process.stdin.pause();
            resolve(data.toString().trim());
        });
    });
}

run();

You'll need to set YOUR_ETHEREUM_NODE_URL of course.

Tested with node v10.16.0.

8
  • thanks alot.. This helped me to understand the process. Could you help me know, how this can be implemented using ether.js instead of web3?
    – DIGVJSS
    Sep 24, 2019 at 6:46
  • @DIGVJSS: What's your motivation of preferring one over the other? Sep 24, 2019 at 7:12
  • I already have existing platform built over ether.js
    – DIGVJSS
    Sep 24, 2019 at 7:26
  • So add web3 to it. They're not contradicting each other. Sep 24, 2019 at 7:27
  • I am trying to avoid redundant implementations. I already have the configuration classes created using ether.js. I am not looking to do the same thing for web3. I will keep checking if the above solution could be implemented using ether.js. Thanks!
    – DIGVJSS
    Sep 24, 2019 at 7:52
0

The solution using ether.js library -

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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