Zokyo Auditing Tutorials
  • šŸ”Zokyo Auditing Tutorials
  • šŸ“šTutorials
    • šŸƒTutorial 1: Front-Running
      • šŸš€Prerequisites
      • šŸ“˜Understanding Front-Running
      • šŸ‘“Examples
      • āš’ļøMitigation Steps
      • šŸ¦Resource Bank to more front running examples
      • šŸ¤Front-Running Conclusion
    • 🧱Tutorial 2: Unsafe Casting
      • šŸš€Prerequisites
      • šŸ“˜Understanding Casting
      • šŸ‘“Examples
      • šŸ¤Unsafe Casting Conclusion
    • šŸ‘Tutorial 3: Approvals and Safe Approvals
      • šŸš€Prerequisites
      • šŸ“˜Understanding Approvals
      • šŸ‘“Vulnerability Examples
        • šŸ”ERC20 Approval Reset Requirement
        • 😓Ignoring Return Values from ERC20 approve() Function: Potential Miscount of Successful Approvals
        • 🚫Improper use of Open Zeppelins safeApprove() for Non-zero Allowance Increments
        • 🄾Omitted Approval for Contract Interactions Within a Protocol
        • šŸ¤¦ā€ā™‚ļøFailing to Reset Token Approvals in Case of Failed Transactions or other actions
        • šŸ’­Miscellaneous
        • ERC20 Approve Race Condition Vulnerability
      • āš’ļøSpot the Vulnerability
      • šŸ¤Approvals and Safe Approvals Conclusion
    • ā›“ļøTutorial 4: Block.chainid, DOMAIN_SEPARATOR and EIP-2612 permit
      • šŸš€Prerequisites
      • šŸ“˜Understanding Block.chainid and DOMAIN_SEPARATOR
      • šŸ‘“Examples
      • āš’ļøGeneral Mitigation Steps
      • šŸ¤Tutorial 4 Conclusion
  • šŸ’°Tutorial 5: Fee-On-Transfer Tokens
    • šŸš€Prerequisites
    • šŸ“˜Understanding Fee-On-Transfer
    • šŸ‘“Examples
    • šŸ“˜Links to more fee-on-transfer vulnerability examples
    • šŸ¤Fee-On-Transfer Tokens: Conclusion
  • 🌓Tutorial 6: Merkle Trees
    • šŸš€Prerequisites
    • šŸ“˜Understanding Merkle Trees
    • šŸ”ŽVerification within a Merkle Tree:
    • šŸ“œMerkle Proofs Within Smart Contracts
    • šŸ–‹ļøMerkle Proof Solidity Implementation
    • šŸ›‘Vulnerabilities When Using Merkle Trees
    • šŸ’€Example Vulnerabilities
    • 🧠Exercise
    • šŸ¤Merkle Trees Conclusion
  • 🌳Tutorial 7: Merkle-Patricia Trees
    • šŸš€Prerequisites
    • šŸ“˜Understanding Merkle-Patricia Trees
    • šŸ“•Understanding Merkle-Patrica Trees pt.2
    • šŸ”ŽVerification within a Merkle-Patricia Tree
    • šŸ›‘Vulnerabilities When Using Merkle-Patricia Trees
    • šŸ’€Example Vulnerability
    • šŸ¤Merkle-Patricia Trees: Conclusion
  • šŸ”Tutorial 8: Reentrancy
    • šŸš€Prerequisites
    • šŸ“˜Understanding Reentrancy
    • āš’ļøMitigation
    • šŸ’€The DAO Hack: An In-depth Examination
    • šŸ‘“Examples
    • šŸ¦Resource Bank To More Reentrancy Examples
    • šŸ¤Conclusion: Reflecting on the Reentrancy Vulnerability
  • šŸ”‚Tutorial 9: Read-Only Reentrancy
    • šŸš€Prerequisites
    • šŸ“˜Understanding Read-Only Reentrancy
    • šŸ”ØMitigating Read-Only Reentrancy
    • šŸ‘“Real World Examples
    • šŸ¦Resource Bank To More Reentrancy Examples
    • šŸ¤Read-Only Reentrancy: Conclusion
  • šŸš†Tutorial 10: ERC20 transfer() and safeTransfer()
    • šŸš€Prerequisites
    • šŸ“˜Understanding ERC20 transfer() and safeTransfer()
    • šŸ‘“Examples
    • šŸ¤Conclusion
  • šŸ“žTutorial 11: Low level .call(), .transfer() and .send()
    • šŸš€Prerequisites
    • šŸ“˜Understanding .call, .transfer, and .send
    • šŸ›‘Understanding the Vulnerabilities of .transfer and .send
    • šŸ‘“Examples
    • šŸ¤Low level .call(), .transfer() and .send() conclusion
  • ā˜ŽļøTutorial 12: Delegatecall Vulnerabilities in Precompiled Contracts
    • šŸš€Prerequisites
    • šŸ“³Understanding Delegatecall
    • ā›°ļøEVM, L2s, Bridges, and the Quest for Scalability
    • šŸ—ļøUnderstanding Precompiles in the Ethereum Virtual Machine (EVM)
    • šŸ’»Custom Precompiles
    • šŸ’€Potential Vulnerabilities in EVM Implementations: Overlooked DelegateCall in Precompiled Contracts
    • šŸ‘“Real World Examples
    • šŸ¤Delegatecall and Precompiles: Conclusion
  • 🌊Tutorial 13: Liquid Staking
    • šŸš€Prerequisites
    • šŸ“˜Understanding Liquid Staking
    • šŸ’€Understanding Liquid Staking Vulnerabilities
    • šŸ›‘Example Vulnerability
    • 🐜Example Vulnerability 2
    • šŸ•·ļøExample Vulnerability 3
    • šŸ¤Liquid Staking: Conclusion
  • 🚿Tutorial 14: Slippage
    • šŸš€Prerequisites
    • šŸ“˜Understanding Slippage in Automated Market Makers (AMMs)
    • šŸ’€Understanding the "Lack of Slippage Check" Vulnerability in Automated Market Makers (AMMs) and DEXs
    • 😔On-Chain Slippage Calculations Vulnerability
    • šŸ“›0 slippage tolerance vulnerability
    • šŸ‘“Real World Examples
    • šŸ¦Resource bank to more slippage vulnerabilities
    • šŸ¤Slippage Conclusion
  • šŸ“‰Tutorial 15: Oracles
    • šŸš€Prerequisites
    • šŸ“˜Understanding Oracles
    • šŸ“ˆTypes of price feeds
    • 😔Flash Loans
    • šŸ’€Understanding Oracle Vulnerabilities
      • ā›“ļøThe Danger of Single Oracle Dependence
      • ā¬‡ļøUsing Deprecated Functions
      • āŒLack of return data validation
      • šŸ•Inconsistent or Absent Price Data Fetching/Updating Intervals
    • šŸ”«Decentralized Exchange (DEX) Price Oracles Vulnerabilities
    • šŸ›‘Found Vulnerabilities In Oracle Implementations
      • āš–ļøNewly Registered Assets Skew Consultation Results
      • ⚔Flash-Loan Oracle Manipulations
      • ā›“ļøRelying Only On Chainlink: PriceOracle Does Not Filter Price Feed Outliers
      • āœļøNot Validating Return Data e.g Chainlink: (lastestRoundData)
      • šŸ—ÆļøChainlink: Using latestAnswer instead of latestRoundData
      • 😭Reliance On Fetching Oracle Functionality
      • šŸŽ±Wrong Assumption of 18 decimals
      • šŸ§€Stale Prices
      • 0ļøāƒ£Oracle Price Returning 0
      • šŸ›¶TWAP Oracles
      • šŸ˜–Wrong Token Order In Return Value
      • šŸ—ļømiscellaneous
    • šŸ¤Oracles: Conclusion
  • 🧠Tutorial 16: Zero Knowledge (ZK)
    • šŸš€Prerequisites
    • šŸ“šTheory
      • šŸ”ŒCircom
      • šŸ’»Computation
      • šŸ›¤ļøArithmetic Circuits
      • 🚧Rank-1 Constraint System (R1CS)
      • āž—Quadratic Arithmetic Program
      • āœļøLinear Interactive Proof
      • ✨ZK-Snarks
    • šŸ¤“Definitions and Essentials
      • šŸ”‘Key
      • šŸ˜ŽScalar Field Order
      • 🌳Incremental Merkle Tree
      • āœ’ļøECDSA signature
      • šŸ“ØNon-Interactive Proofs
      • šŸļøFiat-Shamir transformation (or Fiat-Shamir heuristic)
      • 🪶Pedersen commitment
    • šŸ’€Common Vulnerabilities in ZK Code
      • ā›“ļøUnder-constrained Circuits
      • ā—Nondeterministic Circuits
      • 🌊Arithmetic Over/Under Flows
      • šŸ‚Mismatching Bit Lengths
      • šŸŒŖļøUnused Public Inputs Optimized Out
      • 🄶Frozen Heart: Forging of Zero Knowledge Proofs
      • 🚰Trusted Setup Leak
      • ā›”Assigned but not Constrained
    • šŸ›Bugs In The Wild
      • 🌳Dark Forest v0.3: Missing Bit Length Check
      • šŸ”¢BigInt: Missing Bit Length Check
      • šŸš“Circom-Pairing: Missing Output Check Constraint
      • šŸ¹Semaphore: Missing Smart Contract Range Check
      • šŸ”«Zk-Kit: Missing Smart Contract Range Check
      • šŸ¤–Aztec 2.0: Missing Bit Length Check / Nondeterministic Nullifier
      • āøļøAztec Plonk Verifier: 0 Bug
      • šŸŖ‚0xPARC StealthDrop: Nondeterministic Nullifier
      • 😨a16z ZkDrops: Missing Nullifier Range Check
      • 🤫MACI 1.0: Under-constrained Circuit
      • ā„ļøBulletproofs Paper: Frozen Heart
      • šŸ”ļøPlonK: Frozen Heart
      • šŸ’¤Zcash: Trusted Setup Leak
      • 🚨14. MiMC Hash: Assigned but not Constrained
      • šŸš”PSE & Scroll zkEVM: Missing Overflow Constraint
      • āž”ļøPSE & Scroll zkEVM: Missing Constraint
      • 🤨Dusk Network: Missing Blinding Factors
      • 🌃EY Nightfall: Missing Nullifier Range Check
      • šŸŽ†Summa: Unconstrained Constants Assignemnt
      • šŸ“ŒPolygon zkEVM: Missing Remainder Constraint
    • šŸ’æZK Security Resources
  • šŸ¤Tutorial 17 DEX's (Decentralized Exchanges)
    • šŸš€Prerequisites
    • šŸ“šUnderstanding Decentralized Exchanges
    • šŸ’€Common Vulnerabilities in DEX Code
      • šŸ”ŽThe "Lack of Slippage Check" Vulnerability in Automated Market Makers (AMMs) a
      • 😔On-Chain Slippage Calculations Vulnerability
      • šŸ“›Slippage tolerance vulnerability
      • 😵How Pool Implementation Mismatches Pose a Security Risk to Decentralized Exchanges (DEXs)
      • šŸŠā€ā™‚ļøVulnerabilities in Initial Pool Creation - Liquidity Manipulation Attacks
      • šŸ›‘Vulnerabilities In Oracle Implementations
        • āš–ļøNewly Registered Assets Skew Consultation Results
        • ⚔Flash-Loan Oracle Manipulations
        • ā›“ļøRelying Only On Chainlink: PriceOracle Does Not Filter Price Feed Outliers
        • āœļøNot Validating Return Data e.g Chainlink: (lastestRoundData)
        • šŸ—ÆļøChainlink: Using latestAnswer instead of latestRoundData
        • 😭Reliance On Fetching Oracle Functionality
        • šŸŽ±Wrong Assumption of 18 decimals
        • šŸ§€Stale Prices
        • 0ļøāƒ£Oracle Price Returning 0
        • šŸ›¶TWAP Oracles
        • šŸ˜–Wrong Token Order In Return Value
        • šŸ—ļømiscellaneous
      • 🄶Minting and Burning Liquidity Pool Tokens
      • šŸŽ«Missing Checks
      • šŸ”ž18 Decimal Assumption
        • šŸ“ŒUnderstanding ERC20 Decimals
        • šŸ’€Examples Of Vulnerabilities To Do With Assuming 18 Decimals
      • šŸ›£ļøIncorrect Swap Path
      • The Importance of Deadline Checks in Swaps
    • šŸ¤Conclusion
  • šŸ¤–Tutorial 18: Proxies
    • šŸš€Prerequisites
    • šŸ“„Ethereum Storage and Memory
    • šŸ“²Ethereum Calls and Delegate Calls
    • šŸ’ŖUpgradability Patterns in Ethereum: Enhancing Smart Contracts Over Time
    • šŸ”Proxy Upgrade Pattern in Ethereum
    • šŸŒ€Exploring the Landscape of Ethereum Proxies
      • šŸŖžTransparent Proxies
      • ā¬†ļøUUPS Proxies
      • šŸ’”Beacon Proxies
      • šŸ’ŽDiamond Proxies
  • šŸ”žTutorial 19: 18 Decimal Assumption
    • šŸš€Prerequisites
    • šŸ“ŒUnderstanding ERC20 Decimals
    • šŸ’€Examples Of Vulnerabilities To Do With Assuming 18 Decimals
    • šŸ¤Conclusion
  • āž—Tutorial 20: Arithmetic
    • šŸš€Prerequisites
    • šŸ•³ļøArithmetic pitfall 1: Division by 0
    • šŸ”ŖArithmetic pitfall 2: Precision Loss Due To Rounding
    • 🄸Arithmetic pitfall 3: Erroneous Calculations
    • šŸ¤Conclusion
  • šŸ”Tutorial 21: Unbounded Loops
    • šŸš€Prerequisites
    • ⛽Gas Limit Vulnerability
    • šŸ“ØTransaction Failures Within Loops
    • šŸ¤Conclusion
  • šŸ“”Tutorial 22: `isContract`
    • šŸš€Prerequisites
    • šŸ’€Understanding the 'isContract()` vulnerability
    • šŸ¤Conclusion
  • šŸ’µTutorial 23: Staking
    • šŸš€Prerequisites
    • šŸ’€First Depositor Inflation Attack in Staking Contracts
    • šŸŒŖļøFront-Running Rebase Attack (Stepwise Jump in Rewards)
    • ā™ØļøRugability of a Poorly Implemented recoverERC20 Function in Staking Contracts
    • 😠General Considerations for ERC777 Reentrancy Vulnerabilities
    • šŸ„Vulnerability: _lpToken and Reward Token Confusion in Staking Contracts
    • 🌊Slippage Checks
    • 🌽The Harvest Functionality in Vaults: Issues and Best Practices
  • ā›“ļøTutorial 24: Chain Re-org Vulnerability
    • šŸš€Prerequisites
    • ā™»ļøChain Reorganization (Re-org) Vulnerability
    • šŸ§‘ā€āš–ļøChain Re-org Vulnerability in Governance Voting Mechanisms
  • šŸŒ‰Tutorial 25: Cross Chain Bridges Vulnerabilities
    • šŸš€Prerequisites
    • ā™»ļøERC777 Bridge Vulnerability: Reentrancy Attack in Token Accounting
      • šŸ›‘Vulnerability: Withdrawals Can Be Locked Forever If Recipient Is a Contract
    • šŸ‘›The Dangers of Not Using SafeERC20 for Token Transfers
    • Uninitialized Variable Vulnerability in Upgradeable Smart Contracts
    • Unsafe External Calls and Their Vulnerabilities
    • Signature Replay Attacks in Cross-Chain Protocols
  • 🚰Tutorial 26: Integer Underflow and Overflow Vulnerabilities in Solidity (Before 0.8.0)
    • šŸš€Prerequisites
    • šŸ’€Understanding Integer Underflow and Overflow Vulnerabilities
    • šŸ¤Conclusion
  • šŸ„Tutorial 27: OpenZeppelin Vulnerabilities
    • šŸš€Prerequisites
    • šŸ›£ļøA Guide on Vulnerability Awareness and Management
      • šŸ¤Conclusion
  • šŸ–ŠļøTutorial 28: Signature Vulnerabilities / Replays
    • šŸš€Prerequisites
    • šŸ”Reusing EIP-712 Signatures in Private Sales
    • šŸ”Replay Attacks on Failed Transactions
    • šŸ“ƒImproper Token Validation in Permit Signature
  • šŸ¤Tutorial 29: Solmate Vulnerabilities
    • šŸ”Lack of Code Size Check in Token Transfer Functions in Solmate
  • 🧱Tutorial 30: Inconsistent block lengths across chains
    • šŸ•›Incorrect Assumptions about Block Number in Multi-Chain Deployments
  • šŸ’‰Tutorial 31: NFT JSON and XSS injection
    • šŸ“œVulnerability: JSON Injection in tokenURI Functions
    • šŸ“Cross-Site Scripting (XSS) Vulnerability via SVG Construction in Smart Contracts
  • šŸƒTutorial 32: Merkle Leafs
    • šŸ–„ļøMisuse of Merkle Leaf Nodes
  • 0ļøTutorial 33: Layer 0
    • šŸ“©Lack of Force Resume in LayerZero Integrations
    • ⛽LayerZero-Specific Vulnerabilities in Airdropped Gas and Failure Handling
    • šŸ”“Understanding the Vulnerability of Blocking LayerZero Channels
    • šŸ–ŠļøCopy of Understanding the Vulnerability of Blocking LayerZero Channels
  • ā™»ļøTutorial 34: Forgetting to Update the Global State in Smart Contracts
  • ā€¼ļøTutorial 35: Wrong Function Signature
  • šŸ›‘Tutorial 36: Handling Edge Cases of Banned Addresses in DeFi
  • Tutorial 37: initializer and onlyInitializing
  • āž—Tutorial 38: Eigen Layer
    • šŸ“©Denial of Service in NodeDelegator Due to EigenLayer's maxPerDeposit Check
    • šŸ“ˆIncorrect Share Issuance Due to Strategy Updates in EigenLayer Integrations
    • šŸ”nonReentrant Vulnerability in EigenLayer Withdrawals
  • ⚫Tutorial 39: Wormhole
    • šŸ“©Proposal Execution Failure Due to Guardian Set Change
  • šŸ’¼Tutorial 40: Uniswap V3
    • šŸ“©Understanding and Mitigating Partial Swaps in Uniswap V3
    • 🌊Underflow Vulnerability in Uniswap V3 Position Fee Growth Calculations
    • āž—Handling Decimal Discrepancies in Uniswap V3 Price Calculations
  • šŸ”¢Tutorial 41: Multiple Token Addresses in Proxied Tokens
    • šŸ”“Understanding Vulnerabilities Arising from Tokens with Multiple Entry Points
  • šŸ¤–Tutorial 42: abiDecoder v2
    • 🄄Vulnerabilities from Manipulated Token Interactions Using ABI Decoding
  • ā“Tutorial 43: On-Chain Randomness
    • Vulnerabilities in On-Chain Randomness and How It Can Be Exploited
  • šŸ˜–Tutorial 44: Weird ERC20 Tokens
    • Weird Token List
  • šŸ”ØTutorial 45: Hardcoded stable coin values
  • ā¤ļøTutorial 46: The Risks of Chainlink Heartbeat Discrepancies in Smart Contracts
  • šŸ‘£Tutorial 47: The Risk of Forgetting a Withdrawal Mechanism in Smart Contracts
  • šŸ’»Tutorial 48: Governance and Voting
    • Flash Loan Voting Exploit
    • Exploiting Self-Delegation
    • šŸ’°Missing payable Keyword in Governance Execute Function
    • šŸ‘ŠVoting Multiple Times by Shifting Delegation
    • šŸ‘Missing Duplicate Veto Check
  • šŸ“•Tutorial 49: Not Conforming To EIP standards
    • šŸ’ŽUnderstanding EIP-2981: NFT Royalty Standard
    • šŸ‘Improper Implementation of EIP-2612 Permit Standard
    • šŸ”Vulnerabilities of Missing EIP-155 Replay Attack Protection
    • āž”ļøVulnerabilities Due to Missing EIP-1967 in Proxy Contracts
    • šŸ”“Vulnerability of Design Preventing EIP-165 Extensibility
    • šŸŽŸļøThe Dangers of Not Properly Implementing ERC-4626 in Yield Vaults
    • šŸ”EIP-712 Implementation and Replay Attacks
  • ā³Tutorial 50: Vesting
    • šŸš”Vulnerability of Allowing Unauthorized Withdrawals in Vesting Contracts
    • šŸ‘ŠVulnerability of Unbounded Timelock Loops in Vesting Contracts
    • ā¬†ļøVulnerability of Incorrect Linear Vesting Calculations
    • ⛳Missing hasStarted Modifier
    • šŸ”“Vulnerability in Bond Depositor's Vesting Period Reset
  • ⛽Tutorial 51: Ethereum's 63/64 Gas Rule
    • šŸ›¢ļøAbusing Ethereum's 63/64 Gas Rule to Manipulate Contract Behavior
  • šŸ“©Tutorial 52: NPM Dependency Confusion and Unclaimed Packages
    • šŸ’ŽExploiting Unclaimed NPM Packages and Scopes
  • šŸŽˆTutorial 53: Airdrops
    • šŸ›„Claiming on Behalf of Other Users
    • 🧲Repeated Airdrop Claims Vulnerability
    • šŸƒAirdrop Vulnerability – Merkle Leaves and Parent Node Hash Collisions
  • šŸŽÆTutorial 54: Precision
    • šŸŽVulnerabilities Due to Insufficient Precision in Reward Calculations
    • Min-Shares: Fixed Minimum Share Values for Tokens with Low Decimal Precision
    • Vulnerability Due to Incorrect Rounding When the Numerator is Not a Multiple of the Denominator
    • Vulnerability from Small Deposits Being Rounded Down to Zero Shares in Smart Contracts
    • Precision Loss During Withdrawals from Vaults Can Block Token Transfers Due to Value < Amount
    • 18 Decimal Assumption Scaling: Loss of Precision in Asset Conversion Due to Incorrect Scaling
  • Tutorial 55: AssetIn == AssetOut, FromToken == ToToken
    • šŸ–¼ļøVulnerability: Missing fromToken != toToken Check
  • 🚿Tutorial 56: Vulnerabilities Related to LP Tokens Being the Same as Reward Tokens
    • šŸ–¼ļøVulnerabilities Caused by LP Tokens Being the Same as Reward Tokens
  • Tutorial 57: Unsanitized SWAP Paths and Arbitrary Contract Call Vulnerabilities
    • šŸ“²Arbitrary Contract Calls from Unsanitized Paths
  • Tutorial 58: The Risk of Infinite Approvals and Arbitrary Contract Calls
    • 🪣Exploiting Infinite Approvals and Arbitrary Contract Calls
  • Tutorial 59: Low-Level Calls in Solidity Returning True for Non-Existent Contracts
    • Low-Level Calls Returning True for Non-Existent Contracts
  • 0ļøāƒ£Tutorial 60: The Impact of PUSH0 and the Shanghai Hardfork on Cross-Chain Deployments > 0.8.20
    • PUSH0 and Cross-Chain Compatibility Challenges
  • šŸTutorial 61: Vyper Vulnerable Versions
    • Vyper and the EVM
  • āŒØļøTutorial 62: Typos in Smart Contracts — The Silent Threat Leading to Interface Mismatch
    • Vyper and the EVM
  • ā˜ļøTutorial 63: Balance Check Using ==
    • The Vulnerability: == Balance Check
  • šŸ’Tutorial 64: Equal Royalties for Unequal NFTs
    • Understanding the Problem: Equal Royalties for Unequal NFTs
  • šŸ–¼ļøTutorial 65: ERC721 and NFTs
    • The Risk of Using transferFrom Instead of safeTransferFrom in ERC721 Projects
    • ā„ļøWhy _safeMint Should Be Used Instead of _mint in ERC721 Projects
    • The Importance of Validating Token Types in Smart Contracts
    • šŸ“¬Implementing ERC721TokenReceiver to Handle ERC721 Safe Transfers
    • NFT Implementation Deviating from ERC721 Standard in Transfer Functions
    • NFT Approval Persistence after Transfer
    • šŸŽ®Gameable NFT Launches through Pseudo-Randomness
    • 2ļøāƒ£Protecting Buyers from Losing Funds Due to Claimed NFT Rewards on Secondary Markets
    • ā™»ļøPreventing Reentrancy When Using SafeERC721
    • šŸ–ŠļøPreventing Re-use of EIP-712 Signatures in NFT Private Sales
  • 2ļøāƒ£Tutorial 66: Vulnerability Arising from NFTs Supporting Both ERC721 and ERC1155 Standards
  • šŸ“·Tutorial 67: ERC1155 Vulnerabilities
    • ā™»ļøPreventing Reentrancy in OpenZeppelin's SafeERC1155
    • šŸ›«Vulnerabilities in OpenZeppelin's ERC1155Supply Contract
    • Understanding Incorrect Token Owner Enumeration in ERC1155Enumerable
    • Avoiding Breaking ERC1155 Composability with Improper safeTransferFrom Implementation
    • šŸ’Ensuring Compatibility with EIP-2981 in ERC1155 Contracts
  • 🪟Informational Vulnerabilities
  • ⛽Gas Efficiency
  • šŸ’»Automation Tools
  • šŸ”œOut Of Gas (Coming Soon)
  • šŸ”œDEX Aggregators (Coming Soon)
  • šŸ”œBribes (Coming Soon)
  • šŸ”œUnderstanding Compiled Bytecode (coming soon)
  • šŸ”œDeployment Mistakes (coming soon)
  • šŸ”œOptimistic Roll-ups (coming soon)
  • šŸ”œTypos (coming soon)
  • šŸ”œTry-Catch (coming soon)
  • šŸ”œNFT Market-place (coming soon)
  • šŸ”œUpgrade-able Contracts (coming soon)
