🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Smart Contract Attack Vectors and Defense Patterns

Blockchain SecurityđŸŸĸ Free Lesson
Blockchain Security

The one-line mental model

Every contract on a public chain is running in a hostile network with its source visible, its entry points open, and its value permanently on display, so security means assuming every external call and every price input can be turned against you.

Prerequisites

  • !Solidity function calls, msg.sender, and low-level call
  • !How a transaction trace records state changes and logs

What You'll Learn

  • 1Reproduce a reentrancy drain and explain why the fix is ordering, not luck
  • 2Audit a contract's external call surface for access-control gaps
  • 3Explain how a flash loan turns a thin market into a false price
  • 4Design a response plan that assumes a bug will be found after deployment

Start with the threat model, not the checklist

Security reviews that begin with a list of known bugs tend to find known bugs and miss everything else. Begin instead with assets and adversaries: what value does this contract hold, who is allowed to move it, what inputs does it trust, and who benefits if each of those assumptions fails. A vault that holds no funds has a different posture than one holding a hundred million, even if the code is nearly identical.

Then enumerate the contract's external surface. Every function callable by an untrusted address, every call or transfer to an address derived from user input, every price read from an oracle, and every delegatecall into a target chosen at runtime is a doorway. The review question is not whether each doorway is intended to be open, but whether it can be used from an angle you did not consider.

Reentrancy: the bug that keeps teaching

Reentrancy is not a quirk of one language; it is the general hazard of making an external call in the middle of state-dependent logic. The attacker supplies a contract whose fallback function re-enters the victim before bookkeeping is complete:

// Vulnerable: state updated after the external call
contract Bank {
    mapping(address => uint256) public balances;

    function deposit() external payable {
        balances[msg.sender] += msg.value;
    }

    function withdraw() external {
        uint256 amount = balances[msg.sender];
        (bool ok, ) = msg.sender.call{value: amount}("");
        require(ok, "send failed");
        balances[msg.sender] = 0;   // too late: already re-entered
    }
}

// Attacker: drains far more than the deposit
contract Attacker {
    Bank public bank;

    constructor(Bank _bank) {
        bank = _bank;
    }

    function attack() external payable {
        bank.deposit{value: 1 ether}();
        bank.withdraw();
    }

    receive() external payable {
        if (address(bank).balance >= 1 ether) {
            bank.withdraw();
        }
    }
}

The canonical fixes all target the same root cause. Checks-effects-interactions updates state before handing control outward. A reentrancy guard makes re-entry revert outright. Pull-over-push removes the external call from the critical path entirely by letting users withdraw their own funds. Applying all three to a fund-moving function is not over-engineering; it is what auditors expect to see.

Access control and the functions you forgot about

The second most common class of loss is a function that should never have been callable by the public, usually an initialization function left exposed or an administrative setter missing its gate. A pattern that looks safe can hide the problem in an inherited base: an initialize function on a proxy is equivalent to a constructor, and if anyone can call it first, anyone can become the owner of your deployed protocol.

Two Solidity specifics matter here. tx.origin is the original signer, not the immediate caller, so using it for authorization allows a phishing contract to act through a user who interacted with it. delegatecall executes another contract's code in your storage context, so any delegatecall to a user-influenced address is a total loss of the contract's state, no matter how innocent the surrounding logic appears.

Price manipulation and the flash-loan window

Protocols that read a spot price from a single liquidity pool inherit the pool's manipulation cost, which for a small pool can be a few ether. A flash loan raises that cost to zero for the duration of one transaction, because the attacker never needs to hold capital and the whole sequence reverts if the price cannot be moved far enough to profit:

python
def can_profit_from_oracle_manipulation(
    pool_depth, flash_fee=0.0009, required_move=0.30, target_profit=50_000
):
    """Crude model: is moving the price worth attempting against a thin pool?"""
    # Moving price by X percent in a constant-product pool costs roughly
    # (sqrt(1 + X) - 1) of the pool's depth in input capital.
    needed = pool_depth * ((1 + required_move) ** 0.5 - 1)
    cost = needed * flash_fee  # premium paid on the flash loan
    return target_profit > cost, needed, cost


ok, needed, cost = can_profit_from_oracle_manipulation(pool_depth=2_000_000)
print(f"attempt viable: {ok}, capital needed ${needed:,.0f}, fee ${cost:,.2f}")

Defenses stack. A time-weighted average price over many blocks raises the manipulation cost from one block to many. A second, independent feed lets the contract require agreement between sources. A deviation bound rejects any update that moves more than a stated percentage in one observation, which converts a manipulation into a rejected update rather than a bad liquidation.

Front-running, sandwich attacks, and MEV

Every public transaction waits in a mempool where searchers can read it, reorder the block, and place their own transactions around it. A sandwich places a buy before your swap and a sell after it, extracting exactly the price impact you were going to create. The economic damage is bounded but real, and it is unavoidable on any transparent ordering market without mitigation.

