Subscription cloning after reconnection

this.subscription = this.web3.eth.subscribe("newBlockHeaders").on("data", (blockHeader) => {
      console.log("block:", blockHeader.number);
});

I’m using following code to track new blocks. Every reconnection, manual or auto leads to burst console.log of the same block. Also I tried to unsubscribe, to make resub, but got the error that subscription is not found. Then I used alchemy node to test same behaviour and there is no problem at all. Reconnection didn’t duplicate subscription and logging only one console.log at every new blockHeader.

Today I exceed request limit due this reconnection issue. Waiting for reply

Hi @Snitovets, and welcome to the Infura community!

Your original question sounds like you’re seeing the same block being console.logged when there is a reconnection - how often is that occurring?

Pretty often. Looks like subscription duplicates on every reconnection. And I can’t just unsubscribe and subscribe back.

Reproduction

const Web3 = require("web3");

if (!process.env.INFURA_API) {
  throw new Error("INFURA_API must be defined!");
}

const provider = new Web3.providers.WebsocketProvider(process.env.INFURA_API, {
  clientConfig: {
    keepalive: true,
    keepaliveInterval: 60000
  },
  reconnect: {
    auto: true,
    delay: 5000,
    maxAttempts: 1000,
    onTimeout: false
  }
});

provider.on("reconnect", () => {
  console.warn("Web3 provider reconnected");
});
provider.on("close", () => {
  console.error("Web3 provider disconnected!");
});

const web3 = new Web3(provider);

let i = 0;

const id = setInterval(() => {
  if (i === 10) clearInterval(id);

  provider.reconnect();
  i++;
}, 3000);

setTimeout(() => {
  console.log("Enough...");
  process.exit(0);
}, 120000);

const subscription = web3.eth
  .subscribe("newBlockHeaders")
  .on("data", (blockHeader) => {
    console.log("block:", blockHeader.number);
  });