Powered by GitBook
On this page
  1. Tutorial 33: Layer 0

Copy of Understanding the Vulnerability of Blocking LayerZero Channels

Overview of the Vulnerability

In LayerZero-based cross-chain communication systems, gas miscalculation is a critical vulnerability that can lead to either wasted gas or, more severely, failed cross-chain transactions. This type of vulnerability typically arises when gas costs for cross-chain messages are incorrectly calculated due to discrepancies between the gas configurations of the source chain and the destination chain. In LayerZero, the delivery of messages across chains is highly dependent on accurate gas estimation.

A mismatch between the gas configurations can lead to two outcomes:

  1. Overpaying for Gas: If too much gas is allocated, the excess gas is wasted, though it may be refunded to the caller.

  2. Underpricing the Gas Cost: If too little gas is allocated, the cross-chain transaction may fail, leading to stuck assets or messages. This is particularly dangerous for assets such as NFTs, where failure in message delivery can result in assets being irretrievably stuck between chains.


Why Gas Miscalculation Happens

  1. Source vs. Destination Chain Gas Configurations: LayerZero’s cross-chain messaging system requires gas to be calculated for both the source and destination chains. The issue arises when the source chain's gas configuration is used to calculate the gas required for the destination chain’s message processing. Since gas costs vary between different chains, using the source chain’s gas configuration can result in significant discrepancies.

  2. DstConfig Misconfiguration: In LayerZero, destination chain gas configurations (DstConfig) are stored in a mapping keyed by chain ID. This allows the protocol to accurately calculate gas for each chain based on its specific requirements. However, when the wrong gas values (e.g., source chain’s baseGas and gasPerByte) are used for a destination chain transaction, the gas estimation will be inaccurate.

  3. No Fallback Handling: The lack of adequate fallback handling in case of failed transactions exacerbates this vulnerability. When a cross-chain transaction fails due to underpricing gas, the system does not properly handle the error, leaving assets (such as NFTs) stuck in limbo, with no way to recover or retry the transaction.


