0
0
Blockchain / Solidityprogramming~5 mins

Testing with ethers.js in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Testing with ethers.js
O(n)
Understanding Time Complexity

When testing smart contracts with ethers.js, it's important to know how the time to run tests changes as the number of tests or contract calls grows.

We want to understand how the test execution time scales when we add more test cases or interact more with the blockchain.

Scenario Under Consideration

Analyze the time complexity of the following ethers.js test code snippet.


const { expect } = require("chai");
const { ethers } = require("hardhat");

describe("SimpleContract", function () {
  it("should return correct value", async function () {
    const contract = await ethers.getContractFactory("SimpleContract").then(factory => factory.deploy());
    await contract.deployed();
    for (let i = 0; i < 100; i++) {
      const value = await contract.getValue(i);
      expect(value).to.equal(i * 2);
    }
  });
});
    

This code deploys a contract and calls a function 100 times in a loop, checking the returned value each time.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The loop calling contract.getValue(i) 100 times.
  • How many times: Exactly 100 times in this example, but this number can grow with test size.
How Execution Grows With Input

As the number of calls in the loop increases, the total test time grows roughly in direct proportion.

Input Size (n)Approx. Operations
1010 contract calls
100100 contract calls
10001000 contract calls

Pattern observation: Doubling the number of calls roughly doubles the total execution time.

Final Time Complexity

Time Complexity: O(n)

This means the test time grows linearly with the number of contract calls in the loop.

Common Mistake

[X] Wrong: "Adding more calls inside the test loop won't affect test time much because calls are fast."

[OK] Correct: Each contract call involves communication with the blockchain simulator or network, which takes time. More calls add up and increase total test time linearly.

Interview Connect

Understanding how test execution time grows helps you write efficient tests and shows you can think about performance beyond just code correctness.

Self-Check

"What if we batch multiple calls into one contract function instead of calling individually? How would the time complexity change?"