Can the swap operation be carried out using web3.js and a forked HardHat implementation?

Embarking on my journey into ethereum development, I am currently engrossed in crafting a basic script that facilitates swaps using web3.js.

To begin with, my web3 is establishing a connection to the HardHat forked server.

The first step involves setting up the contract for the Uniswap v2Router02 router

const uniSwapv2Contract = new web3.eth.Contract(JSON.parse(uniswapV2Router02.result), "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D"); 

Subsequently, when required, I trigger the following callback


   const handleSwap = async () => {
      const [currencyOne, currencyTwo] = pairName.split("/");

      const tokenFrom = web3.utils.toChecksumAddress("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"); // WETH
      const tokenTo = web3.utils.toChecksumAddress("0x6982508145454ce325ddbe47a25d4ec3d2311933"); // PEPE 

      const path = [tokenFrom, tokenTo];

      var data = uniSwapv2Contract.methods.swapExactETHForTokens(
          web3.utils.toHex(1000000000),
          path,
          account,
          web3.utils.toHex(Math.round(Date.now()/1000)+60*20),
      );

      var count = await web3.eth.getTransactionCount(account);

      var rawTransaction = {
          from: account,
          to: web3.utils.toChecksumAddress("0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D"),
          data:data.encodeABI(),
          gasPrice: '0x09184e72a000', // Customizable by the user during MetaMask confirmation.
          // gas: '0x27101', // Customizable by the user during MetaMask confirmation.
          gas: web3.utils.toHex(9999999999999),
          gasLimit: '0x22000', // Customizable by the user during MetaMask confirmation.
          value: "0xDE0B6B3A7640000", // 1 full
          // nonce:web3.utils.toHex(100)
          nonce: web3.utils.toHex(count)
      };

      const signedTransaction  = await web3.eth.accounts.signTransaction(rawTransaction, "XXXX my private key XXXX"); // private key

      const txHash = await web3.utils.sha3(signedTransaction.rawTransaction);
      const transactionResult = await web3.eth.sendSignedTransaction(signedTransaction.rawTransaction).catch(error=>{
        console.log(error);
      });

    }

After execution, I encounter the following error in the browser:

TransactionRevertInstructionError: Transaction has been reverted by the EVM 

Hardhat presents more detailed information as follows:


Contract call: <UnrecognizedContract> 
From: 0xdd11751cdd3f6eff01b1f6151b640685bfa5db4a 
To: 0x7a250d5630b4cf539739df2c5dacb4c659f2488d 
Value: 1 ETH 

Error: Transaction reverted without a reason string 

The ordinary transactions like transfers function correctly, but those involving "Data" generated by swapExactETHForTokens fail.

I have cross-checked the contract hashes and downloaded ABI from etherscan.

A portion of the ETH has been converted to WETH.

In an attempt to resolve the issue, I created a fresh account and cleared the history in MetaMask where I monitor the results for transfers and swaps.

Even after running the server in verbose mode, limited insights were gained.

As a precautionary measure, I intend to write a script in Python to further investigate the problem.

Answer №1

Begin by making sure all your token information, allowances, balances, and gas settings are accurate.

  1. Double-Check Token Addresses: Verify that the addresses for tokenFrom and tokenTo align with the correct token contracts on the network you're utilizing.

  2. Review Token Allowances: Confirm if you have granted adequate token allowances for the uniSwapv2Contract to transact on your behalf. For instance, when trading ETH for PEPE, authorize the uniSwapv2Contract to utilize the required amount of PEPE tokens from your account.

  3. Validate Token Balances: Make sure there are ample tokens in tokenFrom to cover the intended swap amount.

  4. Assess Gas Parameters: Check whether the gas price and limit set in the rawTransaction object are suitable for the network being used. Adjust as needed.

  5. Track Transaction Errors: Instead of simply catching errors using catch, log the error message and carefully inspect the details to understand why the transaction is being reverted. Replace console.log(error) with console.error(error) to log the full error stack trace.

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

Maintaining selected options in select lists while updating model data in Angular

New to Angular and exploring the Product object with Sku objects nested inside. An app allows users to fetch a product, resulting in the Product object being assigned to $scope.product: var app = angular.module('app', []); app.controller(&apos ...

Enhance Your Website with HTML and JavaScript

Here is the code snippet I am working with: sTAT **javascript** var acc = document.getElementsByClassName("item-wrapper"); var i; for (i = 0; i < acc.length; i++) { acc[i].onclick = function(){ this.classList.toggle("selected"); this.nextElementS ...

Click here to open in a new tab and experience the ever-changing dynamic

Imagine a scenario where a property site displays the main viewed property ad at the top, with smaller ads in square divs below. When a user clicks on one of the smaller ads, it dynamically swaps places with the main ad thanks to JavaScript. All ad data is ...

Can you explain NodeSource in simple terms, and what purpose does it serve?

Not too long ago, I delved into researching how to effectively host a MEAN stack web application on AWS. During my quest for knowledge, I stumbled upon a tutorial that caught my eye. The one I ended up following can be found at https://www.youtube.com/wat ...

Whenever a query is entered, each letter creates a new individual page. What measures can be taken to avoid this?

Currently, I am working on a project that involves creating a search engine. However, I have encountered an issue where each time a user types a query, a new page is generated for every alphabet entered. For instance, typing 'fos' generates 3 pag ...

What is the best way to utilize a JavaScript function across all pages in Drupal 7?

What is the best way to utilize a global JavaScript function in Drupal 7? I have structured my JavaScript file as follows and included it using drupal_add_js(): (function($) { function add_if_country_is_not_usa() { // Determine the current country ...

Generate a binary string using JavaScript and then transform it into C#

I have an upload section in my JavaScript program. I utilize JS FileReader to obtain a binary string of the uploaded document before sending it to my C# WebApi for storage on the server. JavaScript Code let myFile = ev.target.files[0]; if(myFile.size > ...

Enhancing SVG graphics dynamically with JavaScript and ensuring compatibility across different web browsers

I am currently working on incorporating an element into an existing SVG file. Interestingly, the process runs smoothly on Chrome and Firefox but encounters issues on Edge. I aim for it to function seamlessly on the latest versions of all three browsers, wi ...

Ways to Soothe Long Polling

Currently, I am developing a basic chat feature using AJAX in a function that triggers a setTimeout call to itself upon successful execution. This occurs approximately every 30 seconds. While this setup serves its purpose, I am seeking a more immediate not ...

Currently, there is a requirement to include past build outcomes in the HTML test report within the playwright

Is there a way to display the previous build status of each test case for every test case? I have been attempting to use test.info() in playwright, but it seems inaccessible from onTestEnd. One option could be to retrieve the previous build data from Jenki ...

MongoDB has incorrect date and time records

I've been working on a blog site where entries are logged with the time and date they were posted and stored in MongoDB. Everything was working fine on my local machine, but when I deployed the site to Heroku, I noticed that the date displayed is 8 ho ...

Is Node.js functioning properly, but how can I incorporate it into a web browser?

I have a SQL Server table that I want to display in a web browser using the DataTables jQuery plugin. The code below works well for outputting data in the command line, but I need it to be displayed in the browser, possibly in JSON format. I am utilizing ...

Tips on refreshing a div using jQuery while maintaining the functionality of addEventListener

Hi, I am facing an issue with updating the "div" element. The refresh works fine, but after refreshing when I try to click on the updated "div", the addEventListener in my JavaScript code does not seem to work anymore. Can someone please explain why this i ...

The error handler in AngularJS $http service is always left wanting for a call

Here's the code snippet I'm currently using: $http .post('/api/login', $scope.user) .success(function (data, status, headers, config) { // code }) .error(function (data, status, headers, config) { // code }); It seems to be functi ...

What is the best way to assign a distinct index value to each object in an array

When I use the function below to add an index to each array object, all IDs end up with the same value when I check console.log: var foo = [...this.props.articleList]; foo.forEach(function(row, index) { row.id = index+1; }); console.log(foo); My des ...

Using Knockoutjs to fetch and display server-side data within the MVC framework

My goal is to initialize my knockoutjs viewmodel with data from the server. In my ASP.Net MVC project, I achieve this by passing a mvc viewmodel to the view: public ActionResult Edit(int cvId) { CV cv = repository.FindCV(cvId); //auto mapper mapp ...

What is the best way to make a JSONP request using jQuery?

Whenever I try to access this API through the browser, everything works fine and I receive the correct response. However, when I attempt to call the API using jQuery AJAX, I encounter an error. *The script is being refused execution from 'http://api ...

What is the target of the `__proto__` attribute in a constructor function?

I'm taking the time to dive deeper into prototypal inheritance. I know that an instance's __proto__ property points to the constructor function's prototype object, but where does the constructor function's __proto__ property point to? ...

What is it about the setTimeout function that allows it to not block other

Why is setTimeout considered non-blocking even though it is synchronous? And on which thread does it run if not the main thread? ...

Setting a default value in a drop-down menu in a React Native application

Within my array of 5 values in the "Options" props, I want to set a default value of "Please Select" defined in the state. However, when trying to retrieve it in the Value props, an error is occurring with a message saying "Label of undefined". Essential ...