VectorRoot causePrimary defense
ReentrancyExternal call mid-logicChecks-effects-interactions, guards
Missing authorizationUn-gated privileged functionModifiers, audited inheritance, tests for each role
Oracle manipulationSpot price trustedTWAPs, multi-source feeds, deviation limits
Front-runningTransparent mempoolCommit-reveal, private relays, slippage bounds
Unbounded loopsGas limit hit mid-operationPull patterns, pagination, caps
delegatecall to untrusted targetArbitrary code in own storageFixed targets, allowlists, proxies with locked implementations
Signature replayMissing chain ID or nonceEIP-712 typed data with domain separators

Privilege separation and key management

The code review only covers half of a protocol's security surface; the other half is who holds the keys that can change or stop it. A single admin key that can upgrade the implementation, mint tokens, and pause withdrawals is a crown jewel, and every hour it exists as a single signature is an hour in which one compromise ends the protocol. The defense is boring and effective: separate the roles, put each behind its own multisig with a different signer set, and place a timelock in front of anything that changes logic.

The second half of key discipline is operational hygiene. Signers should be hardware-backed, ideally in separate jurisdictions, and the ceremony for changing signers should be documented and rehearsed before it is needed. Publish the addresses controlling every privileged role in one place, and let the community verify them. A protocol that says its admin keys are held by a five-of-nine multisig without publishing the nine addresses has told you nothing that can be checked, which is precisely the standard that a public chain makes possible and that most teams fail to meet.

The audit lifecycle that actually reduces risk

Static analysis catches a surprising share of the cheap findings: reentrancy patterns, uninitialized storage, unprotected selfdestruct, dangerous delegatecall. Running Slither in continuous integration costs nothing and should be a merge gate. Symbolic execution tools like Mythril explore paths that tests never hit, and fuzzing frameworks like Echidna let you state an invariant and let the computer search for a counterexample for hours.

What tools do not do is reason about economic incentives. Whether a liquidation bonus is large enough to attract liquidators in a crash, whether a governance quorum can be captured with borrowed tokens, whether a fee switch creates a perverse incentive for a protocol participant — these require a human reading the design against the assumption that every participant is profit-maximizing. Budget for both kinds of review, and run the automated suite on every commit so the expensive review is spent on the questions only a person can answer.

âš ī¸Assume you will need an incident response

The realistic posture is that a bug will be discovered after deployment, possibly by you. Keep a pause mechanism that a small trusted council can trigger quickly, document exactly who is authorized to unpause and under what conditions, and practice the drill. Protocols that paused within minutes of an exploit limited losses that would otherwise have compounded for hours.

Common Mistakes

Treating a passing audit as proof the code is safe

Fix: An audit is a point-in-time review of a specific commit; keep the diff after that commit small, re-audit meaningful changes, and monitor continuously

Relying on a single spot price from a single pool

Fix: Use time-weighted or multi-source oracles with deviation bounds, and assume any single pool can be moved within one block

Leaving administrative powers unlimited after launch

Fix: Scope admin functions narrowly, put them behind a timelock and multisig, and publish the address controlling them

Writing tests only for intended behavior

Fix: Add tests for unauthorized calls, reentrancy attempts, zero amounts, and boundary values; hostile inputs are where the losses come from

Best Practices

  • Make static analysis a CI gate and triage every finding, even the ones you decide to accept
  • Write invariants as executable properties and fuzz them continuously rather than relying on example-based tests
  • Keep an incident runbook with named responders, a tested pause path, and a communication template ready before launch
  • Separate upgrade keys, pause keys, and treasury keys so a single compromise cannot rewrite logic and drain funds at once

Interview Questions

Q1: Why is reentrancy dangerous if Solidity has a call stack limit?

The stack limit bounds recursion depth but not economic damage. Even a few re-entrant calls can drain a vault, and the attacker's fallback can keep re-entering until the contract's balance is gone or the gas runs out, whichever comes first.

Q2: What does a deviation bound on an oracle accomplish?

It rejects updates that move more than a set percentage in one observation, so a single-block manipulation becomes a dropped update rather than a price that liquidations or borrows act on. It trades some freshness for manipulation resistance.

Q3: How should a team respond when an exploit is discovered in production?

Pause affected contracts immediately if a pause path exists, communicate what is known and what users should not do, trace the transaction that exploited the bug, and plan recovery or a fork only after the scope is clear. Speed of containment matters more than completeness of the first statement.

Key Takeaways

  • Security starts from assets and adversaries, then enumerates every external surface, not from a generic checklist
  • Reentrancy is fixed by ordering state updates before external calls, with guards as a second layer
  • Oracle and mempool manipulation are economic attacks that need architectural defenses, not better coding style
  • Static analysis, symbolic execution, and fuzzing catch the mechanical classes; humans catch the incentive classes
  • A tested pause mechanism and a named response plan turn a serious bug into a contained incident
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Related Tutorials

Content with similar topics across other courses

Need Expert Blockchain Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement