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

Setting up parameters and arguments in Vuex mutations: A guide

I am currently developing a todo list application using Vue.js, Vuex, and Firebase. The functionality of the app seems to be in working order with the Store file effectively managing the retrieval and display of entered todo items to and from Firestore. Ho ...

What is the best way to add an element conditionally within a specific Vue Component scope?

I've been working on creating a Component for titles that are editable when double-clicked. The Component takes the specific h-tag and title as props, generating a regular h-tag that transforms into an input field upon double click. It's function ...

Currently focused on designing a dynamic sidebar generation feature and actively working towards resolving the issue of 'Every child in a list must have a distinct "key" prop'

Issue Found Alert: It seems that each child within a list needs a unique "key" prop. Please review the render method of SubmenuComponent. Refer to https://reactjs.org/link/warning-keys for further details. at SubmenuComponent (webpack-internal:///./src/c ...

Adjust properties based on screen size with server-side rendering compatibility

I'm currently using the alpha branch of material-ui@v5. At the moment, I have developed a custom Timeline component that functions like this: const CustomTimeline = () => { const mdDown = useMediaQuery(theme => theme.breakpoints.down("md")); ...

Can a link be generated that swaps out the original URL redirect for the following visitor upon clicking?

Can the program be fed with a list of links to automatically redirect to the next URL once clicked? In this setup, each visitor would only see one link and not have access to any other URLs in the chain. Is there a way to make this happen? Any suggestion ...

When running the command "npx create-next-app@latest --ts," be aware that there are 3 high severity vulnerabilities present. One of the vulnerabilities is that "node-fetch

Just set up a fresh project with Next.js and TypeScript by following the documentation using npx create-next-app@latest --ts. Encountering multiple high severity vulnerabilities despite running npm audit fix --force, which actually adds more vulnerabiliti ...

Attaching identical class and event handlers to numerous dynamically created elements

I am facing a challenge with the following HTML structure: <a href="#" @click.prevent="toggleClass">Show/Hide</a><br> <li :class="{myClass: showItems}">Item 1</li> <a href="#" @click.prevent="toggleClass">Show/Hide< ...

The payload is properly returned by the Reducer, however, the component is receiving it as

In my current project, I am developing an application that involves fetching data from a firebase database. This particular database does not require authentication, and I have already adjusted the access rules to allow for public access. One of the actio ...

Creating a JavaScript function that responds to multiple click events

Can someone please help me out? I have the link to the output of my work below using JavaScript and HTML: My goal is for only one circle to be active when clicked, while the others are disabled. Currently, when I click on a circle and then another one, bo ...

What is the process for altering the color of an HTML output depending on its values?

I created a simple HTML code to showcase some outcomes. The possible results are SUCCESS, Failure, and Still Failing. I want these results to be displayed with corresponding colors, such as green for SUCCESS, and red for both Failure and Still Failing. I ...

Automatically identify the appropriate data type using a type hint mechanism

Can data be interpreted differently based on a 'type-field'? I am currently loading data from the same file with known type definitions. The current approach displays all fields, but I would like to automatically determine which type is applicab ...

Failing to retain hyperlinks with ajax

Currently, I am utilizing ajax to transmit data from a sophisticated custom field wysiwyg editor. Within this setup, the specific div with the class 'bio' is what I'm addressing. The issue arises when the data is retrieved - all the original ...

There was an issue with the NextJS axios request as it returned a status code

I'm currently in the process of developing an application with NextJS and Strapi In my project, I am fetching data from Strapi using Axios within NextJS Next: 14.0.4 Axios: ^1.6.5 Strapi: 4.17.1 Node: 18.17.0 Here is the code snippet: import axios f ...

What are the best practices for using .toString() safely?

Is it necessary for the value to return toString() in order to call value.toString()? How can you determine when you are able to call value.toString()? <script> var customList = function(val, lst) { return { value: val, tail: lst, t ...

Navigating the Terrain of Mapping and Filtering in Reactjs

carModel: [ {_id : A, title : 2012}, {_id : B, title : 2014} ], car: [{ color :'red', carModel : B //mongoose.Schema.ObjectId }, { color ...

Pass data dynamically to router in ExpressJS

Within my app.js file, there are several variables defined: var user = "max"; Additionally, there is a route function set up like so: app.post('/register', user.postRegister); In the /routes/user.js file, there is a module function structured ...

When you try to click outside of react-select, the dropdown doesn't

I've been working on customizing react-select and encountered some issues. Specifically, after modifying the ValueContainer and SelectContainer components, I noticed that the dropdown doesn't close when clicking outside of it after selecting a va ...

Fixing the problem of digest overflow in AngularJS

I've been working on a code to display a random number in my view, but I keep encountering the following error message: Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting! It seems to be related to a digest outflow issue, and I&apo ...

Is it possible to animate the innerHTML of a div using CSS?

In my HTML file, I have these "cell" divs: <div data-spaces class="cell"></div> When clicked, the innerHTML of these divs changes dynamically from "" to "X". const gridSpaces = document.querySelectorAll("[data-spaces]"); f ...

Express.js Res redirection problem occurring with Backbone.js due to failure in redirecting hashtag URLs

Issue Summary: Having trouble with Express.js redirect functionality. The problem occurs when trying to redirect after entering /#impulse, but works fine with /impulse/. Server processes the request for /#impulse before applying redirect checks, which re ...