Why view and pure functions deserve careful design

In Solidity, view functions read blockchain state without modifying it, while pure functions do not read or modify state at all. Both are intended to be safe, predictable helpers, but they serve different purposes.

A view function is appropriate when the result depends on storage, balances, timestamps, or other on-chain data. A pure function is appropriate when the output depends only on the input parameters and internal computation.

This distinction matters because:

  • view functions can still be called on-chain by other contracts, where gas costs matter.
  • pure functions are easier to test and reuse because they have no external dependencies.
  • Both function types are commonly used in off-chain reads, where unexpected reverts or ambiguous return values create integration problems.

A good rule is simple: if a function can be pure, make it pure. If it must read state, keep it view and make the dependency explicit.


Choose the narrowest possible function type

The most common mistake is marking a function view when it could be pure, or writing a view function that reads more state than necessary.

Prefer pure for deterministic computation

Use pure for formatting, validation, math, hashing inputs, and transforming data.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

library FeeMath {
    function calculateFee(uint256 amount, uint256 bps) internal pure returns (uint256) {
        require(bps <= 10_000, "Invalid bps");
        return (amount * bps) / 10_000;
    }

    function isValidAddress(bytes20 raw) internal pure returns (bool) {
        return raw != bytes20(0);
    }
}

These functions are predictable because they depend only on their arguments. They are easy to test and safe to reuse in other contracts.

Use view only when state is required

If the result depends on storage, the function should say so clearly.

contract Vault {
    mapping(address => uint256) private balances;

    function balanceOf(address account) external view returns (uint256) {
        return balances[account];
    }
}

This function is simple, explicit, and easy for integrators to understand.


Make dependencies obvious in the function signature

A well-designed read-only function should expose the data it needs through parameters rather than hiding assumptions in contract state.

Good: explicit inputs

function previewMint(
    uint256 assets,
    uint256 totalAssets,
    uint256 totalSupply
) external pure returns (uint256 shares) {
    if (totalSupply == 0) return assets;
    return (assets * totalSupply) / totalAssets;
}

This style is useful for “preview” helpers because it makes the calculation portable and testable. It also avoids accidental dependence on storage values that may change between calls.

Less ideal: hidden dependencies

function previewMint(uint256 assets) external view returns (uint256) {
    if (totalSupply == 0) return assets;
    return (assets * totalSupply) / totalAssets;
}

This version is valid, but it is less transparent. Callers must know that the result depends on current contract state, and the function is harder to reuse in off-chain simulations.

A practical guideline is to ask: “Could this calculation be reused in a script, frontend, or another contract without needing the whole contract context?” If yes, prefer a pure helper with explicit inputs.


Avoid side effects and hidden state reads

Even though view and pure functions cannot modify state, they can still create problems if they rely on indirect behavior.

Do not call external contracts unless necessary

A view function can technically call another contract’s view function, but that introduces risk:

  • the external contract may revert,
  • the returned value may change unexpectedly,
  • the call may become expensive,
  • the function is no longer self-contained.

If you need external data, isolate it in a dedicated function and document the dependency clearly.

Avoid reading mutable globals unless required

Functions that depend on block.timestamp, block.number, msg.sender, or address(this) are not inherently wrong, but they should be used intentionally.

Global valueSuitable forCaution
block.timestampTime-based previews, vesting checksCan vary between blocks and should not be treated as exact time
block.numberEpoch-based logicLess intuitive than timestamps for users
msg.senderCaller-specific viewsResults differ by caller, which can confuse off-chain consumers
address(this)Contract-specific calculationsUsually stable, but still a runtime dependency

If a function’s output changes based on the caller, make that clear in the name or documentation. For example, claimableFor(address account) is clearer than claimable() if the result depends on the provided account.


Design read-only helpers for integration, not just internal convenience

Many view and pure functions exist to support external systems. Frontends, bots, and indexers rely on them for previews, validation, and display logic. That means the API should be stable and easy to consume.

Use descriptive names

Good names reduce ambiguity:

  • previewDeposit
  • estimateWithdraw
  • isExpired
  • normalizedAmount
  • feeForAmount

Avoid vague names like getValue, calc, or check, which do not explain what is being computed.

Return structured data when it improves clarity

A single return value is fine for simple helpers. For more complex previews, return a tuple or struct-like set of values so callers do not need to recompute derived data.

