Smart Contract Security

Production engineering guide for smart contract security in Web3 and blockchain systems.

Smart contract security is the practice of ensuring correctness, integrity, and resilience of executable code deployed on blockchain networks, particularly Ethereum and EVM-compatible chains. It matters at every stage of the lifecycle: from writing the initial Solidity logic to finalizing a production deployment, and especially during upgrades, audits, and incident response. A single vulnerability in a contract can lead to millions in lost funds, irreversible state corruption, or complete system downtime.

Designing for Security

Security begins at the design phase, where the developer anticipates failure modes and encodes assumptions into code. The most common design decisions involve access control, state management, and error handling.

Access Control Patterns

Use modifier and require statements consistently to enforce permissions. For example, a onlyOwner modifier enforces that only the contract’s owner can call certain functions:

modifier onlyOwner() {
    require(msg.sender == owner, "Only owner can call this function");
    _;
}

This pattern is effective, but subtle failures arise when owner is not properly initialized or when ownership is transferred without updating the storage variable. A common mistake is omitting owner initialization in the constructor:

constructor() {
    owner = msg.sender;
}

This assumes msg.sender is set correctly, but in a multisig environment, the contract may be deployed by a 0x... address that is not the intended owner. To ensure correctness, always verify initialization using assert:

constructor() {
    owner = msg.sender;
    assert(owner != address(0));
}

The assert statement generates a PANIC error code 0x01 if the condition fails, which is critical in a production environment where gas costs matter.

State Management and Reentrancy

State changes must be atomic and idempotent. A typical error occurs when a function updates multiple state variables but fails midway due to out-of-gas (OOG) or transaction reversion.

Use the Checks-Effects-Interactions (CEI) pattern to prevent reentrancy attacks:

function transfer(address to, uint256 amount) external {
    // Checks
    require(balances[msg.sender] >= amount, "Insufficient balance");

    // Effects
    balances[msg.sender] -= amount;
    balances[to] += amount;
    emit Transfer(msg.sender, to, amount);

    // Interactions
    (bool success, ) = to.call(abi.encodeWithSignature("receivePayment(uint256)", amount));
    require(success, "Transfer to receiver failed");
}

The abi.encodeWithSignature call generates a calldata payload for the receivePayment function, and call sends a 0 value by default. If the recipient contract reverts during receivePayment, the entire transaction rolls back, but the balances update remains—leading to inconsistent state.

A common failure mode is the reentrancy attack when the recipient contract calls back into the calling contract before the first function completes. To prevent this, use reentrancyGuard:

uint256 private _reentrancyLock = 1;

modifier nonReentrant() {
    require(_reentrancyLock == 1, "Reentrant call");
    _reentrancyLock = 2;
    _;
    _reentrancyLock = 1;
}

This lock mechanism uses a single storage slot and prevents nested calls. The 2 value is used during execution, and the slot is reset to 1 after completion. A subtle failure occurs when a function calls another function that is itself nonReentrant—the lock is not shared across calls, so nested calls can proceed simultaneously.

Writing Secure Code

Code-level security focuses on avoiding common vulnerabilities and encoding assumptions into the contract's behavior.

Handling Ether Transfers

Transferring ETH to a contract must account for payable functions and transfer vs send vs call.

Use receive and fallback functions to handle incoming ETH:

receive() external payable {
    emit Deposit(msg.value);
}

fallback() external payable {
    emit Deposit(msg.value);
}

The receive function is called when ETH is sent directly to the contract (e.g., eth_call), while fallback is called during a call with data. A common mistake is using transfer for large ETH payments:

function deposit() external payable {
    require(msg.value > 0, "Must send ETH");
    balances[msg.sender] += msg.value;
    emit Deposit(msg.sender, msg.value);
}

But transfer sends a fixed amount of 2300 gas, which may be insufficient for complex logic. For larger transfers, use call with explicit gas:

