Leanpub Header

Skip to main content

Smart Contract Security: Finding DeFi Vulnerabilities

Smart Contract Security: Finding DeFi Vulnerabilities
This book is 100% completeLast updated on 2026-09-16

A Comprehensive Engineering Guide to Smart Contract Auditing, EVM Internals, DeFi Exploitation, Protocol Economics, and Blockchain Security

Smart contracts operate in environments where code, financial assets, cryptographic authorization, and economic incentives interact directly. A subtle implementation error can compromise access controls, corrupt accounting, undermine protocol solvency, or expose digital assets to irreversible loss. Understanding these risks requires more than familiarity with Solidity syntax. It demands a rigorous examination of execution semantics, storage architecture, transaction ordering, protocol mathematics, and the assumptions that connect individual contracts to larger decentralized systems.

Smart Contract Security: Finding DeFi Vulnerabilities is a comprehensive, implementation-focused engineering reference to identifying, analyzing, testing, and mitigating vulnerabilities in Ethereum smart contracts and decentralized finance protocols. Across 40 chapters, it progresses from EVM architecture and Solidity execution to advanced DeFi attack surfaces, automated security analysis, formal verification, real-world exploit investigations, and professional auditing practices.

Minimum price

$27.00

$27.00

You pay

Author earns

$

Also available for 1 book credit with a Reader Membership

PDF
405
Pages
Discussion Forum
About

About

About the Book

Smart Contract Security: Finding DeFi Vulnerabilities

A Comprehensive Engineering Guide to Smart Contract Auditing, EVM Internals, DeFi Exploitation, Protocol Economics, and Blockchain Security

Smart contracts operate in environments where code, financial assets, cryptographic authorization, and economic incentives interact directly. A subtle implementation error can compromise access controls, corrupt accounting, undermine protocol solvency, or expose digital assets to irreversible loss. Understanding these risks requires more than familiarity with Solidity syntax. It demands a rigorous examination of execution semantics, storage architecture, transaction ordering, protocol mathematics, and the assumptions that connect individual contracts to larger decentralized systems.

Smart Contract Security: Finding DeFi Vulnerabilities is a comprehensive, implementation-focused engineering reference to identifying, analyzing, testing, and mitigating vulnerabilities in Ethereum smart contracts and decentralized finance protocols. Across 40 chapters, it progresses from EVM architecture and Solidity execution to advanced DeFi attack surfaces, automated security analysis, formal verification, real-world exploit investigations, and professional auditing practices.

The book approaches smart contract security as a combination of software engineering, adversarial analysis, and economic reasoning. It examines how seemingly correct code can fail under unexpected execution paths, manipulated market conditions, unusual token behavior, or carefully constructed transaction sequences.

The result is a structured exploration of the mechanisms that determine whether smart contracts remain secure under adversarial conditions—and how engineers can build stronger verification, testing, and incident-response processes around them.

What You Will Learn

Understand the foundations of smart contract security, including EVM execution, Solidity semantics, storage layout, memory management, threat modeling, and access control. Examine how privilege escalation, storage collisions, unsafe external calls, and incorrect assumptions about contract state can create exploitable conditions.

Investigate major vulnerability classes, including single-function and cross-contract reentrancy, read-only reentrancy, arithmetic errors, precision loss, denial-of-service conditions, unchecked return values, and transaction-ordering dependencies. Explore how MEV and adversarial transaction sequencing influence the security of protocols that depend on predictable execution order.

Analyze the mathematical and economic foundations of decentralized finance. Study automated market maker invariants, oracle manipulation, time-weighted average prices, flash-loan-assisted attacks, lending health factors, bad debt generation, yield aggregator share inflation, liquid staking derivatives, and ERC-4626 vault accounting.

Explore the security implications of cross-chain bridges, message relaying, validator authorization, signature verification, replay protection, EIP-712 typed data, governance mechanisms, proxy-based upgradeability, and diamond-pattern architectures. Understand how trust boundaries and integration assumptions can introduce vulnerabilities that are not apparent when individual contracts are examined in isolation.

