Blockchain Testing

Production engineering guide for blockchain testing in Web3 and blockchain systems.

Blockchain Testing is the discipline of validating the correctness, reliability, and performance of blockchain systems—ranging from smart contract logic to full node operation—across development, staging, and production environments. It matters most when deploying new protocols, upgrading consensus mechanisms, integrating cross-chain services, or ensuring transaction finality in high-throughput applications. Unlike traditional software testing, blockchain testing must account for asynchrony, eventual consistency, deterministic execution, and the immutable, distributed nature of data.

Testing Smart Contract Logic

Smart contracts are the core business logic of blockchain applications. Testing them requires not only unit and integration tests but also validation of state transitions across multiple blocks.

The standard test suite begins with a test script in package.json:

{
  "scripts": {
    "test": "hardhat test",
    "test:watch": "hardhat test --watch"
  }
}

Hardhat is the dominant framework for Ethereum-based development, and its hardhat.config.ts defines network and testing parameters:

import { HardhatUserConfig } from "hardhat/config";

const config: HardhatUserConfig = {
  solidity: "0.8.20",
  networks: {
    hardhat: {
      chainId: 1337,
      mining: {
        auto: true,
        interval: 5000,
      },
      accounts: {
        count: 20,
        initialBalance: "1000000000000000000000", // 1000 ETH
      },
    },
    goerli: {
      url: "https://goerli.infura.io/v3/${process.env.INFURA_PROJECT_ID}",
      accounts: [process.env.PRIVATE_KEY!],
    },
  },
  paths: {
    tests: "test",
    artifacts: "artifacts",
    cache: "cache",
  },
};

export default config;

The test directory contains .ts files using Mocha and Chai. A typical test case verifies a token transfer:

import { expect } from "chai";
import { ethers } from "hardhat";

describe("Token", function () {
  let token: Contract;
  let owner: Signer;
  let addr1: Signer;
  let addr2: Signer;

  beforeEach(async function () {
    [owner, addr1, addr2] = await ethers.getSigners();
    const Token = await ethers.getContractFactory("Token");
    token = await Token.deploy("MyToken", "MTK", 18);
    await token.waitForDeployment();
  });

  it("should have correct initial supply", async function () {
    const totalSupply = await token.totalSupply();
    expect(totalSupply).to.equal(1000000000000000000000000n); // 1000 MTK
  });

  it("should transfer tokens", async function () {
    await token.connect(owner).transfer(addr1, 100000000000000000000n); // 100 MTK
    const balance = await token.balanceOf(addr1);
    expect(balance).to.equal(100000000000000000000n);
  });
});

Running tests on a local node is fast but may miss real-world behavior. To catch reorgs and long delays, test scripts must simulate network conditions:


npx hardhat test --network hardhat --no-compile

To test reorgs, use hardhat node with a custom hardhat.config.ts:

networks: {
  hardhat: {
    chainId: 1337,
    mining: {
      auto: true,
      interval: 1000,
    },
    accounts: {
      count: 20,
      initialBalance: "1000000000000000000000",
    },
    gas: "auto",
    gasPrice: "auto",
    blockGasLimit: 12500000,
    timeout: 20000,
  },
},

A common failure: the test assumes block.timestamp is updated, but mining.auto is set to false. The test passes locally but fails in CI due to missed block times. Another silent issue: await token.waitForDeployment() returns too early—before the contract is fully mined into the chain, leading to missing abi or address mismatches.

To verify finality, write a helper to wait for a transaction to be finalized:

async function waitForFinality(txHash: string, confirmations = 6) {
  const receipt = await ethers.provider.waitForTransaction(txHash, confirmations);
  return receipt;
}

Finality is not guaranteed by waitForTransaction alone. A transaction may be mined but not yet finalized. Use eth_getTransactionReceipt to check confirmations and blockHash changes to detect reorgs.

Testing Node Operation and Synchronization

Validating node health and synchronization is critical for full nodes, archive nodes, and light clients. The primary tool is curl to interact with the JSON-RPC API.

To check node readiness, query the eth_syncing endpoint:

curl -X POST \
  -H "Content-Type: application/json" \
  --data '{
    "jsonrpc": "2.0",
    "method": "eth_syncing",
    "params": [],
    "id": 1
  }' \
  http://localhost:8545

