1

I have this function.I want to perform swap 3 times with the interval of 30 second using swapExactTokenForTokens.But only only one transaction get success.Others failing. Here is my Code.



const erc20ABI = ["function decimals() public view returns (uint8)",
                    "function approve(address spender, uint rawAmount) external returns (bool)",
                    "function name() view returns (string)",
                    "function symbol() view returns (string)",
                    "function balanceOf(address) view returns (uint)"];

const routerABI = ["function getAmountsOut(uint amountIn, address[] memory path) public view returns (uint[] memory amounts)", 
                    "function swapExactTokensForTokens(uint amountIn, uint amountInMin,address[] calldata path,address to,uint deadline) external returns (uint[] memory amounts)",
                    "function getAmountsIn(uint amountOut, address[] memory path) public view returns (uint[] memory amounts)"];


const routerAddress = "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D";//uniswap router address
const WETHAddress = "0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6"; //WETH
const myTokenAddress = "0x1f9840a85d5af5bf1d1762f925bdaddc4201f984";//UNI

const providerAddress = "-------------";

const privateKey = "--------------------------";

const provider = new ethers.providers.JsonRpcProvider(providerAddress);
wallet = new ethers.Wallet(privateKey, provider)
const signer = wallet.connect(provider);

const routerInstance = new ethers.Contract(routerAddress, routerABI, signer);
const token1 = new ethers.Contract(myTokenAddress, erc20ABI, signer);
const token2 = new ethers.Contract(WETHAddress, erc20ABI, signer);

const TokenSwap = async(amount, myTokenAddress, WETHAddress) => {
    const decimal1 = await token1.decimals()
    const decimal2 = await token2.decimals()

    const amountIn = ethers.utils.parseUnits(amount, decimal1).toString();

    const amountInMin = [0,0];
    const amountOutMin = ethers.utils.parseUnits(Number((ethers.utils.formatUnits(amountInMin[1],18)) - 0.1).toString(),18);
    const tx = await routerInstance.swapExactTokensForTokens(
        amountIn,
        amountInMin[0].toString(),
        [myTokenAddress, WETHAddress],
        wallet.address,
        Date.now() + 1000 * 60 * 5,
    )
    
    tx.wait();//
    console.log(tx.hash)


}

for (i=0; i<3;i++){
    amount = '0.1'
TokenSwap(amount, myTokenAddress, WETHAddress)
}

One of them is in success state and other 2 getting failed.Can you help me to solve this issue

Goerli Testnet

0x1191f08fdb2b66008c64d9a8b93fead591085dd5a7e4e8f40f05353a04bca535 0xe9e2161eeffc33ae55021ede873dbadd14b28deafbe3c4bae5076a76f4d18991 0xfcc8952d8ef55b62700e6f0ca8c18882f154e89ecc596009babe8b91b285d7f7

Also I have done approve correctly.

Error:

D:\blockchain\CLI\node_modules\@ethersproject\logger\lib\index.js:199
        var error = new Error(message);
                    ^