Develop practical auditing and verification skills using Slither, Semgrep, Echidna, Foundry, property-based testing, invariant testing, symbolic execution, and formal verification with Certora. Learn how forked-mainnet simulations and automated testing pipelines help evaluate contract behavior under realistic conditions.

Finally, examine major security incidents, professional audit reporting, protocol solvency analysis, incident response, circuit breakers, responsible disclosure, and whitehat operations.

EVM Architecture and Smart Contract Execution

Effective auditing begins with understanding the execution environment in which a contract operates. Solidity source code is transformed into EVM bytecode, executed through a stack-based virtual machine, and evaluated against persistent storage, transient execution state, transaction context, and gas constraints.

This book examines the relationship between Solidity semantics and low-level EVM behavior, including storage slots, memory management, execution flow, and the assumptions developers make about contract state. It explores how storage-layout errors and slot collisions can affect proxy systems and how access-control weaknesses can expose privileged operations.

Threat modeling provides the foundation for identifying security-critical assets, trust boundaries, external dependencies, and attacker capabilities. Rather than treating each function as an isolated unit, the analysis considers how multiple contracts, administrative roles, external calls, and protocol components interact.

These foundations establish a systematic approach to understanding how implementation details become security properties—and how incorrect assumptions can undermine those properties.

Reentrancy, Arithmetic Errors, and Execution-Level Vulnerabilities

Smart contract vulnerabilities frequently emerge from unexpected interactions between control flow, external calls, and state transitions.

The book explores conventional reentrancy, cross-function reentrancy, cross-contract reentrancy, and read-only reentrancy. It examines how external interactions can expose intermediate states, violate accounting assumptions, or allow another contract to act before the original operation has completed.

Arithmetic analysis extends beyond basic overflow and underflow conditions. Precision loss, rounding behavior, unit mismatches, and incorrect scaling can affect balances, exchange rates, collateral requirements, and share calculations. The discussion connects these implementation details to the financial consequences they can produce.

Additional chapters investigate denial-of-service patterns, unchecked return values, low-level call behavior, and other execution-level weaknesses. The objective is to understand not only how these vulnerabilities arise, but also how defensive design, explicit validation, and systematic testing can reduce their likelihood.

DeFi Protocol Mathematics and Economic Attack Surfaces

Decentralized finance introduces security challenges that cannot be understood through code inspection alone. Protocols depend on mathematical invariants, market prices, liquidity conditions, collateral models, and assumptions about the behavior of external assets.

The book examines automated market makers and the invariants governing liquidity pools. It explores how oracle manipulation and weaknesses in spot-price or TWAP assumptions can affect borrowing limits, collateral valuation, liquidations, and other protocol decisions.

Flash loans provide another important case study in adversarial composition. By temporarily obtaining substantial liquidity within a transaction, an attacker may be able to influence prices, exploit accounting discrepancies, or manipulate protocol state when safeguards depend on assumptions that do not hold across an entire transaction.

Lending protocols, yield aggregators, liquid staking derivatives, and ERC-4626 vaults introduce additional accounting and solvency considerations. The analysis covers health-factor weaknesses, bad debt generation, share inflation, depegging risks, and integration problems involving nonstandard token behavior.

These topics demonstrate why secure DeFi engineering requires both code-level verification and a rigorous understanding of the economic properties that the implementation is supposed to preserve.

Cross-Chain Security, Signatures, and Upgradeable Architectures

Smart contract security extends across cryptographic authorization, governance, contract deployment, and interactions between independent blockchain systems.

The book examines cross-chain bridge architectures, message relaying, proof verification, and validator authorization. It considers how failures in authentication, message validation, or trust assumptions can compromise systems that move information or assets between chains.

Signature verification receives dedicated attention, including replay attacks, typed-data signing, and EIP-712 integration. The discussion connects cryptographic authorization to the precise interpretation of signed messages, contract state, and execution context.

