Custom Truffle web3 provider to support Infura authentication

Install lib:

- For Http: 
yarn add web3-providers-http

- For Ws:
yarn add web3-providers-ws

Example web3 provider configuration:

https://web3js.readthedocs.io/en/v1.7.4/web3-eth.html

// ====
// Http
// ====

const Web3HttpProvider = require('web3-providers-http');

const options = {
    keepAlive: true,
    withCredentials: false,
    timeout: 20000, // ms
    headers: [
        {
            name: 'Access-Control-Allow-Origin',
            value: '*'
        },
        {
            ...
        }
    ],
    agent: {
        http: http.Agent(...),
        baseUrl: ''
    }
};

const provider = new Web3HttpProvider('http://localhost:8545', options);

// ==========
// Websockets
// ==========

const Web3WsProvider = require('web3-providers-ws');

const options = {
    timeout: 30000, // ms

    // Useful for credentialed urls, e.g: ws://username:password@localhost:8546
    headers: {
      authorization: 'Basic username:password'
    },

    clientConfig: {
      // Useful if requests are large
      maxReceivedFrameSize: 100000000,   // bytes - default: 1MiB
      maxReceivedMessageSize: 100000000, // bytes - default: 8MiB

      // Useful to keep a connection alive
      keepalive: true,
      keepaliveInterval: 60000 // ms
    },

    // Enable auto reconnection
    reconnect: {
        auto: true,
        delay: 5000, // ms
        maxAttempts: 5,
        onTimeout: false
    }
};

const ws = new Web3WsProvider('ws://localhost:8546', options);

Integrate with truffle

const HDWalletProvider = require('@truffle/hdwallet-provider');
const Web3HttpProvider = require('web3-providers-http');


module.exports = {
  networks: {

    rinkeby: {
      provider: () => new HDWalletProvider(MNEMONIC, `wss://rinkeby.infura.io/ws/v3/${INFURA_API_KEY}`),
      network_id: 4,
      skipDryRun: true,
      networkCheckTimeout: 90000,
      timeoutBlocks: 200,
      // gas: 4698712,
      // gasPrice: 1000000022,
    },

    rinkebyAuth: {
      provider: () =>
        new HDWalletProvider({
          privateKeys: [MNEMONIC],
          provider: new Web3HttpProvider(`https://rinkeby.infura.io/v3/${INFURA_API_KEY}`, {
            headers: [
              {
                name: 'Authorization',
                value: 'Basic u7Vh2h7mMTBmODk12ms902U4ZjM2YzlkYzVkYTAz=',
              },
            ],
          }),
        }),
      network_id: 4,
      skipDryRun: true,
      networkCheckTimeout: 90000,
      timeoutBlocks: 200,
    },

  }
}

Change authentication Basic to Bearer to use JWT approach