Skip to content
This repository was archived by the owner on Mar 5, 2025. It is now read-only.

Memory leaks on Contract class #7461

Open
vincent2303 opened this issue Feb 20, 2025 · 1 comment
Open

Memory leaks on Contract class #7461

vincent2303 opened this issue Feb 20, 2025 · 1 comment

Comments

@vincent2303
Copy link

vincent2303 commented Feb 20, 2025

Expected behavior

Creating contract instances should not cause memory leak.

Actual behavior

Creating contract instances is causing a memory leak (heapUsed keeps increasing).

Steps to reproduce the behavior

With this code, HeapUsed keeps increasing (even if newly created contracts are not used and should be deleted by garbage collector automatically).

import { Web3 } from 'web3';

const YOUR_ENDPOINT = 'YOUR_ENDPOINT';

const client = new Web3(new Web3.providers.HttpProvider(YOUR_ENDPOINT));

while (true) {
  for (let index = 0; index < 10 ** 5; index++) new client.eth.Contract([], '0x468b88941e7cc0b88c1869d68ab6b570bcef62ff');
  console.log(`Heap Used: ${(process.memoryUsage().heapUsed / 1e9).toFixed(2)} GB`);
}

Logs

On my laptop (Apple M3 Pro), It crashes after 1 minute, It logs this:

Heap Used: 0.63 GB
Heap Used: 1.14 GB
Heap Used: 1.21 GB
Heap Used: 2.03 GB
Heap Used: 1.87 GB
Heap Used: 2.69 GB
Heap Used: 2.74 GB
Heap Used: 2.94 GB
Heap Used: 3.27 GB
Heap Used: 3.72 GB
Heap Used: 4.02 GB

<--- Last few GCs --->
...
<--- JS stacktrace --->
FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
...

Environment

Node version: v20.17.0
pnpm version: 9.14.4
web3 version: 4.16.0

When This behavior has been introduced

Using version 4.12.1 of web3, creating Contract instances does not cause a memory leak.
It means this behaviour appeared between version 4.12.1 and version 4.16.0
Here are logs for the exact same code with web3 version 4.12.1:

Heap Used: 0.04 GB
Heap Used: 0.05 GB
Heap Used: 0.05 GB
Heap Used: 0.06 GB
Heap Used: 0.06 GB
Heap Used: 0.06 GB
Heap Used: 0.07 GB
Heap Used: 0.07 GB
Heap Used: 0.02 GB
Heap Used: 0.02 GB
Heap Used: 0.03 GB
Heap Used: 0.03 GB
Heap Used: 0.04 GB
Heap Used: 0.04 GB
Heap Used: 0.04 GB
Heap Used: 0.05 GB
Heap Used: 0.05 GB
Heap Used: 0.06 GB
Heap Used: 0.06 GB
Heap Used: 0.06 GB
Heap Used: 0.07 GB
Heap Used: 0.07 GB
Heap Used: 0.08 GB
Heap Used: 0.02 GB
... (no memory issue)
@jdevcs
Copy link
Contributor

jdevcs commented Feb 25, 2025

We suggest to migrate to ethers or viem, due Web3.js is sunsetting,
For further details regarding the sunsetting of Web3.js, please refer to the official announcement here: Web3.js Sunset Announcement

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants