Issue detected: unexpected data returned during testing using ether.js with the uniswapv2router.swapExactTokensForTokens function

While testing UNISWAP_V2_ROUTER.swapExactTokensForTokens with ether.js, I encountered an error when executing this line of code:

await swapInstances.connect(accounts[0]).swap(tokenIn, tokenOut, amountIn, amountOutMin, to);
. The error message reads:
Transaction reverted: function returned an unexpected amount of data
.

Any idea why this is happening?

Here is the unit test in question:

 it("should be able to swap tokens", async function () {
            accounts = await ethers.getSigners()
            to = await accounts[1].getAddress();
            const Swap = await ethers.getContractFactory("Swap", accounts[0]);
            const swapInstances = await Swap.deploy();
            const LocandaToken = await ethers.getContractFactory("LocandaToken", accounts[0]); //ERC20
            const locandaToken = await LocandaToken.deploy();
            const RubiconPoolToken = await ethers.getContractFactory("RubiconPoolToken", accounts[1]); //ERC20
            const rubiconPoolToken = await RubiconPoolToken.deploy();
            tokenIn = locandaToken.address;
            tokenOut = rubiconPoolToken.address;

            await locandaToken.connect(accounts[0]).transfer(swapInstances.address, amountIn);
            await rubiconPoolToken.connect(accounts[1]).transfer(swapInstances.address, amountIn);

            
            const ethBalance = await ethers.provider.getBalance(accounts[0].address);
            console.log("eth balance" + ethBalance);

            await locandaToken.connect(accounts[0]).approve(swapInstances.address, amountIn)
            const test = await swapInstances.connect(accounts[0]).swap(tokenIn, tokenOut, amountIn, amountOutMin, to);
        })

This is the swap function being called:

function swap(
        address _tokenIn,
        address _tokenOut,
        uint256 _amountIn,
        uint256 _amountOutMin,
        address _to // address where sending the tokenout
    ) external {
        IERC20(_tokenIn).transferFrom(msg.sender, address(this), _amountIn); // transfer from user wallet to this contract
        IERC20(_tokenIn).approve(UNISWAP_V2_ROUTER, _amountIn); // aprove the router to spend _tokenin
        address[] memory path; //represents the path/flow of the swap

        if (_tokenIn == WETH || _tokenOut == WETH) {
            path = new address[](2);
            path[0] = _tokenIn;
            path[1] = _tokenOut;
        } else {
            path = new address[](3);
            path[0] = _tokenIn;
            path[1] = WETH;
            path[2] = _tokenOut;
        }

        IUniswapV2Router(UNISWAP_V2_ROUTER).swapExactTokensForTokens(
            _amountIn,
            _amountOutMin,
            path,
            _to,
            block.timestamp
        );  
    }

Answer №1

When I mistakenly used Router1's address instead of Router2's, I encountered this error.

Once I corrected the router address, the issue was resolved.

Answer №2

Launching two new tokens necessitates the absence of Uniswap pools dedicated to those specific tokens.

To rectify this, it is advisable to establish a corresponding pair using the uniswapV2Factory and proceed with adding liquidity:

Another point to consider is where the amountOutMin is being specified.

Additionally, why is there a need to transfer tokens to the swap contract?

await locandaToken.connect(accounts[0]).transfer(swapInstances.address, amountIn);

await rubiconPoolToken.connect(accounts[1]).transfer(swapInstances.address, amountIn);

Answer №3

If you encounter an error like this, it could be due to the IERC20 interface being used. Typically, functions like transfer and transferFrom in the IERC20 interface return a (bool) value.

function transfer(address to, uint256 amount) external returns (bool);
function transferFrom(address from, address to, uint256 amount) external returns (bool);

However, some tokens or external routers may have interfaces with transfer or transferFrom functions that do not return anything. For example, with USDT token, the transfer and transferFrom functions do not return any value. If you are trying to call these functions using your custom IERC20 functions with a bool return value, you may receive an error message saying "Transaction reverted: function returned an unexpected amount of data".

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide on displaying containers with jQuery and CSS

Looking to create a smiley survey using only Front-End technologies. Once a radio button is selected, the associated content should appear for comments. Currently, I have set up my CSS with display: none. I attempted to implement this functionality using ...

I'm having trouble saving the session, what could be the issue?

Hey there, I've created a form where users can sign up. Once the user fills in all the details and clicks submit, an Ajax request sends the form data to the database. If this process happens without any errors, a hidden div containing payment buttons ...

What is the method for retrieving a gzip file using jQuery?