function quoteSwap(uint256 amountIn)
    external
    view
    returns (uint256 amountOut, uint256 fee, uint256 priceImpact)
{
    fee = (amountIn * feeBps) / 10_000;
    amountOut = _simulateSwap(amountIn - fee);
    priceImpact = _estimatePriceImpact(amountIn);
}

This is often better than forcing callers to make several calls or reverse-engineer the result from a single opaque number.


Keep calculations deterministic and bounded

Read-only functions should be predictable in both result and cost. A function that is technically view but expensive to execute can still cause problems when called on-chain.

Avoid unbounded loops in public read functions

A view function that iterates over a large array or mapping can become unusable as state grows. Even if it works off-chain, other contracts may not be able to call it economically.

Prefer precomputed aggregates or pagination.

function userPositionCount(address user) external view returns (uint256) {
    return positions[user].length;
}

function positionAt(address user, uint256 index) external view returns (Position memory) {
    require(index < positions[user].length, "Index out of bounds");
    return positions[user][index];
}

This pattern is more scalable than returning an entire list in one call.

Keep math stable and explicit

Use clear scaling factors and document units. For example, if a function returns basis points, say so in the name or comments. If it returns token amounts, specify decimals assumptions.

A common source of bugs is mixing raw integers with human-readable units. A pure helper can prevent this by normalizing values in one place.

function toWad(uint256 amount, uint8 decimals) internal pure returns (uint256) {
    if (decimals == 18) return amount;
    if (decimals < 18) return amount * (10 ** (18 - decimals));
    return amount / (10 ** (decimals - 18));
}

This kind of helper is ideal as pure because it depends only on inputs.


Use view and pure functions as a contract API layer

A strong Solidity codebase often separates internal business logic from external read APIs. This keeps the contract easier to maintain and reduces duplication.

Pattern: internal logic plus external preview wrapper

contract StakingPool {
    uint256 public totalStaked;
    uint256 public rewardRate;

    function _pendingReward(uint256 stake, uint256 elapsed) internal pure returns (uint256) {
        return (stake * elapsed) / 1 days;
    }

    function pendingReward(address user) external view returns (uint256) {
        uint256 stake = _stakeOf(user);
        uint256 elapsed = block.timestamp - lastUpdate[user];
        return _pendingReward(stake, elapsed) * rewardRate / 1e18;
    }

    function _stakeOf(address user) internal view returns (uint256) {
        return stakes[user];
    }

    mapping(address => uint256) private stakes;
    mapping(address => uint256) private lastUpdate;
}

This structure has two benefits:

  1. The core calculation is reusable and testable.
  2. The external function remains focused on state access and presentation.

If the business logic changes, you can update the internal helper without rewriting every external read function.


Document revert conditions and edge cases

Read-only functions are often assumed to be “safe,” but they can still revert. That is acceptable when the revert is intentional and documented.

Common reasons for reverts include:

  • invalid indexes,
  • division by zero,
  • stale or uninitialized state,
  • unsupported token decimals,
  • overflow checks in arithmetic.

Be explicit about these cases in NatSpec comments or developer documentation. For example:

/// @notice Returns the user's withdrawable balance.
/// @dev Reverts if the account has not been initialized.
function withdrawable(address account) external view returns (uint256) {
    require(initialized[account], "Account not initialized");
    return balances[account] - locked[account];
}

This makes the contract easier to integrate because callers know what to expect.


Practical checklist for safe read-only functions

Before shipping a view or pure function, review the following:

  • Can this function be pure instead of view?
  • Does the function depend on only the data it truly needs?
  • Are the inputs and outputs named clearly?
  • Is the function deterministic for the same inputs and state?
  • Could the function become too expensive as state grows?
  • Are all revert conditions intentional and documented?
  • Would a caller understand whether the result is caller-specific or global?

If the answer to any of these is unclear, the function probably needs a redesign.


Summary of design choices

GoalRecommended approachWhy it helps
Deterministic computationUse pureEasier testing and reuse
State-dependent readsUse viewMakes dependencies explicit
Frontend previewsReturn clear, named valuesReduces integration errors
Large datasetsUse pagination or indexed accessPrevents expensive calls
Reusable mathExtract internal pure helpersAvoids duplication
Caller-specific resultsInclude the relevant address in the signatureMakes behavior obvious

The best read-only Solidity functions are small, explicit, and boring in the best sense: they do exactly one thing, depend on exactly the right inputs, and behave the same way every time those inputs are the same.

Learn more with useful resources