Error: nonce has already been used (error={"reason":"processing response error","code":"SERVER_ERROR","body":"{\"jsonrpc\":\"2.0\",\"id\":89,\"error\":{\"code\":-32000,\"message\":\"nonce too low: next nonce 337, tx nonce 336\"}}\n","error":{"code":-32000},"requestBody":"{\"method\":\"eth_sendRawTransaction\",\"params\":[\"0x02f8b105820150849502f900849502f90e82729794b4fbf271143f4fbf7b91a5ded31805e42b2208d680b844095ea7b300000000000000000000000093127808fb485f3725a3e11ba269038973f1d730000000000000000000000000000000000000000000000000016345785d8a0000c001a08ca082fa873ebf86a17e8754d5944b6f4a47ec05b2b9fdf5e2068a7a72835832a06a74608014e2b27fa9594b5c3168bf9a6e7f360840e2ece63fee2491dea47955\"],\"id\":89,\"jsonrpc\":\"2.0\"}","requestMethod":"POST","url":"https://holy-dimensional-research.ethereum-goerli.quiknode.pro/147af65013ea5eaf950052e88a7d75758c21d60a/"}, method="sendTransaction", transaction="0x02f8b105820150849502f900849502f90e82729794b4fbf271143f4fbf7b91a5ded31805e42b2208d680b844095ea7b300000000000000000000000093127808fb485f3725a3e11ba269038973f1d730000000000000000000000000000000000000000000000000016345785d8a0000c001a08ca082fa873ebf86a17e8754d5944b6f4a47ec05b2b9fdf5e2068a7a72835832a06a74608014e2b27fa9594b5c3168bf9a6e7f360840e2ece63fee2491dea47955", code=NONCE_EXPIRED, version=providers/5.5.1)
    at Logger.makeError (D:\blockchain\CLI\node_modules\@ethersproject\logger\lib\index.js:199:21)
    at Logger.throwError (D:\blockchain\CLI\node_modules\@ethersproject\logger\lib\index.js:208:20)
    at checkError (D:\blockchain\CLI\node_modules\@ethersproject\providers\lib\json-rpc-provider.js:103:16)
    at JsonRpcProvider.<anonymous> (D:\blockchain\CLI\node_modules\@ethersproject\providers\lib\json-rpc-provider.js:659:47)
    at step (D:\blockchain\CLI\node_modules\@ethersproject\providers\lib\json-rpc-provider.js:48:23)
    at Object.throw (D:\blockchain\CLI\node_modules\@ethersproject\providers\lib\json-rpc-provider.js:29:53)
    at rejected (D:\blockchain\CLI\node_modules\@ethersproject\providers\lib\json-rpc-provider.js:21:65)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  reason: 'nonce has already been used',
  code: 'NONCE_EXPIRED',
  error: Error: processing response error (body="{\"jsonrpc\":\"2.0\",\"id\":89,\"error\":{\"code\":-32000,\"message\":\"nonce too low: next nonce 337, tx nonce 336\"}}\n", error={"code":-32000}, requestBody="{\"method\":\"eth_sendRawTransaction\",\"params\":[\"0x02f8b105820150849502f900849502f90e82729794b4fbf271143f4fbf7b91a5ded31805e42b2208d680b844095ea7b300000000000000000000000093127808fb485f3725a3e11ba269038973f1d730000000000000000000000000000000000000000000000000016345785d8a0000c001a08ca082fa873ebf86a17e8754d5944b6f4a47ec05b2b9fdf5e2068a7a72835832a06a74608014e2b27fa9594b5c3168bf9a6e7f360840e2ece63fee2491dea47955\"],\"id\":89,\"jsonrpc\":\"2.0\"}", requestMethod="POST", url="https://holy-dimensional-research.ethereum-goerli.quiknode.pro/147af65013ea5eaf950052e88a7d75758c21d60a/", code=SERVER_ERROR, version=web/5.5.1)  
      at Logger.makeError (D:\blockchain\CLI\node_modules\@ethersproject\logger\lib\index.js:199:21)
      at Logger.throwError (D:\blockchain\CLI\node_modules\@ethersproject\logger\lib\index.js:208:20)
      at D:\blockchain\CLI\node_modules\@ethersproject\web\lib\index.js:301:32
      at step (D:\blockchain\CLI\node_modules\@ethersproject\web\lib\index.js:33:23)
      at Object.next (D:\blockchain\CLI\node_modules\@ethersproject\web\lib\index.js:14:53)
      at fulfilled (D:\blockchain\CLI\node_modules\@ethersproject\web\lib\index.js:5:58)
      at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
    reason: 'processing response error',
    code: 'SERVER_ERROR',
    body: '{"jsonrpc":"2.0","id":89,"error":{"code":-32000,"message":"nonce too low: next nonce 337, tx nonce 336"}}\n',
    error: Error: nonce too low: next nonce 337, tx nonce 336
        at getResult (D:\blockchain\CLI\node_modules\@ethersproject\providers\lib\json-rpc-provider.js:142:21)
        at processJsonFunc (D:\blockchain\CLI\node_modules\@ethersproject\web\lib\index.js:344:22)
        at D:\blockchain\CLI\node_modules\@ethersproject\web\lib\index.js:276:46
        at step (D:\blockchain\CLI\node_modules\@ethersproject\web\lib\index.js:33:23)
        at Object.next (D:\blockchain\CLI\node_modules\@ethersproject\web\lib\index.js:14:53)
        at fulfilled (D:\blockchain\CLI\node_modules\@ethersproject\web\lib\index.js:5:58)
        at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
      code: -32000,
      data: undefined
    },
    requestBody: '{"method":"eth_sendRawTransaction","params":["0x02f8b105820150849502f900849502f90e82729794b4fbf271143f4fbf7b91a5ded31805e42b2208d680b844095ea7b300000000000000000000000093127808fb485f3725a3e11ba269038973f1d730000000000000000000000000000000000000000000000000016345785d8a0000c001a08ca082fa873ebf86a17e8754d5944b6f4a47ec05b2b9fdf5e2068a7a72835832a06a74608014e2b27fa9594b5c3168bf9a6e7f360840e2ece63fee2491dea47955"],"id":89,"jsonrpc":"2.0"}',
    requestMethod: 'POST',
    url: 'https://holy-dimensional-research.ethereum-goerli.quiknode.pro/147af65013ea5eaf950052e88a7d75758c21d60a/'
  },
  method: 'sendTransaction',
  transaction: {
    type: 2,
    chainId: 5,
    nonce: 336,
    maxPriorityFeePerGas: BigNumber { _hex: '0x9502f900', _isBigNumber: true },
    maxFeePerGas: BigNumber { _hex: '0x9502f90e', _isBigNumber: true },
    gasPrice: null,
    gasLimit: BigNumber { _hex: '0x7297', _isBigNumber: true },
    to: '0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6',
    value: BigNumber { _hex: '0x00', _isBigNumber: true },
    data: '0x095ea7b300000000000000000000000093127808fb485f3725a3e11ba269038973f1d730000000000000000000000000000000000000000000000000016345785d8a0000',
    accessList: [],
    hash: '0x0fa2d468b388d710dbd1d21f8346a3901ed0c3b287d035ef2a44be6dc94ca0e6',
    v: 1,
    r: '0x8ca082fa873ebf86a17e8754d5944b6f4a47ec05b2b9fdf5e2068a7a72835832',
    s: '0x6a74608014e2b27fa9594b5c3168bf9a6e7f360840e2ece63fee2491dea47955',
    from: '0x93127808FB485F3725a3e11bA269038973F1d730',
    confirmations: 0
  },
  transactionHash: '0x0fa2d468b388d710dbd1d21f8346a3901ed0c3b287d035ef2a44be6dc94ca0e6'
}

1 Answer 1

2

"Error: nonce has already been used".

You need to update the nonce between each transaction. Grab the nonce on the first occasion, and then increment the number when building the transaction data.

2
  • 1
    I am getting a replacement fee too low error when I add incrementing nonce Commented Feb 17 at 3:38
  • 1
    The underpriced warning happens if the nonce is the same but the gas price per unit, is within 10% of the original transactions gas price per unit. So a replacement has the same nonce and an increased gas fee, you seem to be using the same nonce and gas fee. Check you really are increasing the nonce.
    – Maka
    Commented Feb 20 at 0:43

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.