(bool success, bytes memory data) = address(this).call{value: amount, gas: 100000}(
    abi.encodeWithSignature("deposit()", amount)
);
require(success, "Deposit failed");

The call method allows for a custom gas limit and returns both success and data from the called function, enabling better error handling.

Error Handling with Custom Errors

Solidity 0.8.0 introduced error declarations, replacing revert with error strings. Use them for clarity and consistency:

error InsufficientBalance(address account, uint256 balance, uint256 required);
error InvalidAddress(address addr);
error InvalidAmount(uint256 amount);

function withdraw(uint256 amount) external {
    if (balances[msg.sender] < amount) {
        revert InsufficientBalance(msg.sender, balances[msg.sender], amount);
    }
    balances[msg.sender] -= amount;
    payable(msg.sender).transfer(amount);
    emit Withdrawal(msg.sender, amount);
}

The revert instruction generates a revert reason code, and the ABI encodes the error name and parameters. Clients can decode these errors and display user-friendly messages.

Deploying with Security in Mind

Deployment is not a one-off step but a critical phase where security assumptions are tested and validated.

Deployment Scripts with Hardhat

Use Hardhat to automate deployments with consistent configurations:

const hre = require("hardhat");

async function main() {
    const MyContract = await hre.ethers.getContractFactory("MyContract");
    const myContract = await MyContract.deploy("Initial Value");

    await myContract.waitForDeployment();

    const address = await myContract.getAddress();
    console.log("MyContract deployed to:", address);

    // Verify on Etherscan
    await hre.run("verify:verify", {
        address: address,
        constructorArguments: ["Initial Value"],
    });
}

main().catch((error) => {
    console.error(error);
    process.exitCode = 1;
});

The verify:verify task calls Etherscan’s API to verify the contract’s source code, enabling users to view the full Solidity code directly on the blockchain.

Deployment Configuration

Configuration is stored in hardhat.config.js:

module.exports = {
    solidity: "0.8.21",
    networks: {
        hardhat: {
            chainId: 1337,
            accounts: {
                mnemonic: "test test test test test test test test test test test test",
            },
        },
        goerli: {
            url: "https://goerli.infura.io/v3/your-project-id",
            accounts: [process.env.PRIVATE_KEY],
            gasPrice: 10000000000, // 10 gwei
        },
        mainnet: {
            url: "https://mainnet.infura.io/v3/your-project-id",
            accounts: [process.env.PRIVATE_KEY],
            gasPrice: 15000000000, // 15 gwei
            gas: 3000000,
        },
    },
    etherscan: {
        apiKey: process.env.ETHERSCAN_API_KEY,
    },
};

This configuration enables consistent deployment across testnets and mainnet. The gas and gasPrice fields ensure that transactions are optimized and predictable.

Post-Deployment Checks

After deployment, verify that the contract behaves as expected:

npx hardhat run scripts/check-deployment.js --network goerli

The script checks for:

A typical check:

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

async function checkDeployment() {
    const MyContract = await ethers.getContractFactory("MyContract");
    const myContract = await MyContract.attach("0x..."); // deployed address

    const owner = await myContract.owner();
    console.log("Owner is:", owner);

    const value = await myContract.getValue();
    console.log("Initial value is:", value.toString());

    const tx = await myContract.setValue("Updated Value");
    await tx.wait();

    const newValue = await myContract.getValue();
    console.log("Value after update:", newValue.toString());

    // Ensure event was emitted
    const filter = myContract.filters.ValueChanged();
    const events = await myContract.queryFilter(filter);
    console.assert(events.length > 0, "ValueChanged event not emitted");
}

checkDeployment().catch(console.error);

This script runs after deployment and logs output that can be captured in CI/CD pipelines.

Auditing and Testing

Auditing is the process of systematically evaluating a contract’s behavior and correctness. It involves unit tests, integration tests, and formal verification.

Unit Testing with Foundry

Use Foundry for fast, comprehensive testing:


[profile.default]
src = "src"
test = "test"
out = "out"
libs = ["lib"]
remappings = ["@openzeppelin/=lib/openzeppelin-contracts"]

[profile.test]
gas = 1000000

A test file test/MyContract.t.sol:

import "forge-std/Test.sol";
import "../src/MyContract.sol";

contract MyContractTest is Test {
    MyContract public myContract;

    function setUp() public {
        myContract = new MyContract("Initial");
        vm.deal(address(this), 100 ether);
    }

    function testTransfer() public {
        myContract.transfer(address(1), 1000);

        assertEq(myContract.balances(address(1)), 1000);
        assertEq(myContract.balances(address(this)), 99000);
    }

    function testRevertOnInsufficientBalance() public {
        vm.expectRevert(bytes("Insufficient balance"));
        myContract.transfer(address(1), 100000);
    }
}

The vm.deal function sends ETH to an account, and vm.expectRevert checks that a transaction reverts with a specific error.

Integration Testing with Hardhat

For integration testing, use Hardhat to simulate multiple contracts and transactions:

describe("Staking Pool", function () {
    let pool, token, owner, addr1, addr2;

    beforeEach(async function () {
        [owner, addr1, addr2] = await ethers.getSigners();

        const Token = await ethers.getContractFactory("ERC20Mock");
        token = await Token.deploy("Test Token", "TST");

        const Pool = await ethers.getContractFactory("StakingPool");
        pool = await Pool.deploy(token.address);
    });

    it("should deposit and withdraw", async function () {
        await token.connect(owner).approve(pool.address, 1000);
        await pool.connect(owner).deposit(500);

        expect(await pool.balanceOf(owner.address)).to.equal(500);
        expect(await token.balanceOf(pool.address)).to.equal(500);

        await pool.connect(owner).withdraw(250);

        expect(await pool.balanceOf(owner.address)).to.equal(250);
        expect(await token.balanceOf(pool.address)).to.equal(250);
    });
});

This test suite validates the interaction between two contracts, ensuring that staking and token transfers work correctly.

Incident Response and Monitoring

When a contract fails in production, the response must be fast and systematic.

Error Handling in Production

A common failure is the out-of-gas (OOG) error, where a transaction runs out of gas and reverts. The error is signaled by the PANIC code 0x01 in the transaction receipt.

Use try...catch in Solidity to handle OOG:

function safeDeposit(address to, uint256 amount) external {
    (bool success, ) = address(this).call{value: amount, gas: 200000}(
        abi.encodeWithSignature("deposit(address,uint256)", to, amount)
    );
    if (!success) {
        emit DepositFailed(to, amount);
    }
}

The call returns success and data, and if the call fails (e.g., due to OOG), the function logs a DepositFailed event.

Monitoring with Node Operators

Node operators monitor contracts by querying the blockchain using eth_getLogs and eth_call.

Example query:

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "eth_getLogs",
  "params": [
    {
      "fromBlock": "0x123456",
      "toBlock": "latest",
      "address": "0x1234567890123456789012345678901234567890",
      "topics": [
        "0x0d1093366c5e501cb6b2534a19191d4530e5159d56149b1b117568b34c278098"
      ]
    }
  ]
}

This query retrieves all ValueChanged events from a specific contract, enabling real-time monitoring.

Alerting on Critical Events

Set up alerts using eth_subscribe to monitor for new blocks, transactions, or specific events:

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "eth_subscribe",
  "params": [
    "logs",
    {
      "address": "0x1234567890123456789012345678901234567890",
      "topics": [
        "0x0d1093366c5e501cb6b2534a19191d4530e5159d56149b1b117568b34c278098"
      ]
    }
  ]
}

This subscription triggers when a new ValueChanged event is emitted, allowing systems to react in real time.

Summary of Key Patterns

These practices ensure that smart contracts are correct, resilient, and maintainable across evolving blockchain environments.

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.