get_D() and get_y() in Curve StableSwap

get_D() and get_y() in Curve StableSwap This article shows algebraically step-by-step how the code for get_D() and get_y() are derived from the StableSwap invariant. Given the StableSwap Invariant: $$ An^n\sum x_i +D=An^nD+\frac{D^{n+1}}{n^n\prod x_i} $$ There are two frequent math operations we wish to conduct with it: Compute $D$ given fixed values for $A$, and the […]

Fixed Point Arithmetic in Solidity (Using Solady, Solmate, and ABDK as Examples)

Fixed Point Arithmetic in Solidity (Using Solady, Solmate, and ABDK as Examples) A fixed-point number is an integer that stores only the numerator of a fraction — while the denominator is implied. This type of arithmetic is not necessary in most programming languages because they have floating point numbers. It is necessary in Solidity because […]

Uniswap V2: Calculating the Settlement Price of an AMM Swap

Uniswap V2: Calculating the Settlement Price of an AMM Swap This article explains how to determine the price settlement of a trading pair in an Automated Market Maker (AMM). It answers the question of “How many token X can be swapped for token Y from the AMM?”. The swap() function on Uniswap V2 requires you […]

How Chainlink Price Feeds Work

How Chainlink Price Feeds Work Chainlink price oracles are smart contracts with public view functions that return the price of a particular asset denominated in USD. Off-chain nodes collect the prices from various sources like exchanges and write the price data to the smart contract. Here is the smart contract for getting the price of […]

How Compound V3 Allocates COMP Rewards

How Compound V3 Allocates COMP Rewards Compound issues rewards in COMP tokens to lenders and borrowers in proportion to their share of the a market’s lending and borrowing. The algorithm is extremely similar to the MasterChef Staking Algorithm, so the reader should familiarize themselves with that first. High level overview of Compound V3 rewards Similar […]

Bulkers in Compound V3

Bulkers in Compound V3 The bulker contracts in Compound V3 are multicall-like contracts for batching several transactions. For example, if we wanted to supply Ether, LINK, and wBTC as collateral and borrow USDC against it in one transaction, we can do that. We can also reduce the collateral holdings and withdraw a loan in one […]

Understanding Collateral, Liquidations, and Reserves in Compound V3

Understanding Collateral, Liquidations, and Reserves in Compound V3 In this chapter we will examine the following topics about Compound V3: collateral valuation absorbing insufficiently collateralized loans (liquidations) selling absorbed collateral what reserves are and how reserves affect liquidations. These are a lot of topics to go over in one article, but they are all heavily […]

cUSDC V3 (Compound V3) as a non-standard Rebasing Token, CometExt.sol

cUSDC V3 (Compound V3) as a non-standard Rebasing Token, CometExt.sol The Compound V3 contract behaves like a rebasing ERC 20 token. A rebasing token is a token which has an algorithmically adjusted supply rather than a fixed one. The “token” here represents the present value of positive USDC balances. That is, lenders can transfer the […]

DeFi Interest Rate Indexes: Principal value and Present Value in Compound V3

DeFi Interest Rate Indexes: Principal value and Present Value in Compound V3 The intuitive way to track lender deposits is to record the amount of USDC they deposited and the time they deposited. Compound V3 does not do this. Instead, similar to SushiSwap Masterchef Staking Algorithm, Compound V3 tracks the hypothetical gain of one dollar […]

Compound V3 Interest Per Second

Compound V3 Interest Per Second The Compound V3 protocol measures interest on the scale of seconds. The Compound V3 frontend scales the number up to years for human friendliness. When we check the interest rate parameters for Compound V3 on Etherscan, we see the following parameters for borrowers. In the following section, we will corroborate these parameters […]

The Architecture of the Compound V3 Smart Contract

The Architecture of the Compound V3 Smart Contract Introduction and prerequisites Compound is one of the most significant lending protocols in DeFi, having inspired the design of nearly every lending protocol on several blockchains. This article explains the smart contract architecture of V3. Since Compound is a lending protocol, we assume the reader is familiar […]

DeFi Lending: Liquidations and Collateral

DeFi Lending: Liquidations and Collateral In TradFi, when someone defaults on a loan, the creditor has the right to seize assets or garnish wages. In DeFi, when someone defaults on a loan it isn’t possible to take assets from their wallet. To enforce repayment, users must deposit a larger notional value of cryptocurrency than they […]