Expected response:

{
  "jsonrpc": "2.0",
  "result": {
    "startingBlock": 1000000,
    "currentBlock": 1000050,
    "highestBlock": 1000500
  },
  "id": 1
}

When currentBlock is less than highestBlock, the node is syncing. A false result indicates the node is fully synced.

To monitor sync progress, write a script that polls eth_syncing every 5 seconds:

#!/bin/bash
while true; do
  response=$(curl -s -X POST \
    -H "Content-Type: application/json" \
    --data '{"jsonrpc":"2.0","method":"eth_syncing","params":[],"id":1}' \
    http://localhost:8545)

  if echo "$response" | jq -e '.result | type == "boolean" and .result == false'; then
    echo "Node is fully synced at block $(echo "$response" | jq -r '.result.highestBlock')"
    break
  fi

  current=$(echo "$response" | jq -r '.result.currentBlock')
  highest=$(echo "$response" | jq -r '.result.highestBlock')
  echo "Syncing: $current / $highest"

  sleep 5
done

The script fails silently when the node stops syncing but never reaches currentBlock === highestBlock. The eth_syncing response may include earliestBlock, which is often ignored. A node may have synced from block 1, but earliestBlock is 100000, meaning the node is not yet at genesis.

To test node reconfiguration, use systemctl to restart the node process and verify it resumes syncing from the last known block.

sudo systemctl restart geth
sudo systemctl status geth -l

Check logs for eth_syncing messages and verify that geth reconnects to peers and resumes from the last currentBlock.

Testing Cross-Chain Communication

Cross-chain messaging requires end-to-end validation of message delivery, confirmation, and execution. The most common pattern is using a bridge contract that emits MessageSent events and a receiving chain that processes them.

To test a message sent from Ethereum to Polygon, use ethers to send a transaction and verify the message is processed:

import { ethers } from "ethers";

const provider = new ethers.JsonRpcProvider("https://polygon-mainnet.g.alchemy.com/v2/KEY");
const signer = new ethers.Wallet(PRIVATE_KEY, provider);

const bridge = new ethers.Contract(
  "0x1234567890123456789012345678901234567890",
  [
    "event MessageSent(uint256 indexed id, address sender, bytes message)",
  ],
  signer
);

await bridge.sendMessage("Hello from Ethereum", { gasLimit: 200000 });

const filter = bridge.filters.MessageSent();
const events = await bridge.queryFilter(filter, "latest");
const latestEvent = events[events.length - 1];

console.log("Message ID:", latestEvent.args.id);
console.log("Message:", latestEvent.args.message.toString());

The message is not complete until it is confirmed on the destination chain. To test this, write a function that waits for a message to be confirmed on the target chain:

async function waitForMessageConfirmation(messageId: bigint, targetChain: string) {
  const targetProvider = new ethers.JsonRpcProvider(targetChain);
  const targetBridge = new ethers.Contract(
    "0x1234567890123456789012345678901234567890",
    [
      "event MessageConfirmed(uint256 indexed id)",
    ],
    targetProvider
  );

  const filter = targetBridge.filters.MessageConfirmed(messageId);
  const receipt = await targetProvider.waitForTransaction(
    await targetBridge.getFilterLogs(filter),
    1
  );

  return receipt;
}

A common failure: the receiving chain emits MessageConfirmed, but the messageId does not match the sent id. The cause is often a mismatch in bytes encoding, where message is bytes32 on one side but bytes on the other. Another silent error: the MessageSent event is emitted, but the transaction is not mined before the message is picked up by the relayer.

To validate a relayer, use psql to query a database tracking sent and confirmed messages:

SELECT id, sender, message, sent_at, confirmed_at, status
FROM messages
WHERE status = 'sent'
ORDER BY sent_at DESC
LIMIT 10;

A relayer may have sent a message but not updated status to sent, leading to duplicate processing.

Testing Consensus and Finality

Consensus correctness is tested by validating that blocks are produced at the expected intervals, and that finality is reached as expected.

For proof-of-stake chains, use eth_getBlockByNumber with full transactions to verify that the block producer is correct:

curl -X POST \
  -H "Content-Type: application/json" \
  --data '{
    "jsonrpc": "2.0",
    "method": "eth_getBlockByNumber",
    "params": ["0x100000", true],
    "id": 1
  }' \
  http://localhost:8545