Impact of the Vulnerability

The impact of gas miscalculation in LayerZero cross-chain operations varies in severity depending on the nature of the transaction and the discrepancy in gas pricing:

  1. Wasted Gas: If too much gas is allocated for the transaction, the excess gas is effectively wasted. While the caller may receive a refund for the unused gas, it still results in inefficient use of resources and unnecessary costs for users.

  2. Stuck Assets and Failed Transactions: A more serious consequence of underpricing gas is that cross-chain messages may fail. When this happens, critical assets, such as NFTs, can become stuck between chains, potentially lost forever. Since the LayerZero protocol does not emit an event to signal the failure of the lzReceive() function, users and operators may not even be aware that the asset is stuck or that the transaction has failed.

    • Example: If an NFT is being transferred from Chain A to Chain B, and the gas required for Chain B’s message processing is underpriced, the transaction will revert, leaving the NFT stuck on Chain A. Without an event being emitted to notify operators of the failure, the NFT may remain irrecoverable.


Real-World Example: Gas Miscalculation in the LayerZeroModule

In the LayerZeroModule.sol contract of the Holograph protocol, cross-chain messaging primitives are handled through LayerZero. To estimate gas pricing, the contract uses the DstConfig struct exposed in LayerZero’s RelayerV2. However, the issue arises when the source chain’s baseGas and gasPerByte configuration parameters are used to calculate the gas cost for the destination chain’s message.