The interest rate model of AAVE V3 and Compound V2

The interest rate model of AAVE V3 and Compound V2 Interest rates in TradFi (traditional finance) are largely determined by central banks and influenced by market factors. In contrast, DeFi interest rates are algorithmically determined by the demand for loans and the supply of funds from lenders. Concepts in this article will be explained through […]

The staking algorithm of Sushiswap MasterChef and Synthetix

The staking algorithm of Sushiswap MasterChef and Synthetix The MasterChef and Synthetix staking algorithms distribute a fixed reward pool among stakers according to their time-weighted contributions to a pool. To save on gas, the algorithms use a cumulative counter of token-level reward and defer the reward distribution. Imagine we have a fixed pool of 100,000 […]

Uniswap V2 Architecture: An Introduction to Automated Market Makers

Uniswap V2 Architecture: An Introduction to Automated Market Makers Uniswap is a DeFi app that enables traders to swap one token for another in a trustless manner. It was one of the early automated market makers for trading (though not the first). Automated market makers are an alternative to an order book, which the reader […]

How Uniswap V2 computes the mintFee

How Uniswap V2 computes the mintFee Uniswap V2 was designed to collect 1/6th of the swap fees to the protocol. Since a swap fee is 0.3%, 1/6th of that is 0.05%, so 0.05% of every trade would go to the protocol. Although this feature was never actually activated, we discuss this feature anyway since some […]

Uniswap v2 router code walkthrough

Uniswap v2 router code walkthrough The Router contracts provide a user-facing smart contract for safely minting and burning LP tokens (adding and removing liquidity) safely swapping pair tokens They add the ability to swap Ether by integrating with the wrapped Ether (WETH) ERC20 contract. They add the slippage related safety checks omitted from the core […]

Flash Loans and how to hack them: a walk through of ERC 3156

Flash Loans and how to hack them: a walk through of ERC 3156 Flash loans are loans between smart contracts that must be repaid in the same transaction. This article describes the ERC 3156 flash loan specification as well as the ways flash lenders and borrowers can be hacked. Suggested security exercises are provided at […]

UniswapV2Library Code Walkthrough

UniswapV2Library Code Walkthrough UniswapV2Library The Uniswap V2 Library simplifies some interactions with pair contracts and is used heavily by the Router contracts. It contains eight functions that are not state-changing,. They are also handy for integrating Uniswap V2 from a smart contract. getAmountOut() and getAmountIn() If we want to predict the amount of token y […]

How the TWAP Oracle in Uniswap v2 Works

How the TWAP Oracle in Uniswap v2 Works What exactly is “price” in Uniswap? Suppose we have 1 Ether and 2,000 USDC in a pool. This implies that the price of Ether is 2,000 USDC. Specifically, the price of Ether is 2,000 USDC / 1 Ether (ignoring decimals). More generally, the price of an asset, […]

Checklist for building a Uniswap V2 clone

Checklist for building a Uniswap V2 clone It’s very educational to rebuild Uniswap v2 from scratch using modern Solidity (or Huff if you really want to do it in hard mode). Here are some pointers and suggestions for doing so. Use an updated version of solidity. Be aware that this will lead to syntactic changes. […]

Uniswap V2 Mint and Burn Functions Explained

Uniswap V2 Mint and Burn Functions Explained The lifecycle of Uniswap V2 is someone mints LP tokens (supplies liquidity, i.e. tokens to the pool) for the first time, then a second depositor mints liquidity, swaps happen, then eventually the liquidity providers burn their LP tokens to redeem pool tokens. It turns out to be easier […]

Breaking Down the Uniswap V2 Swap Function

Breaking Down the Uniswap V2 Swap Function Uniswap V2’s swap function is cleverly designed, but many devs find its logic counterintuitive the first time they encounter it. This article explains how it works in depth. Here is the code reproduced below: Admittedly, this is a wall of code, but let’s break it down. On line […]

How Tornado Cash Works (Line by Line for Devs)

How Tornado Cash Works (Line by Line for Devs) Introduction to Tornado Cash Tornado cash is a cryptocurrency smart contract mixer that enables users to deposit crypto with one address and withdraw with another wallet without creating a traceable link between those two addresses. Tornado cash is probably the most iconic zero knowledge smart contract […]