The response includes miner (for PoW) or proposer (for PoS). To test proposer selection, compare proposer across blocks.

To test finality, use eth_getFinalityCheckpoint:

{
  "jsonrpc": "2.0",
  "method": "eth_getFinalityCheckpoint",
  "params": [],
  "id": 1
}

Expected response:

{
  "jsonrpc": "2.0",
  "result": {
    "currentFinalityCheckpoint": {
      "epoch": 100,
      "root": "0x12345678901234567890123456789012345678901234567890123456789012"
    },
    "previousFinalityCheckpoint": {
      "epoch": 99,
      "root": "0x23456789012345678901234567890123456789012345678901234567890123"
    }
  },
  "id": 1
}

A failure occurs when currentFinalityCheckpoint.epoch is not incremented after epoch-length blocks, or when root mismatches due to incorrect state hashing.

To validate finality, write a test that checks that a block is finalized after a certain number of confirmations:

async function isFinalized(blockNumber: number, confirmations: number) {
  const block = await provider.getBlock(blockNumber);
  const finalized = await provider.getFinalityCheckpoint();

  const epoch = block.number - (block.number % confirmations);
  return finalized.currentFinalityCheckpoint.epoch === epoch;
}

This fails silently when the confirmations parameter is mismatched with the expected epoch size, or when the chain has a different finalityDelay than expected.

Testing Transaction Propagation and Latency

To test how quickly transactions propagate through the network, use eth_getTransactionByHash and eth_getTransactionReceipt with timing.

# Send a transaction and record timestamps
curl -X POST \
  -H "Content-Type: application/json" \
  --data '{
    "jsonrpc": "2.0",
    "method": "eth_sendTransaction",
    "params": [{
      "from": "0x1234567890123456789012345678901234567890",
      "to": "0x0987654321098765432109876543210987654321",
      "value": "0x123456789abc",
      "gas": "0x5208",
      "gasPrice": "0x12a05f200"
    }],
    "id": 1
  }' \
  http://localhost:8545

Then monitor the transaction:

# Poll until receipt is available
while true; do
  response=$(curl -s -X POST \
    -H "Content-Type: application/json" \
    --data '{"jsonrpc":"2.0","method":"eth_getTransactionReceipt","params":["0x..."],"id":1}' \
    http://localhost:8545)

  if echo "$response" | jq -e '.result | .status == "0x1"'; then
    echo "Transaction confirmed at $(date)"
    break
  fi

  sleep 1
done

Latency is not just time to receipt. It includes time to block inclusion, time to confirmation, and time to finality. A transaction may be "mined" but not yet "confirmed" due to slow relayer processing.

A common failure: the transactionHash is not properly encoded. The eth_sendTransaction response returns a transactionHash as a string in 0x format, but the client expects 0x as string or bytes. A mismatch leads to missing transactions.

Testing Event Indexing and Querying

Event indexing is essential for dApps to react to blockchain activity. To test indexing, use psql to query the indexed events and validate correctness.

SELECT block_number, event_name, args->>'sender' as sender, args->>'amount' as amount
FROM events
WHERE event_name = 'Transfer'
  AND block_number BETWEEN 1000000 AND 1000100
ORDER BY block_number;

A failure occurs when the indexer misses events due to incomplete fromBlock or toBlock ranges. Another issue: args is stored as jsonb, but the query expects json, leading to type mismatches.

To test indexer performance, generate a load of 1000 Transfer events and measure query latency:

const transfers = Array.from({ length: 1000 }, (_, i) => ({
  from: `0x${(i + 1).toString(16).padStart(40, '0')}`,
  to: `0x${(i + 2).toString(16).padStart(40, '0')}`,
  value: BigInt(1000000000000000000 + i),
}));

for (const transfer of transfers) {
  await bridge.transfer(transfer.to, transfer.value, { gasLimit: 200000 });
}

Then measure how long it takes to query all transfers:

SELECT COUNT(*) FROM events WHERE event_name = 'Transfer';

If the query takes more than 500ms for 1000 events, the indexer is not optimized.

Finality is not just block finality—event finality, where all events are indexed and queryable, is a distinct concern. A test must verify that events are not only written but also available for querying.

This page was rewritten on 18 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.