I have set up my own HTTP server using node.js and express.js. var express = require('express'); express().use(express.static(__dirname)).listen(3000); Within my static content folder, I have two test files: myfile.csv and myfile.csv.gz. These ...

Is there a way to incorporate a trace in Plotly while also arranging each data point along the x-axis in a unique custom order?

I am facing a challenge in creating a line graph that displays (x, y) coordinates where the x axis represents a date and the y axis represents a value. The dates are formatted like DD-MM-YYYY, for example, 15-04-2015. My initial trace is added with the fo ...

No specification has been provided for the delivery

I'm currently working with the Meteor framework and I am attempting to send an uploaded file (HTML input) from the client to the server using the npm package Delivery. Below is my code: Client side : var socket = io.connect('http://0.0.0.0 ...

"Controller's $watch function fails to trigger when new items are added to an array within a directive

Within my code, I have established a two-way binding variable called publish.selected_tags that connects a directive with a controller. To monitor changes in this variable, I implemented a $watch function within my controller: $scope.$watch('publish ...

Angular promise creation

Just starting out with Angular and I might be approaching promises incorrectly. I have a factory that returns a promise: .factory('myData', ['$http', '$q', function($http, $q) { var deferred = $q.defer(); $http.get(& ...

Trouble with NodeJS async/await - navigating through function arguments

Currently, I am attempting to perform web scraping using a particular library while implementing Node's async/await method in my code. Within the function named 'sayhi', I have created a variable 'page' and encountered an issue wh ...

Executing a personalized function - settings.func does not exist as a valid function

I have developed a custom jQuery plugin where I intend to invoke a specific function like this... (function($) { $.fn.customPlugin= function(options) { var settings = { func: null }; if (options) { $. ...

Error: Attempted to access undefined property 'renderMenu' in a promise without handling it

I am looking to generate a dynamic menu based on the JSON data provided below: [ { "teamId": "10000", "teamName": "Laughing Heroes", "superTeamId": "", "createTime": "2017-06-25T06:07:45.000Z", "createUserId": null }, { "team ...

Incorporating Mediainfo.js into Angular 8: A Seamless Integration

I'm attempting to utilize Mediainfo.js for retrieving video information on the frontend of my Angular 8 project. However, I am encountering the following errors: GET https://192.168.25.177:4200/MediaInfoModule.wasm 404 (Not Found) wasm streaming compi ...

Leveraging Mermaid for angular applications

As a newcomer to Mermaid, I am attempting to integrate it into my Angular project. Placing it in my HTML has proven successful. <script src="https://cdnjs.cloudflare.com/ajax/libs/mermaid/9.0.1/mermaid.min.js"></script> <div class="merma ...

Using finally() to correctly construct a Javascript promise

Currently, I am working on an Express API that utilizes the mssql package. If I neglect to execute sql.close(), an error is triggered displaying: Error: Global connection already exists. Call sql.close() first. I aim to keep the endpoints simple and e ...

I have successfully established a new channel, but I am having difficulty retrieving the unique identifier for it

After using the provided code to create a channel, I'm having trouble locating the channel ID needed for the next step in my function. This function is meant to move to a specific category and send a message to it. const buyid = generateID message. ...

Leveraging require in AWS lambda operations

As part of my exploration into AWS Lambda functions, I've been trying to determine if the require statement can be used within them. This would allow me to incorporate other non-lambda functions into my code. Although zipping the node modules folder i ...

Challenges with displaying TreeTable in SAPUI5

I have a case with a single xml view. Inside this view, there is a treetable with two columns. <core:View xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" controllerName="sdf_test.App" xmlns:html="http://www.w3.org/1999/xhtml" ...

Into the depths we delve, extending beyond to an array of objects?

I have a question about the possibility of extending an array of objects like this: Imagine I have : myObj = [ {"name" : "one", "test" : ["1","2"]}, {"name" : "two", "test" : ["1","2"]} ] And I want to add to it something like - {"name" : ...

Unusual Behavior Uncovered in jQuery Selectors

Have you ever noticed a peculiar behavior of jQuery selectors? I recently discovered that when the page contains elements with non-unique IDs, jQuery returns different results for the same selectors: Here's an example of HTML code: <button id=&ap ...

Tips for integrating new channels and categories using a Discord bot

Hey there! I'm trying to add channels and categories, but I can't seem to get the function ".createChannel" working. The console keeps telling me that the function doesn't exist. I've been referencing the documentation at https://discor ...

Enhancing the angular options list with new commands

Is there an easy way to append specific commands to the end of an Angular select box? For instance, I want a list that looks like this: Cat Dog Octopus Browse… All items except Browse are data values bound using ng-options, while Browse is a command t ...