Governance mechanisms introduce another class of security risks. Flash-loan voting, proposal hijacking, and weaknesses in authorization or voting assumptions can allow adversarial actors to influence protocol decisions.

Upgradeable contracts require careful treatment of storage compatibility, initialization, delegated execution, and administrative authority. The book explores proxy patterns and diamond architectures, emphasizing how modularity and upgrade flexibility can introduce additional attack surfaces when their security assumptions are not rigorously enforced.

The broader objective is to understand how security depends on the complete system architecture rather than on the apparent correctness of individual functions.

Automated Analysis, Fuzzing, and Formal Verification

Reliable smart contract security requires more than manual code review. Automated tools, adversarial testing, and explicit specifications help identify failures that ordinary functional tests may miss.

This book introduces static analysis with Slither, Semgrep, and custom detection rules, demonstrating how automated inspection can reveal suspicious code patterns and support repeatable auditing workflows.

Fuzz testing with Echidna and Foundry explores how generated inputs, sequences of calls, and unexpected state transitions can expose vulnerabilities. Property-based testing and invariant specification extend this approach by defining the conditions that must remain true throughout contract execution.

The discussion also covers symbolic execution and formal verification using Certora, connecting implementation behavior to explicit security properties and verification conditions.

Forked-mainnet simulations provide a practical environment for investigating deployed protocols, reproducing relevant states, and testing interactions with existing contracts. These techniques are considered alongside advanced Foundry workflows and continuous integration pipelines.

The emphasis is on combining complementary methods: static analysis to identify potential weaknesses, testing to discover behavioral failures, and formal methods to verify carefully defined properties within their stated assumptions and scope.

Real-World Exploit Analysis and Security Post-Mortems

Understanding historical incidents provides valuable insight into the difference between intended protocol behavior and actual adversarial outcomes.

The book investigates several significant security incidents, including:

  • The DAO Hack — reentrancy, control flow, and the consequences of unsafe external interactions.
  • Euler Finance — donation-related accounting behavior, lending logic, and health-factor failures.
  • Curve/Vyper — reentrancy-lock vulnerabilities and the importance of compiler and implementation correctness.
  • Mango Markets — oracle manipulation, market liquidity, and the relationship between price assumptions and financial exposure.
  • Ronin Bridge — validator compromise, authorization boundaries, and cross-chain trust assumptions.

Each case study focuses on the underlying technical and architectural mechanisms rather than merely recounting the events. The goal is to understand how vulnerabilities developed, which assumptions failed, and what lessons can inform future protocol design and auditing.

Historical exploit analysis also highlights the importance of examining the interaction between code, economic incentives, deployment configuration, and operational security.

Professional Auditing, Protocol Resilience, and Incident Response

Finding a vulnerability is only one part of professional security engineering. Findings must be reproduced, explained, prioritized, and translated into actionable remediation guidance.

The book examines the structure of professional smart contract audit reports, including technical evidence, impact assessment, reproducibility, and remediation recommendations. It explores how security findings can be communicated clearly to developers, protocol teams, and other stakeholders.

Continuous integration and automated security pipelines help incorporate analysis into the software development lifecycle. Protocol solvency modeling and economic stress testing extend verification beyond individual functions to evaluate the behavior of financial systems under adverse conditions.

Incident-response mechanisms receive dedicated treatment, including circuit breakers, pause mechanisms, and operational considerations for limiting damage when unexpected behavior occurs. The final chapters explore bug bounty programs, responsible disclosure, and whitehat operations as components of a broader security process.

Together, these practices connect vulnerability discovery to the ongoing work of maintaining secure, resilient, and auditable decentralized systems.

Who Is This Book For?

This book is intended for Solidity developers, smart contract auditors, DeFi engineers, Web3 security researchers, blockchain developers, protocol architects, and security-focused software engineers.

It is particularly relevant to professionals who want to investigate complex contract interactions, assess DeFi protocol risk, build automated security tooling, evaluate economic attack surfaces, or develop more rigorous testing and verification workflows.

