Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 47 ยท Security

Common Vulnerabilities

Learn the classic smart contract bugs: reentrancy, tx.origin, unchecked calls, front-running, denial of service, weak randomness and signature replay.

Smart contracts hold money, run in public and cannot be patched by default. Anyone can read the code, call every public function and replay attacks until they work. A bug that would be a minor annoyance in a web app can drain millions here, so security is not a final polish step: it shapes how you write every function.

This lesson is a tour of the bugs that appear again and again. For each one you will see the idea, the Solidity shape of the mistake, the standard fix and a small JavaScript stand-in so that you can watch the attack happen. The stand-ins are not Solidity and run no EVM: they model the logic of the attack with plain objects. The vulnerable patterns themselves are real.

Eight classic mistakes

Reentrancy Money leaves before the books are updated.
tx.origin Wrong identity used for permission.
Ignored results A failed call that nobody checks.
Front-running Someone sees your move first.
1 / 2

Reentrancy

When your contract sends ether to another contract, the receiver's code runs. That code can call back into your contract before your first function has finished. If your function paid out first and updated its records afterwards, the callback sees stale records and can withdraw again.

SOLIDITY
// VULNERABLE: pays first, records afterwards
function withdraw() external {
    uint256 amount = deposits[msg.sender];
    require(amount > 0, "nothing to withdraw");
    (bool ok, ) = msg.sender.call{value: amount}("");
    require(ok, "send failed");
    deposits[msg.sender] = 0;
}

The fix is to update state before any external call (checks, effects, interactions), or to lock the function with a guard. The next lesson takes this bug apart step by step. Here is the attack in a stand-in: the bank hands ether to the caller and the caller's receive hook calls withdraw again.

JS A reentrancy drain

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Mallory put in one ether and left with eleven, because every nested withdraw still saw her deposit as one.

tx.origin and weak identity checks

msg.sender is whoever called the current function. tx.origin is the wallet that signed the whole transaction, however many contracts it passed through. Using tx.origin for authorization lets a malicious contract borrow your owner's identity: the owner is tricked into calling a harmless-looking contract, which then calls your contract, and tx.origin still says "owner". See msg.sender, msg.value and Global Variables for the basics.

SOLIDITY
// VULNERABLE
function sendAll(address to) external {
    require(tx.origin == owner, "not owner");   // use msg.sender instead
    payable(to).transfer(address(this).balance);
}

Signature replay

Contracts often accept an off-chain signature: "the owner approves paying 3 ether to Bob". If the contract only checks that the signature is valid, anyone can submit the same signature again, and again. A safe signed message includes a nonce that the contract marks as used, the contract address and the chain id (so it cannot be replayed on a copy or on another network). The standard way to structure this is EIP-712 typed data.

JS Signature replay and tx.origin

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Unchecked return values

Low-level calls (call, send, delegatecall, staticcall) do not revert when the callee fails. They return false and keep going. If you ignore that boolean, your contract may record a payment that never happened.

SOLIDITY
// VULNERABLE: ignores the result
payable(winner).send(prize);
claimed[winner] = true;

// Better
(bool ok, ) = payable(winner).call{value: prize}("");
require(ok, "payment failed");

The same trap exists for tokens. Most ERC-20 tokens return true on success, but some famous ones return nothing at all, and a few return false instead of reverting. Libraries such as OpenZeppelin's SafeERC20 handle both cases (Using OpenZeppelin).

Integer assumptions

Since Solidity 0.8, arithmetic is checked and overflow reverts (Integers, Overflow and Checked Math). That removes a whole class of bugs but not all of them:

  • Code inside an unchecked { ... } block can still wrap around.
  • Casting to a smaller type, such as uint8(x), silently truncates high bits.
  • Integer division rounds down, so amount * fee / 10000 and amount / 10000 * fee give different results, and tiny amounts can round to zero.
  • Mixing decimals (a 6-decimal token with an 18-decimal one) gives answers off by a factor of a trillion.

Write tests with extreme values (0, 1, the maximum) and see Testing Contracts.

Front-running

Transactions wait in a public pool (the mempool) before a block includes them. Anyone, usually a bot, can see your pending transaction and pay a higher fee to run theirs first. If your transaction was "buy this token at the current price", the bot buys first, raises the price, lets you buy and sells to you at a profit. This is called a sandwich attack. Typical defences are a slippage limit (revert if the price moved more than you accept), commit-reveal schemes (publish a hash first, reveal later), or sending through a private relay. Never design a game where the first person to see a secret answer wins.

Denial of service

One misbehaving party should never be able to block everyone else. Two common causes:

  • Unbounded loops. Looping over a list that anyone can grow eventually costs more gas than a block allows, and the function becomes impossible to call.
  • Push payments. An auction that refunds the previous bidder inside the bid function stops working if that bidder is a contract that always reverts on receiving ether.

The cure is the pull pattern: record what each party is owed and let them withdraw it in their own transaction, so their failure harms only themselves.

Bad randomness

Everything on a blockchain is public and deterministic. block.timestamp, block.number and block.prevrandao are known to the miner or validator and, within the same block, to every contract. A lottery that picks a winner from them can be gamed: an attacking contract calculates the "random" number first and only joins when it wins.

JS Predictable lottery and a blocked auction

Press Run (or Ctrl + Enter) to see the console output here.

No output.

For real randomness use a verifiable source such as a VRF oracle, or a commit-reveal protocol (Oracles, Randomness and Off-Chain Data).

This list is a map, not a checklist you can finish. Real audits also find broken access control, wrong accounting, price-oracle manipulation and unsafe upgrades. Treat any code that moves value as hostile territory.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is tx.origin == owner a dangerous permission check?

    tx.origin is the wallet that signed the transaction, not the immediate caller. Phishing contracts exploit this. Use msg.sender.
  2. 2. A contract verifies an owner's signature but stores no nonce. What can an attacker do?

    A signature proves only that the owner signed that message. Without a consumed nonce (plus contract address and chain id) the same message stays valid forever.
  3. 3. What does a low-level call do when the called contract fails?

    Low-level calls return a success flag. If you ignore it, the contract continues as if the call had worked.
  4. 4. Which pattern prevents one failing recipient from blocking an auction?

    With pull payments a refund that fails only affects the recipient who calls withdraw, not the other bidders.

Summary

  • Reentrancy, tx.origin, ignored return values, integer assumptions, front-running, denial of service, weak randomness and signature replay cause most real losses.
  • Update state before external calls, authorize with msg.sender, check every low-level call result and use SafeERC20 for tokens.
  • Include a nonce, the contract address and the chain id in every signed message.
  • Prefer pull over push payments and avoid unbounded loops.
  • On-chain data is public, so it is never a secret source of randomness.

Next: Reentrancy Step by Step.