I was writing some articles and wanted to refer to a nice list of common DeFi component types. Unfortunately, I couldn’t find a resource that matched what I was looking for, so I started work on this “Ultimate list of Common DeFi Component Types” for security researchers.
Work In Progress
- Options, perpetuals, bonds
- Synthetics / Real world assets
- Bridges and Cross chain
- Prediction markets
Tokens: The Fundamental Units of DeFi
Tokens are the foundational elements of decentralized finance. Tokens can represent various types of value and rights. From currencies to digital representations of physical assets, tokens serve as the primary medium for transactions within DeFi protocols.They’ve got a simple, and general interface that allows for much customisation and has lead to their widespread application in various domains.
Two Main Categories of Tokens
Tokens can be broadly classified into two categories based on their fungibility:
- Fungible Tokens: Fungibility refers to the property of a good or a commodity whose individual units are essentially interchangeable. In the context of tokens, fungible tokens are identical to each other, each holding the same value. An example of fungible tokens is the ERC20 standard on the Ethereum blockchain.
- Non-Fungible Tokens (NFTs): Unlike fungible tokens, each NFT is unique and can’t be replaced with another. Each token has a distinct value and specific information that differentiates it from other tokens. The ERC721 standard on the Ethereum network is one of the most widely used for these types of tokens.
This is a useful high level classification. However, keep in mind that there are variations of these categories, like semi-fungible tokens and multi-token contracts.
Tokens are integral to DeFi, and their implementation and usage should involve certain security considerations:
- Standardization Issues: The lack of consistent standards across different token types can lead to unexpected behavior. For instance, the safeTransfer function operates differently between ERC20 and ERC721 tokens. Understanding these variations is crucial when evaluating interactions with different token types.
📚 Check out this awesome read by samczsun on the issues of safeTransfer https://samczsun.com/the-dangers-of-surprising-code/.
- More Standardization Flaws: The ERC20 standard is very minimalistic and allows for a lot of creative liberties in implementations. Common design patterns and behavious might seem obvious, but token implementations sometimes deviate from common expectations since those assumptions not standardised. For example, a protocol may assume that a token they depend on is non-deflationary when it is not.
- Token Extensions: Some token standards introduce useful, but dangerous behaviour. Like function hooks in ERC777. Such tokens are always worth looking into, as they often introduce complex behaviour that might lead to vulnerabilities.
- Token vs. Native Currency Behavior: Tokens and native currencies seem similar, but may not behave identically in all contexts. An example is a payable multicall function, each call of the multicall will have the same msg.value. Another example are transfers, native transfers on Ethereum will revert if they fail, while token transfers will simply return false.
Libraries like Open Zeppelins’ SafeERC20 help developers get back to a similar behaviour.
Example Hacks involving Token Internals
Here are some example hacks where the token internals were critical facets:
- Batching and Native Token Behaviours in Sushi
- Balancer Pools With Deflationary Tokens Drained
- Lendf.me Re-entrancy with ERC777 Tokens
DeFi lending platforms are one of the most essential components of the DeFi ecosystem. They allow individuals to lend or borrow assets directly through smart contracts, collateralising their loan with other cryptocurrencies. In return for lending their assets, lenders earn interest which is typically dynamic, adjusting in real-time based on supply and demand.
Types of Lending Platforms: Over & Under Collateralization
DeFi lending platforms come in all shapes and sizes, but we can often categorise them as either overcollateralized or undercollateralized.Overcollateralized platforms are like that overly cautious friend who always carries an umbrella, even when there’s not a cloud in the sky. You need to provide more assets as collateral than what you’re borrowing. Did you provide a shit token that crashes as collateral? Then your position is likely to be liquidated!
💡 Protocols will allow people to liquidate your position when your collateral is losing value and the collateralisation ratio (the ratio between loan value and colalteral value) is in danger of dipping too low.You can think of liquidations as a protocol selling your position (the amount you owe + collateral) at a discount.
Undercollateralized platforms, on the other hand, are more risky for the lender. They allow you to borrow with less, or sometimes even without, collateral. They’re very hard to pull off in DeFi and often rely on more complex mechanisms to prevent defaults.
Uses of Lending Platforms: Leverage, Stablecoins and More!
DeFi lending platforms are at the core of DeFi and enable a range of interesting uses.Take leveraging. You can borrow against your assets, buy more of the same asset, and potentially rake in more gains if the price goes up. But remember, with greater rewards come greater risks. If the price plummets, you could end up with even more losses!Another cool use case is stablecoins. Platforms like MakerDAO leverage a lending design to allow you to generate DAI, a stablecoin pegged to the US dollar.
Common Security Flaws and Flashloans
No system is perfect and DeFi lending platforms are no exception. A specific point of interest is the dependency of lending platforms on oracles (see also the section on oracles), which can lead to interesting bugs.
- One unique feature is flash loans. These are uncollateralized loans that are borrowed and repaid within a single transaction. If the loan isn’t repaid, the whole transaction reverts as if it never happened.
- Over-collateralised platforms want to liquidate loans before they go underwater, often with an incentive for someone to liquidate the loan. Liquidations are difficult, and bad debt liquidations even more so!
- Correctly valuing collateral is essential! Lending platforms often use an oracle for determining the health of a loan. Check out our section on oracles for things to keep in mind!
🚀 Researchers are looking into the viability of new “flash loan” extensions that pass the boundary of single transactions.Such an extension might be possible private mempools!
Examples of Lending Platforms
Want to look at some examples? Here are some popular DeFi lending platforms you might want to check out:
- DAI (by MakerDAO)
Example Bugs / Hacks
- Euler Finance Hack: By donating funds to the protocol a hacker was able to liquidate their own bad debt at a profit!
- Rari Capital Hack: Re-entrancy is an issue for all smart contracts, including lending protocols.
- Cream Finance Hack: An attacker tricked the protocol into believing it’s collateral doubled in value.
- Warp Finance : The protocol incorrectly implemented the valuation of LP, allowing the attacker to trick the system into believing it’s tokens were worth more than they actually were.
Stablecoins are digital currencies designed to keep their value or “stable”, often pegged against a certain asset or a pool of assets. The most common peg being the US dollar. Stables bring a sense of predictability to the otherwise turbulent world of crypto, making them a crucial cornerstone to many DeFi constructions.
Common Designs of Stablecoins
Stablecoins come in a variety of designs, each with their own unique approach to maintaining stability:
todo: add reference to collateralised debt position (CDP) being what lending based stable coins use.
- Lending-based Stablecoins: Take DAI, for example. It’s like a self-loan system. You put up more assets (like ETH) as collateral than the DAI you mint.
- One-to-one Backed Stablecoins: USDC is a great example of a fiat-backed stablecoin. For every USDC, there’s an actual US dollar stored in a bank account somewhere. It’s like your digital dollar bill.
- Algorithmic Stablecoins: Say hello to RAI. It’s an algorithmic stablecoin that uses an algorithmic approach to achieving a stable price. Its price is balanced by an algorithm that adjusts based on supply and demand. Think of it as a self-regulating organism, continuously adapting to keep itself stable.
Looking at Stablecoins while wearing a white-hat.
As a white hat, what’s important to keep in mind when looking at a stablecoin or protocols using stable coins?
- Flash loans: Some stable coins, like DAI, enable flash loans which can be very helpful to attackers that need some liquidity to be able to execute an exploit.
- Pegging risks: A stable coin’s peg isn’t set in stone. If you’re hardcoding assumptions about a peg in a smart contract, you could be in for a hard time.
When the Silicon Valley Bank closed its doors, it stirred up some waves in the value of USDC, impacting much of DeFi.
- Maintaining the peg / stability: As the most complex and quintessential aspect of stablecoin designs, this deserves extensive evaluation.
Examples of Stablecoins
Here are some stable coin examples:
Bugs involving stablecoins
- Fei protocol peg incentives: Fei protocol incentivised trading towards the peg, these incentives were facilitated with penalties for people trading away from the peg. Unfortunately, it was possible to avoid the penalties, and iteratively get free incentives.
- UST, Luna and Terra: UST was a stable coin that lost it’s peg due to flaws in it’s incentive design. It’s worth understanding what happened here even though it’s unclear whether a white hat would’ve gotten a bounty for pointing out the issues.
DEX (Decentralized Exchanges)
A decentralised exchange allows users to trade digital assets directly from their wallets without the need for a central exchange or custodian. Instead of matching buyers and sellers in an order book, most DEXs use automated market makers (AMMs) that allow trades to be made against a liquidity pool. These pools are filled by liquidity providers who earn trading fees in return.
Common Designs of DEXs
There are a few ways to approach designing a DEX here are two of the most common designs:
- Invariant AMM (Automated Market Makers): These DEXs use liquidity pools instead of order books. Traders place an order against the pool, and AMMs will execute the order. The price at which the order is executed will depend on the invariant function that the AMM is using.
- Read more here: https://medium.com/bollinger-investment-group/constant-function-market-makers-defis-zero-to-one-innovation-968f77022159
- Order Book Model: This is the classic exchange model, decentralized. Traders place buy or sell orders, and the DEX matches these orders, acting as a matchmaking service for traders.
Looking at DEXs from a Security Perspective
As a bounty hunter, developer, or auditor, what should you watch out for in a DEX? Here are some critical points:
- Flash Loans: Some DEXs, like Uniswap, allow for flash loans. This can be a feature that enables hackers to build a (proof of concept) exploit.
- Slippage: Slippage is when the execution price of a trade is different from when the order was placed. It’s important to review that slippage is always checked & bounded. Lack of slippage control will allow an MEV bot to easily steal funds in transit.
- Changing Constants: Many AMMs feature an invariant-based design, with the invariant computed using a configurable constant. On the surface, this might appear safe, but in reality, it may expose vulnerabilities.
- Alternative AMM Designs: If you’re evaluating an AMM that implements a novel AMM design, or invariant, then this is a critical point of interest for you as a security researcher.
- AMMs as an Oracle: There is an interesting application of AMMs in the design and usage of decentralised oracles. We’ll explore this in the section on oracles.
💡 Invariant AMMs are incredibly common, and it’s worth the time to build a good mental model of how liquidity changes & trades manipulate the curve and position on the curve respectively.
Case Studies: Examples of DEXs
- CoW Swap (hybrid)
Here are some examples of real world instances of bugs in DEXs.
- Curve Constant Update Sandwich: An attacker could have sandwiched a governance update to the stable swap constants, taking funds from the liquidity providers.
- Uniswap Universal Router Re-entrancy: Another reminder that bugs such as re-entrancy remain relevant, it’s important to keep an eye out for them.
- MonoX Protocol Hack - A single lp token AMM: This protocol implemented a novel AMM design, however, a critical check ended up missing leading to an attacker draining the protocol.
Imagine you’re in a dark room and you need to find the light switch. You can’t do it alone, so you use your phone’s flashlight to illuminate the room and find the switch. In this case, your phone acted as an oracle, providing you with crucial information from outside your current environment.In the world of blockchain, oracles serve a similar purpose. They’re third-party services that provide smart contracts with external information. They’re the bridge between the blockchain and the outside world, helping smart contracts interact with data they can’t access on their own.
Oracles aren’t one-size-fits-all, they come in different shapes and sizes. Let’s take a look at a couple of common approaches:
- Decentralised Oracles: This approach is all about trust in numbers. It employs aggregation of data from multiple sources to provide a reliable feed. It can also use dispute resolution mechanisms to keep everyone honest. It’s like having a panel of expert witnesses in a court case.
- AMM (Automated Market Makers) Prices: This approach uses historic prices (like Time-Weighted Average Price, TWAP) from AMMs like Uniswap. This can provide a more accurate representation of a token’s price over a specific period, helping to prevent price manipulation.
Looking at Oracles with a Security Mindset
- Manipulability: Getting accurate data on chain is a difficult and imperfect process. Each oracle design has it’s own weaknesses. Each integration with an oracle should warrant an evaluation of the specific strength and weaknesses.
- Up to date Responses: An out of date oracle response is essentially the same as a wrong oracle response, and will have disastrous effects on protocols depending on it. Interesting things happen when protocols assume price feed results are always up to date.
- Sandwichability: You should keep in mind that price oracle updates can be sandwiched like any other transaction. How this impacts a protocol is highly specific, but warrants checking out.
- Read more on sandwiching oracle updates in this article.
Examples of Oracles
Ready to dive into the world of Oracles? Here are a few key players:
- Chainlink: Chainlink is the big kahuna of decentralized oracles. It aggregates data from multiple sources to provide accurate and reliable information to smart contracts.
- Tellor: Tellor is a decentralized oracle that relies on a network of miners who compete to submit data points for rewards. It also features a dispute resolution system to keep things fair and honest.
- Uniswap: While not an oracle itself, Uniswap’s price feeds are often used as a type of oracle. Its TWAP feature provides a robust measure against price manipulation, making it a trusted source for price information.
Oracles are the eyes and ears of the blockchain, providing crucial real-world data to smart contracts. Understanding how they work and the different approaches to oracle design is a must for any DeFi hacker.
💡 Remember, trust, but verify. Always consider the source of your oracle data and how it’s being provided.
🐛 Hacks, incidents and bug bounties which involved oracles.
Let’s have a look at some issues that happened in relation to oracles:
- Bonq Protocol Hack: The protocol made an incorrect assumption about the functioning of the Tellor oracle, which allowed an attacker to trick it into accepting a faulty price.
- Chainlink Circuit Breaker: The Luna price feed hit a circuit breaker, freezing price updates. Not all protocols that depended on that price feed expected that.
💡 It’s interesting to note that most of these concern protocols that depend on the oracles, and not oracles themselves.