Because different chains have different gas requirements, this miscalculation can lead to two scenarios:

  • Wasting Excess Gas: If the gas requirements of the destination chain are lower than the gas calculated based on the source chain’s configuration, excess gas will be refunded to the caller, but resources are still wasted.

  • Underpricing Gas: If the gas requirements of the destination chain are higher, the transaction will revert due to insufficient gas, and assets such as NFTs may become stuck between chains without any recovery mechanism.


Mitigation Strategies

1. Use Destination Chain Gas Configurations

The primary way to prevent gas miscalculations is to ensure that the gas calculations are based on the destination chain’s gas costs, not the source chain’s. LayerZero’s DstConfig mapping provides the appropriate gas settings for each destination chain based on its chain ID. Developers should always refer to the destination chain’s gas parameters (baseGas and gasPerByte) to accurately estimate the gas required for cross-chain message processing.

  • Best Practice: Ensure that the LayerZero module retrieves and uses gas configurations from the destination chain’s DstConfig struct when estimating gas. This will prevent the system from overpricing or underpricing gas for cross-chain messages.

2. Re-engineer the lzReceive() Function

The lzReceive() function is a critical part of LayerZero’s message handling, where cross-chain messages are received and processed. However, if the transaction fails due to insufficient gas, there is no fallback mechanism to handle this failure. Re-engineering lzReceive() to be more fault-tolerant can help prevent assets from getting stuck in limbo.

  • Best Practice: Reserve a portion of gas to ensure that the lzReceive() function can emit a failure event even when the primary transaction fails. This will allow operators to detect and address failed cross-chain transactions.

3. Introduce a Retry Mechanism

To mitigate the risk of permanently stuck assets, protocols should implement a retry mechanism for failed cross-chain transactions. If a message fails due to underpriced gas, the system should allow the transaction to be retried with the correct gas settings, either automatically or manually by an operator.

  • Best Practice: Implement a fallback system that detects failed lzReceive() calls and retries the message with updated gas pricing from the destination chain.

4. Notify Users and Emit Failure Events

When a transaction fails due to gas mispricing, it is important to notify the relevant parties (such as users or operators) to ensure that the issue is addressed in a timely manner. Protocols should emit failure events whenever a cross-chain transaction fails, providing transparency and enabling operators to take corrective action.

  • Best Practice: Emit an event when a transaction reverts due to gas miscalculation, providing details on the failure and allowing operators to debug and retry the transaction if necessary.


Conclusion

Gas miscalculation is a serious vulnerability in LayerZero-based cross-chain communication systems that can lead to wasted gas or, more critically, stuck assets such as NFTs. This issue occurs when the source chain’s gas configuration is incorrectly used for the destination chain, resulting in underpriced gas costs and failed transactions.

By implementing proper mitigation strategies—such as using the destination chain’s gas configurations, improving the fault tolerance of the lzReceive() function, and adding a retry mechanism—developers can ensure that their cross-chain messaging systems remain resilient and secure. This will protect users from losing assets and help maintain the reliability and efficiency of cross-chain operations.

PreviousUnderstanding the Vulnerability of Blocking LayerZero ChannelsNextTutorial 34: Forgetting to Update the Global State in Smart Contracts

Last updated 7 months ago

0ļø
šŸ–Šļø