Uncaught TypeError: https.Agent is not a constructor

Viewed 238

I am developing a dapp with react, the error when I try to instantiate web3 with an RPC of HTTPS or HTTP.

The error is as follows:

Uncaught TypeError: https.Agent is not a constructor

After doing some research, I have been able to verify that the error comes from the web3-providers-http module.

Expected Behavior When I configure the Metamask provider (window.ethereum) everything works fine. Since I can do write and read transactions, without problem on the blockchain. What I hope is that it works correctly without the error and can make transactions.

Steps to Reproduce

var Web3 = require('web3');
var provider = 'https://mainnet.infura.io/v3/<PROJECT-ID>';
var web3Provider = new Web3.providers.HttpProvider(provider);
var web3 = new Web3(web3Provider);
web3.eth.getBlockNumber().then((result) => {
  console.log("Latest Ethereum Block is ",result);
});

Web3.js Version 1.7.4

Vite Version 3.0.0

Environment Operating System: macOs 11.5.2 Browser: Chrome, Firefox Node.js Version: v12.22.0 NPM Version: 7.7.6

1 Answers

The issue is with http agent as vite doesnot add that polyfill or is not linked

here is the solution I found out

  • Add agent-base by using yarn add stream-browserify agent-base or npm -i stream-browserify agent-base
  • Update your vite.config.js as below
import GlobalsPolyfills from '@esbuild-plugins/node-globals-polyfill'

export default defineConfig({
...
  optimizeDeps: {
    esbuildOptions: {
      define: {
        global: 'globalThis',
      },
      plugins: [
        GlobalsPolyfills({
          process: true,
          buffer: true,
        }),
      ],
    },
  },
  resolve: {
    alias: {
      stream: 'stream-browserify',
      https: 'agent-base', 
      // comment above line and uncomment below line if it doesnot work
      //     http:'agent-base',
    },
  },
...
)}

Another Solution - 2 : You can use ethers package instead of web3 as it is not dependent on http agent

import { ethers, Contract, Wallet, getDefaultProvider } from 'ethers';
import ZntLockerLens from './ZntLockerLens';

    const provider = new ethers.providers.JsonRpcProvider(
      'https://http-testnet.xx.com',
    );
    const contract = new Contract(
      '0x492B7bCD1732FBB8297a24694dxx6B3FEDCA9D0A',
      ZntLockerLens.abi,
      provider,
    );
    (async () => {
      const result = await contract.getLockInfo(
        '0xC02a0c4634B4f2aF73Bb29bxx1153E791AdB7D1e',
      );
      console.log(result);
    })();
Related