Readers should have a working understanding of programming, blockchain fundamentals, and the basic operation of Ethereum smart contracts. Familiarity with Solidity, the EVM, Foundry, and common DeFi primitives will help readers engage with the more advanced chapters.

The material is designed to connect foundational concepts with practical security analysis, making it relevant both to engineers strengthening their existing workflows and to technically minded researchers developing deeper expertise in smart contract security.

Why This Book?

Smart contract security is not simply a matter of avoiding known coding mistakes. DeFi protocols combine executable code, financial mathematics, cryptographic authorization, governance, external dependencies, and adversarial transaction environments.

A contract may pass ordinary tests while still violating an economic invariant. A mathematically sound mechanism may become unsafe when connected to an unreliable oracle. A secure implementation may be undermined by an upgradeability mistake, compromised authorization, or an integration assumption that fails under unusual conditions.

Smart Contract Security: Finding DeFi Vulnerabilities brings these dimensions together in a unified engineering framework spanning EVM internals, vulnerability analysis, DeFi mathematics, cross-chain security, automated testing, formal verification, exploit post-mortems, and professional auditing.

Across 40 chapters, the book provides a structured foundation for investigating how smart contracts fail, how adversarial conditions expose weaknesses, and how systematic engineering practices can improve the security and resilience of decentralized financial systems.

40 Chapters. EVM Internals. Solidity Security. DeFi Exploitation. Oracle Manipulation. Flash Loans. Cross-Chain Bridges. Foundry. Formal Verification. Professional Auditing.

From execution semantics to economic invariants. From vulnerability discovery to verified properties. From exploit analysis to resilient protocol engineering.

Understand the attack surface. Verify the invariants. Engineer more secure smart contracts.

Author

About the Author

Krzysztof Rybiński

I am an independent technology developer and systems engineer who built my technical path largely through self-directed engineering, experimentation, and continuous learning outside a traditional academic or corporate technology career.

My professional background began far from the technology industry. I spent years working in manufacturing, while independently developing my knowledge of software engineering, computer systems, and advanced computing. Over time, that self-directed work evolved into a broad technical practice spanning autonomous AI, cybersecurity, systems programming, GPU computing, automation, and advanced computational architectures.

Today, I design, build, and publish projects involving agentic AI, autonomous defense systems, SIEM/EDR integration, secure software architecture, C/C++, Go, Python, CUDA, quantum computing, cryptography, and privacy-oriented local AI infrastructure.

I approach technology from a systems perspective — from low-level software, memory architecture, and GPU performance to distributed systems, intelligent agents, and high-assurance security architectures.

I also explore aerospace and high-assurance software concepts, including safety-critical architectures, multi-level security, cross-domain solutions, and advanced computational systems.

Alongside active development, I publish long-form engineering projects covering AI, cybersecurity, cloud engineering, quantum computing, GPU programming, cryptography, automation, blockchain, and aerospace engineering.

My current focus is on autonomous software agents, privacy-first local infrastructure, advanced computing, and reliable systems designed to operate with a high degree of independence.

I am open to opportunities involving AI engineering, cybersecurity, software engineering, autonomous systems, HPC/GPU computing, and advanced technology development.

https://businessofmachines.blogspot.com/

https://learn.microsoft.com/en-us/users/machinadeusex/

https://g.dev/machinadeusex

https://github.com/porucznikswext-source

https://www.linkedin.com/in/krzysztof-r-93a37b287/

Get the free sample chapters

Click the buttons to get the free sample in PDF or EPUB, or read the sample online here

Also by the Author

Also by the Author

The Leanpub 60 Day 100% Happiness Guarantee

Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.

See full terms...

Earn $8 on a $10 Purchase, and $16 on a $20 Purchase

We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.

(Yes, some authors have already earned much more than that on Leanpub.)

Learn more about writing on Leanpub

Free Updates. DRM Free.

If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).

Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.

Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.

Learn more about Leanpub's ebook formats and where to read them

Write and Publish on Leanpub

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.

Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub