<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rodrigo Herrera I on Medium]]></title>
        <description><![CDATA[Stories by Rodrigo Herrera I on Medium]]></description>
        <link>https://medium.com/@rodrigoherrerai?source=rss-25fc5577e294------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GvJ9vadk5orRZOs7z7gMKg@2x.jpeg</url>
            <title>Stories by Rodrigo Herrera I on Medium</title>
            <link>https://medium.com/@rodrigoherrerai?source=rss-25fc5577e294------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 16:23:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rodrigoherrerai/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Compound V2 in Depth]]></title>
            <link>https://medium.com/better-programming/compound-v2-in-depth-6227c0528b5?source=rss-25fc5577e294------2</link>
            <guid isPermaLink="false">https://medium.com/p/6227c0528b5</guid>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[compound-finance]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Rodrigo Herrera I]]></dc:creator>
            <pubDate>Fri, 20 Jan 2023 21:06:21 GMT</pubDate>
            <atom:updated>2024-06-04T21:29:03.290Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Compound is a decentralized protocol which establishes money markets with algorithmically set interest rates based on supply and demand, allowing users to frictionlessly exchange the time value of Ethereum assets*.</em></h4><p>Compound V2 is one of the most important protocols on EVM chains. According to Defillama, <a href="https://defillama.com/forks">it is the second most forked project by TVL</a>.</p><p>In this post, we are going to analyze the most important components of Compound, primarily money markets (cTokens) and its governance model.</p><p><strong>NOTE:</strong> <em>You should have a good understanding of the basic Ethereum and Defi concepts to follow along. Primarily, you should be comfortable reading Solidity and the basics of Defi (erc20 tokens, incentives, etc.)</em></p><p>This post is divided into 2 parts:</p><ul><li>The first part goes through the general protocol architecture.</li><li>The second part goes through hands-on examples that demonstrate everything that was covered.</li></ul><p><strong>NOTE:</strong> You can find the GitHub repo <a href="https://github.com/rodrigoherrerai/Compound-V2-Examples">here</a>. We will go through the source in the second part, but it is advisable to read the code as we understand each topic.</p><h3>Protocol Architecture</h3><h4>Money Markets</h4><p>The first concept to understand is money markets. You can think of a money market as a smart contract that holds 2 assets:</p><ol><li>The underlying asset (Eth, Dai, USDC, etc.).</li><li>The token representation of the underlying asset (cToken).</li></ol><p><strong>NOTE:</strong> <em>There are cases where money markets hold more than 2 assets, but compound V2 doesn’t.</em></p><p>In simple terms, you deposit an asset (think of Eth) into a smart contract and get a representation of it (cEth) in return. This token will increase or decrease in value depending on the rules of the smart contract.</p><p>The main conceptual difference between a money market and a traditional lending/borrowing platform is that the former is on-chain (trustless) while the latter requires you to trust an intermediate (platform).</p><p>One of the main benefits of this is that you can read the code and know that something will be executed with certainty and you also know the exact amount of liquidity that there is.</p><h4>cTokens</h4><p>As previously mentioned, each market is implemented as a smart contract and the token representation in the Compound is known as a cToken.</p><p>The cToken is basically an <a href="https://ethereum.org/en/developers/docs/standards/tokens/erc-20/">ERC20 compatible token</a> with extra functionality.</p><p>You can mint cTokens by depositing the underlying token to the cToken smart contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*-19duaCtgcLXD32u" /></figure><p>*<em>You can find the full API of a </em>cToken<em> contract </em><a href="https://docs.compound.finance/v2/ctokens/"><em>here</em></a><em>.</em></p><p>Some important characteristics of a cToken:</p><ul><li>Each cToken will increase its value on a (almost) per block basis due to the interests earned.</li><li>You can use the cToken as collateral to borrow funds. You can also use it in other markets (it is an ERC20-compatible token).</li></ul><p><strong><em>Exchange Rate:</em></strong> The exchange rate between a cToken and the underlying asset e.g. (dai vs cDai or eth vs cEth) begins at 0.020 and increases at a rate equal to the compounding market interest rate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5BLtRYyQOtpXrCwJ" /><figcaption>exchange rate formula</figcaption></figure><p>Where:</p><ul><li>getCash(): The amount of underlying balance owned by this cToken contract.</li><li>totalBorrows(): The amount of underlying currently loaned out by the market, and the amount upon which interest is accumulated to suppliers of the market.</li><li>totalReserves(): Reserves are an accounting entry in each cToken contract that represents a portion of historical interest set aside as cash which can be withdrawn or transferred through the protocol’s governance.</li><li>totalSupply(): The number of tokens currently in circulation in this cToken market.</li></ul><p><strong>NOTE:</strong> <em>All cTokens have 8 decimals, while the underlying token can vary.</em></p><h4>Interest Rates</h4><p>Interest rates are updated on every block as long as the ratio of borrowed assets to supplied assets has changed. The number of rates depends on the specific implementation of the smart contract.</p><p>There is an external smart contract that calculates the rates, both borrow and supply.</p><p>Let’s take the cEther money market as an example.</p><p>If we want to find out about the borrow rate per block, we would call the borrowRatePerBlock function from the specific cToken contract. The cToken contract (cEther for our example) will call another external contract that will get the rates.</p><pre>function borrowRatePerBlock() override external view returns (uint) {<br>        return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);<br>    }</pre><p>This is the reason why each cToken may have different interest rate implementations. For the cEther contract, the interest rate contract is called “LegacyJumpRateModelV2” you can find it <a href="https://etherscan.io/address/0xF9583618169920c544Ec89795a346F487cB5a227#code">here</a>.</p><h4>Liquidations</h4><p><em>A user who has negative account liquidity is subject to liquidation by other users of the protocol to return his/her account liquidity back to positive (i.e. above the collateral requirement). When a liquidation occurs, a liquidator may repay some or all of an outstanding borrow on behalf of a borrower and in return receive a discounted amount of collateral held by the borrower; this discount is defined as the liquidation incentive.</em></p><p>A user’s <strong>account liquidity</strong> (you can read more about it <a href="https://docs.compound.finance/v2/comptroller/#account-liquidity">here</a>) is the amount in USD that a user is able to borrow.</p><p>We are going to go through an example to grasp this better, but before that we need to understand the collateral factor.</p><p>The <strong>collateral factor</strong> is a percentage that ranges between 0–90% that represents the amount that a user can borrow from minting cTokens. The more stable and liquid an asset is, the higher the collateral factor and vice versa.</p><p>Ok, so let’s suppose that Alice supplies 1 Eth to Compound. The price of Eth is $1,000 USD and the collateral factor is 90%. This means that Alice will have an account liquidity of $900 USD (90% of $1,000).</p><p>Then Alice borrows 900 USD of DAI, her new account liquidity would be 0. If the price of Eth goes down, her account liquidity would be negative and liquidators would be able to trigger this liquidation.</p><p><em>*To see this in code, go to the file located under test/AccounLiquidity.t.sol</em></p><p>One last characteristic to understand is that the system doesn’t guarantee that liquidation will take place. It provides incentives so users (liquidators) are constantly watching for a liquidation opportunity so they call the liquidation function and get some money in return.</p><h4>Comptroller</h4><p><em>The Comptroller is the risk management layer of the Compound protocol; it determines how much collateral a user is required to maintain, and whether (and by how much) a user can be liquidated. Each time a user interacts with a cToken, the Comptroller is asked to approve or deny the transaction.</em></p><p>You can think of the Comptroller as a provider and verifier contract that gives information to the cTokens and checks that a user can execute a given transaction.</p><p>* You can find the Comptroller <a href="https://etherscan.io/address/0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B#code">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qFFeGA6AcscTvjLO" /></figure><p><strong>NOTE:</strong> <em>This diagram is not 100% accurate as the architecture is implemented through upgradable proxies but the general concept remains intact.</em></p><h3>Governance</h3><p>One crucial aspect of smart contract systems is their governance model.</p><p>This is probably the most important governance smart contracts in EVM chains, it is used in many protocols.</p><p>This is a complex topic for a short post, so to simplify it, we can think of what governance is by asking the following questions:</p><ul><li>Are the contracts upgradable? If they are, Who can upgrade them?</li><li>Are there any other special privileges in the contracts? For example, can an admin key blacklist certain users?</li></ul><p>These are the most fundamental points that we should focus on smart contract systems. If there are privileged keys that can blacklist users, upgrade the contracts or pause them, then the system is not very trustless or secure.</p><p>Ok, let’s go back to Compound.</p><p>Compound V2 is built around a decentralized voting process. To understand this, it is important to know what upgradable proxies are, you can read about them <a href="https://docs.openzeppelin.com/upgrades-plugins/1.x/proxies">here</a>.</p><p>I am going to go through the most important aspects of the governance process, to simplify it as much as possible.</p><p>If we remember from the previous part, the Comptroller is the contract that basically does a bunch of safety checks for the cTokens.</p><p>The Comptroller is architected as an upgradable proxy, the name of the actual proxy is named the “Unitroller”, you can find the contract’s code <a href="https://etherscan.io/address/0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B#code">here</a>.</p><p>The Unitroller delegates all calls to the Comptroller singleton, but it also has some additional methods, primarily changing the implementation contract and changing the admin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fi0XH0ECgkIMrk-O" /></figure><p>So there are a couple of important security things going on here.</p><p>First of all, if someone upgrades the implementation contract (we will do it later on as a POC) to a malicious address, and changes the admin, then all user’s funds will be lost as there is no way to get it back.</p><p>The process basically works by proposing a proposal, voting (favour or against) and executing the proposal if succeeded.</p><p>Let’s get into the low level process of how making changes to the contract works.</p><h4>1. Propose</h4><p>The first thing is to propose a proposal, and this is done on chain by calling the “propose” function from the GovernorBravoDelegate contract. You can find it <a href="https://etherscan.io/address/0xc0Da02939E1441F497fd74F78cE7Decb17B66529#code">here</a>.</p><pre>function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint)</pre><p>In order to be able to call the propose function, the proposer (msg.sender) should have at least x amount of COMP tokens or votes. This minimum amount of votes to propose a proposal is called the “proposalThreshold” and it is currently 25,000. This means that if you have less than 25,000 COMP tokens or votes, you are not able to be a proposer.</p><p>Once the proposal goes through, there is a voting delay of 13,140 blocks (around 2 days). This means that we need to wait 13,140 blocks to start the voting process.</p><h4>2. Vote</h4><p>Once the voting delay period has passed, the process of voting begins.</p><p>*Users that have “votes” are the ones that are able to vote. For example, if you have 100 COMP tokens and you delegate them to yourself, then you have 100 votes. You can also delegate your 100 COMP tokens to someone else, deferring your votes.</p><p>The process is very simple, there is a function called castVote that voters call with their vote preference. (There are more voting functions but they are all pretty much the same).</p><pre>function castVote(uint proposalId, uint8 support) externalt</pre><p>You just need to pass the id of the proposal and your vote support (0=against, 1=for, 2=abstain).</p><p>Once you vote, all the votes that your account owns will be summed up to the proposal’s state. For example, if you have 10,000 COMP tokens and you are the delegator of your own tokens and vote in favour of a proposal, then that proposal will increase its “for” votes by 10,000.</p><p>The voting period currently lasts for 19,710 blocks (around 3 days).</p><p>Once the voting period ends, it is time to queue the proposal.</p><h4>3. Queue</h4><p>Once all the votes were gathered and the voting period ends, the proposal either “Succeeded” or got “Defeated”. If the proposal succeeded, then the next step can go through.</p><p>The proposal is successful if:</p><p><strong>a)</strong> There were more votes in favour than against</p><p><strong>b)</strong> The “for” votes are greater than the quorumVotes.</p><p>There is a minimum amount of “for” votes in order for the proposal to go through. Currently, the minimum or “quorumVotes” is 400,000.</p><p>The next step (if the proposal succeeds) is to queue it to the Timelock contract. You can find the contract <a href="https://etherscan.io/address/0x6d903f6003cca6255D85CcA4D3B5E5146dC33925">here</a>.</p><p>Once the transaction has been queued to the Timelock contract there is a 172,800 seconds delay (2 days). Once the delay is over, the transaction can be executed.</p><h4>4. Execute</h4><p>After the 2 days Timelock delay has passed, the proposal can be executed.</p><p>This is simply done by calling the “execute” transaction from the GovernorBravoDelegate contract.</p><p>This function will execute the proposal from the context of the Timelock contract.</p><p>A more realistic architecture of how the governance contracts are implemented:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c1DIUJysNTyiQpWv" /></figure><p>And a visual representation of the proposal process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UHFlwP20yKBVXsdn" /><figcaption><a href="https://docs.compound.finance/v2/governance/">https://docs.compound.finance/v2/governance/</a></figcaption></figure><p><strong>NOTE: </strong><em>If a protocol has a badly structured governance model (easy to manipulate), then the governance model becomes the security’s weakest link. As you can see from the previous explanation, the governance of a protocol like Compound has the power to make critical changes that affect (in a positive or negative way) all users.</em></p><p><em>In the Compound’s case, the security of the protocol goes hand in hand with the COMP token valuation. If the total market cap is very low, the possibilities of someone taking control rise significantly.</em></p><h3>Hands-On</h3><p>For this next part, we are going to execute the most common operations in the Compound.</p><p>You can find the GitHub repo <a href="https://github.com/rodrigoherrerai/Compound-V2-Examples">here</a> (you should clone the repo to follow along).</p><p><strong>NOTE:</strong> <em>The examples are done by forking the Ethereum mainnet at block </em><a href="https://etherscan.io/block/16401180"><em>16401180</em></a><em> and using Foundry.</em></p><h4>Governance (upgrading the Comptroller)</h4><p>This is probably the most interesting example. We are going to go through the entire proposal lifecycle that we covered in the Governance section.</p><p>*The file is located at test/UpgradeComptroller.t.sol</p><p>In this example, we are going to create a proposal, vote, win it in our favour, and then execute it. The proposal is to change the Comptroller implementation to a malicious singleton.</p><p>Here is the code:</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity &gt;= 0.8.0;<br><br>import &quot;forge-std/Test.sol&quot;;<br><br>import &quot;../src/NewComptroller.sol&quot;;<br>import &quot;./utils/TestUtils.sol&quot;;<br><br>/// @notice Example contract that upgrades the Comptroller.<br>/// This example also goes through the entire governance journey:<br>/// 1. Create the proposal<br>/// 2. Vote<br>/// 3. Queue it to the Timelock<br>/// 4. Execute the proposal<br>contract UpgradeComptrollerTest is Test, TestUtils {<br>    NewComptroller newComptroller;<br><br>    receive() external payable {}<br><br>    function setUp() public {<br>        // Fork mainnet at block 16_401_180.<br>        cheat.createSelectFork(&quot;mainnet&quot;, BLOCK_NUMBER);<br><br>        ///// We fund this test contract with 400K COMP tokens.<br>        uint256 TRANSFER_AMOUNT = 400_000 * 1e18;<br><br>        cheat.startPrank(0x2775b1c75658Be0F640272CCb8c72ac986009e38);<br>        comp.transfer(address(this), TRANSFER_AMOUNT);<br>        cheat.stopPrank();<br><br>        assertEq(comp.balanceOf(address(this)), TRANSFER_AMOUNT);<br>        /////<br><br>        ///// Now we delegate all votes to this address.<br>        comp.delegate(address(this));<br>        /////<br><br>        // We increase the block number by 1 so the votes are actionable.<br>        vm.roll(block.number + 1);<br>        assertEq(comp.getPriorVotes(address(this), block.number - 1), TRANSFER_AMOUNT);<br><br>        // We create the new singleton Comptroller.<br>        newComptroller = new NewComptroller();<br>    }<br><br>    /// @notice This test function goes through the complete governance model of Compound.<br>    /// It ends up upgrading the comptroller singleton.<br>    function testUpgradeComptroller() public {<br>        // 1. We CREATE and send the PROPOSAL.<br>        uint256 proposalId = propose();<br><br>        // We increase the block number by the voting delay.<br>        uint256 votingDelay = gBravo.votingDelay(); // 13140 blocks<br>        vm.roll(block.number + votingDelay + 1);<br><br>        // 2. We VOTE in favor of our proposal.<br>        gBravo.castVote(proposalId, 1); // 0=against, 1=for, 2=abstain<br><br>        // We increase the block number so it gets to the voting end.<br>        uint256 votingPeriod = gBravo.votingPeriod(); // 19710 blocks<br>        vm.roll(block.number + votingPeriod);<br><br>        // 3. We QUEUE the transaction to the timelock.<br>        gBravo.queue(proposalId);<br><br>        // We increase the timestamp number by the timelock delay.<br>        uint256 timelockDelay = timelock.delay();<br><br>        vm.warp(block.timestamp + timelockDelay);<br><br>        // 4. We EXECUTE the PROPOSAL.<br>        gBravo.execute(proposalId);<br><br>        // We accept the implementation.<br>        newComptroller.acceptImplementation(address(comptroller));<br><br>        // We check that the comptroller has been upgraded.<br>        (bool success, bytes memory data) =<br>            address(comptroller).staticcall(abi.encodeWithSignature(&quot;testImplementation()&quot;));<br>        require(success);<br>        string memory result = abi.decode(data, (string));<br>        assertEq(result, &quot;I am the new Comptroller&quot;);<br>    }<br><br>    function propose() internal returns (uint256) {<br>        address[] memory targets = new address[](1);<br>        targets[0] = address(comptroller);<br><br>        uint256[] memory values = new uint[](1);<br>        values[0] = 0;<br><br>        string[] memory signatures = new string[](1);<br>        signatures[0] = &quot;&quot;;<br><br>        bytes[] memory calldatas = new bytes[](1);<br>        calldatas[0] = abi.encodeWithSignature(&quot;_setPendingImplementation(address)&quot;, address(newComptroller));<br><br>        string memory description = &quot;Upgrades the Comptroller&quot;;<br><br>        uint256 proposalId = gBravo.propose(targets, values, signatures, calldatas, description);<br>        require(proposalId &gt; 0, &quot;Proposal failed&quot;);<br>        return proposalId;<br>    }<br>}</pre><h4>Supply &amp; Redeem</h4><p>In this example, we are going to supply Eth to the CEth market and then redeem it.</p><p>*The file is located at test/SupplyAndRedeem.t.sol</p><p>The steps to supply to a Compound market and get a cToken in return are the following:</p><ol><li>Deposit the underlying asset by calling the “mint()” function.</li></ol><p>The mint function from the cToken will:</p><ul><li>Transfer the underlying token amount (mintAmount) to the cToken contract or msg.value for cEther.</li><li>Mint the corresponding cTokens (depositAmount / exchangeRate).</li></ul><p>We will be mainly interacting with the cEther contract, you can find it <a href="https://etherscan.io/address/0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5">here</a>.</p><p>Here is the complete test case for:</p><p>a) calculating the exchange rate</p><p>b) supplying</p><p>c) redeeming</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity &gt;= 0.8.0;<br><br>import &quot;forge-std/Test.sol&quot;;<br><br>import &quot;./utils/TestUtils.sol&quot;;<br><br>/// @notice Example contract that supplies an asset to Compound and redeems it.<br>contract SupplyAndRedeemTest is Test, TestUtils {<br>    receive() external payable {}<br><br>    function setUp() public {<br>        // Fork mainnet at block 16401180.<br>        cheat.createSelectFork(&quot;mainnet&quot;, BLOCK_NUMBER);<br>    }<br><br>    /// @dev Calculates the exchange rate between eth and cEther.<br>    function getExchangeRate() internal returns (uint256) {<br>        // exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply.<br>        uint256 totalCash = cEther.getCash();<br>        assertEq(totalCash, address(cEther).balance);<br><br>        uint256 totalBorrows = cEther.totalBorrowsCurrent();<br>        assert(totalBorrows &gt; 0);<br><br>        uint256 totalReserves = cEther.totalReserves();<br>        assert(totalReserves &gt; 0);<br><br>        uint256 totalSupply = cEther.totalSupply();<br>        assert(totalSupply &gt; 0);<br><br>        uint256 exchangeRate = 1e18 * (totalCash + totalBorrows - totalReserves) / totalSupply;<br>        return exchangeRate;<br>    }<br><br>    /// @notice Supplies Eth to Compound, checks balances, accrues interests, and redeems.<br>    function testSupplyAndRedeem() public {<br>        // We save the initial eth balance to compare it later on.<br>        uint256 initialEthBalance = address(this).balance;<br><br>        // Our initial cEther balance should be 0.<br>        assertEq(cEther.balanceOf(address(this)), 0);<br><br>        // We supply 1 ether.<br>        cEther.mint{value: 1 ether}();<br><br>        // We could get the exchange rate by calling &quot;exchangeRateCurrent()&quot; directly.<br>        // We calculate it ourselves for learning purposes.<br>        uint256 exchangeRate = getExchangeRate();<br><br>        // We get the balance of cEther after supplying.<br>        uint256 cEtherBalance = cEther.balanceOf(address(this));<br><br>        // We get the amount of cEther that we should have.<br>        uint256 mintTokens = 1 ether * 1e18 / exchangeRate;<br>        assertEq(cEtherBalance, mintTokens);<br><br>        // We incrase the block number by 1.<br>        vm.roll(block.number + 1);<br><br>        // We redeem all the cEther.<br>        require(cEther.redeem(cEther.balanceOf(address(this))) == 0, &quot;redeem failed&quot;);<br><br>        // We should have 0 cEther.<br>        assertEq(cEther.balanceOf(address(this)), 0);<br><br>        // Eth + interests. We should have more eth with 1 block of interests.<br>        assert(address(this).balance &gt; initialEthBalance);<br>    }<br>}</pre><h4>Borrow &amp; Repay</h4><p>In this example, we supply Eth as collateral, enter the markets, borrow Dai and then repay it.</p><p>*The file is located at test/BorrowAndRepay.t.sol</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity &gt;= 0.8.0;<br><br>import &quot;forge-std/Test.sol&quot;;<br><br>import &quot;./utils/TestUtils.sol&quot;;<br><br>/// @notice Example contract that borrows and repays from Compound.<br>contract BorrowAndRepayTest is Test, TestUtils {<br>    function setUp() public {<br>        // Fork mainnet at block 16_401_180.<br>        cheat.createSelectFork(&quot;mainnet&quot;, BLOCK_NUMBER);<br>    }<br><br>    /// @notice Supplies Eth to Compound, checks balances, accrues interest, and redeems.<br>    function testBorrowAndRepay() public {<br>        // We shouldn&#39;t have any Dai balance at this time.<br>        assertEq(dai.balanceOf(address(this)), 0);<br><br>        ///// We need to supply some eth for collateral.<br>        cEther.mint{value: 1 ether}();<br><br>        // We enter the markets.<br>        address[] memory cTokens = new address[](1);<br>        cTokens[0] = address(cEther);<br>        comptroller.enterMarkets(cTokens); // &lt;- we enter here<br><br>        // Checks<br>        address[] memory assetsIn = comptroller.getAssetsIn(address(this));<br>        assertEq(assetsIn[0], address(cEther));<br><br>        /////<br><br>        ///// Now we borrow some dai.<br>        uint256 borrowAmount = 500 * 1e18; // 500 dai<br>        cDai.borrow(borrowAmount);<br><br>        // Checks .. We should have 500 dai<br>        assertEq(dai.balanceOf(address(this)), borrowAmount);<br><br>        /////<br><br>        ///// We repay the dai.<br>        dai.approve(address(cDai), borrowAmount);<br>        cDai.repayBorrow(borrowAmount);<br><br>        assertEq(dai.balanceOf(address(this)), 0);<br>    }<br>}</pre><h3>References</h3><ul><li><a href="https://compound.finance/documents/Compound.Whitepaper.pdf">compound.finance</a></li><li><a href="https://docs.compound.finance/v2/">Compound v2 Documentation</a></li><li><a href="https://docs.compound.finance/v2/">Compound is an algorithmic, autonomous interest rate protocol built for developers, to unlock a universe of open financial applications.</a></li><li><a href="https://docs.compound.finance/v2/">docs.compound.finance</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6227c0528b5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/compound-v2-in-depth-6227c0528b5">Compound V2 in Depth</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Deep Dive Into the Uniswap V2 Protocol]]></title>
            <link>https://medium.com/better-programming/uniswap-v2-in-depth-98075c826254?source=rss-25fc5577e294------2</link>
            <guid isPermaLink="false">https://medium.com/p/98075c826254</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[uniswap]]></category>
            <dc:creator><![CDATA[Rodrigo Herrera I]]></dc:creator>
            <pubDate>Fri, 20 May 2022 10:06:27 GMT</pubDate>
            <atom:updated>2024-06-04T21:28:36.961Z</atom:updated>
            <content:encoded><![CDATA[<h3>Uniswap V2 in Depth</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xxFF55G0Cf6znuddFOY2Eg.png" /></figure><h4><em>Prerequisites</em></h4><p>In order to follow along, it is useful to have the following knowledge:</p><ol><li>General understanding of the EVM</li><li>Comfortable with Solidity</li><li>Basic math (Algebra)</li><li>General understanding of the fundamentals of blockchains and smart contract protocols built on top</li></ol><h3>UniSwap V2</h3><p>The post is divided into two main parts: The first one, “Systems Components Overview,” explains the theory and practice behind the most important components that make the system work.</p><p>The second part, “System’s CORE Implementation,” goes through the actual architectural implementation.</p><p>I believe that to truly understand a system in depth, you should be able to rewrite it from scratch. Hopefully, by the end of this post, you will be able to do that.</p><p>In order to start learning the system in a structured manner, it is important to ask ourselves some questions that are fundamental to the system:</p><ul><li>How does Uniswap’s pricing mechanism work?</li><li>Who provides liquidity to the system?</li><li>Why would someone provide liquidity to the system?</li><li>How does the system represent liquidity?</li></ul><p>Along the way, all the fundamental questions should be answered by understanding the protocol deeply.</p><p>Before starting, let’s quickly talk about what Uniswap is.</p><p>Uniswap is a decentralized automated market maker protocol that allows anyone to swap token A for token B. Automated market makers work differently from a traditional <a href="https://en.wikipedia.org/wiki/Order_book">order book model</a>. The core principle that differentiates an automated market maker (Uniswap) from a traditional centralized order book is that the former runs permissionless code on the blockchain allowing anyone to participate.</p><p>Before moving on, I want to say a couple of things.</p><ol><li>Uniswap V2 is decentralized: Decentralization is not binary, but from my point of view (and many others), a decentralized smart contract protocol is one in which no central party can access the user’s funds. In other words, no one has a special key that can modify the contracts.</li><li>There are three versions of Uniswap: For this post, we will focus on V2 (we will do a V3 post in the future). But if you want to learn how Uniswap was created, I suggest watching <a href="https://www.youtube.com/watch?v=LpjMgS4OVzs">this </a>video.</li><li>A lot of AMMs are a fork of Uniswap V2: Uniswap V2 is much simpler than V3, therefore, easier to maintain. So once you know how Uniswap V2 works, you will know most of the AMMs as well!</li></ol><p>Let’s start!</p><h3>Systems Components Overview</h3><p>To start getting a feeling of how the protocol works, we need to ask ourselves what is really happening when we are doing a simple swap. Of course, the purpose of the entire post is to explain this.</p><p>But at a basic level, you are interacting with a smart contract (pool) that “holds” reserves of two different tokens. For example, if you are swapping some WETH for USDC, you are interacting with the WETH/USDC smart contract pair (we will detail how this works later on). If you are interested, <a href="https://etherscan.io/address/0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc">here</a> is the WETH/USDC smart contract pair on Etherscan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*5Yx42z0zYnjTjkIaUrK0VA.png" /><figcaption>WETH/USDC Pool</figcaption></figure><p>So, if you are buying USDC with WETH, you are increasing the supply of WETH in the pool and reducing the supply of USDC, therefore, increasing the relative price of USDC vs WETH.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*YQmXMw8JfYvSsKTArZE2BA.png" /></figure><p><em>In the following sections, we will discuss how the pool works (the math behind it).</em></p><p>One important thing to keep in mind is that UniswapV1’s pools were always traded against Eth. In other words, every pool was ETH/xToken.</p><p>In Uniswap V2, every pool is ERC-20/ERC-20. This approach provides more flexibility to liquidity providers as they don’t need to rely 100% on ETH. So, every time you swap ETH for another token, your ETH gets converted to WETH first.</p><h3>Protocol Participants</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PMwLT1BZstsRQ4baV-eMgw.png" /><figcaption><a href="https://docs.uniswap.org/protocol/V2/concepts/protocol-overview/ecosystem-participants">https://docs.uniswap.org/protocol/V2/concepts/protocol-overview/ecosystem-participants</a></figcaption></figure><p>Uniswap works by providing incentives to different participants to work with the system in order for them to profit. The main participants of the system are:</p><ol><li>Traders: Traders can perform several actions in the system; some of them are:</li></ol><ul><li>Speculating on the price of an asset.</li><li>Arbitrage software. For example, if the price of ETH in Uniswap is trading at $3,000 and in Coinbase is trading at $3,800, the arbitrageur would immediately buy ETH in Uniswap and resell it in Coinbase for a profit.</li><li>Basic swap functionality. You want to change token x to token y to use them in a Dapp.</li></ul><p>2. Liquidity Providers (LPs): LPs provide liquidity to the token pools. As rewards, they get the transaction fees.</p><p>3. Developers: Developers create the systems and applications that exist in the ecosystem. In Uniswap terms, they can be core protocol developers, third-party Dapp developers that integrate with Uniswap, wallet developers, etc.</p><p>Before diving into smart contracts, let’s understand the core concepts.</p><p>There are three basic components that we need to understand in order to have a deep knowledge of Uniswap (and most of the DeFi protocols): They are constant product formula, arbitrage, and impermanent loss.</p><h4>Fees</h4><p>UniswapV2 charges a flat 0.3% fee per trade. We will see how this is calculated in future sections. The fee goes to the liquidity providers, and this is to reward people for their liquidity. The protocol can also trigger a change that would give 0.05% to the Uniswap team, and that part of the fee would be discounted from the LPs instead of the traders.</p><h3>Constant Product Formula in Depth</h3><p>A lot of the automated market makers work thanks to the constant product formula. It is a very simple yet powerful algorithm.</p><p>The constant product formula is the automated market algorithm that powers the Uniswap protocol (and a lot more AMMs).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*OKyLT5iZ15W6baOScSa81g.png" /><figcaption>Constant Product Formula</figcaption></figure><p>This formula simply states that the invariant k must remain unchanged regarding the outflow/inflow of x and y.</p><p>In other words, you can change the value of x and y to whatever you want, as long as k remains the same.</p><h4>For example:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*xDMmVhZiTQe-kUlpEcxgPA.png" /></figure><p>What are x and y?</p><p>x and y are the reserves of the tokens in the pool. For example, if you are swapping DAI for WETH, you are interacting with the DAI/WETH smart contract pool. The total amount of DAI that the contract holds would be x, and the total amount of WETH would be y.</p><p>Simple enough. This is the algorithm that powers a lot of AMMs.</p><p>In the actual implementation, the formula is a bit different.</p><p>Let’s see the real formula that Uniswap V2 uses.</p><p><a href="https://github.com/Uniswap/v2-core/blob/master/contracts/UniswapV2Pair.sol#L159">Here</a>, you can find the full “swap” function implementation. But we are particularly interested in the following lines of code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*2DOhNSBU8OadB3IiRqPtUg.png" /></figure><p>This piece of code is the real implementation of the constant product formula. Everything else you have read or seen is just the theory. These lines of code are the bare metal implementation of the constant product formula.</p><p>There are four variables inside the require statement:</p><ul><li>balance0Adjusted: Reserves of <strong>x</strong> after the trader sends tokensX to the pool minus 0.3% of the amount sent.</li><li>balance1Adjusted: Reserves of <strong>y</strong> after the tokensY are sent to the trader from the pool.</li><li>_reserve0: Reserves of token x prior to the swap.</li><li>_reserve1: Reserves of token y prior to the swap.</li></ul><p>Of course, balance0Adjusted and balance1Adjusted can be treated inversely.</p><p>Let’s do an example to understand this better:</p><ul><li>There is a DAI/WETH pool in Uniswap.</li><li>Current reserves are 20000DAI / 10 WETH, and a trader wants to exchange 1 WETH for 1500 DAI:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PK-OorgJvcOs9fIIxNTJCg.png" /></figure><p>As you can see, the trader sent 1 WETH to the pool in exchange for 1500 DAI. They could have gotten more DAI for their WETH, but the point here is to illustrate two things:</p><ol><li>The k never remains constant. It always increases due to the transaction fees, but it can also increase if people use the system inefficiently (like in our example, the trader could have gotten more DAI for their WETH).</li><li>The only check that the swap function really enforces is that the new reserves (minus fees) are greater than or equal to previous reserves: newK ≥ oldK.</li></ol><p>Here is actual code implementation of the previous example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*mAineVH11nIAQs8L5XLk5Q.png" /></figure><p>As you can see, things are multiplied by 1000. This is because there is no floating point numbers in Solidity, so this is necessary to represent the 0.3% fee. That is why the amount0In or amount1in are multiplied by 3 (to represent the 0.3%).</p><h4>Getting the maximum amount out</h4><p>A very important thing to understand is the maximum amount of tokens that you can get for a given input.</p><p>NOTE: In Uniswap V2 Periphery, you have all the helper functions to implement this math.</p><p>Example: <br>We have a DAI /WETH pool with the following reserves: <br>- DAI: 100,000<br>- WETH: 20</p><p>We want to swap 1 WETH for the maximum amount of DAI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P8EiwaJEXnT5-fMFxxHeZg.png" /></figure><p>The maximum amount of DAI that we would get for 1 WETH (for this pool) is 4748.29.</p><p>The math we just did can also be represented in code (this function is from V2 Periphery):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*XDFb_fwdMmMWLhkSKz_z_g.png" /></figure><p>It is very important to always get this math right in order to avoid getting fewer output tokens.</p><p>As a final note on this topic, you may be wondering what determines the variable k?</p><p>K is determined when the pool is first created, and then it grows every time there is a new trade. If we go to our past example, if a trader executes a swap just after the one we did, the k for their trade is going to be the newK of the prior trade.</p><h3>Arbitrage</h3><p>Arbitrage is one of the most important concepts to understand how Uniswap works. Although this concept is not unique to Uniswap, it applies to almost all of the DeFi projects. In order to understand this concept better, the first thing we need to ask ourselves is, how does Uniswap know the price of a given token?</p><p>For example, when you are swapping WETH for DAI in Uniswap, how does the protocol know that the price of WETH relative to DAI is x?</p><p>The short answer is that Uniswap has no clue what the real price is. In reality, the price matches the outside world due to incentives.</p><p>The only thing that the protocol really enforces in order to make a successful swap is the “constant product formula.”</p><p>Let’s go through an example.</p><p>Suppose there is a DAI/WETH pool in Uniswap. The price of WETH in Uniswap is trading at around 3000 DAI. We can get the price by dividing the number of reserves of DAI by the number of reserves of ETH (this is not the precise amount that you would get, we calculated that in the previous section).</p><p>Now, here comes the opportunity!</p><p>The price of WETH is trading at $3,200 on Coinbase. There is a difference of $200 USD between the WETH price of Uniswap and Coinbase. This will create an arbitrage opportunity, and immediately an arbitrageur (bot software) will buy WETH in Uniswap and sell it in Coinbase until the price matches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*P8-Qz-HvRY_AGKYmSxeddA.png" /></figure><p>This is how the prices in Uniswap are correlated with the outside world by arbitrageurs that are constantly searching for an arbitrage opportunity. There are different types of arbitrage (we will not go into detail). But for the example shown, it is not an atomic arbitrage.</p><p>In other words, the risks are higher because there is a probability that when the arbitrageur tries to earn a profit in Coinbase, the prices are already at par (because another arbitrageur did it first). That is why the safest arbitrage is done on-chain because transactions are atomic, meaning, if something fails, the whole transaction reverts (minus gas fees).</p><p>So, in conclusion, Uniswap does not know about the outside world prices. Thanks to the arbitrageurs, the prices are almost identical to the outside world.</p><h3>Impermanent Loss</h3><p>Impermanent loss for liquidity providers is the change in dollar terms of their total stake in a given pool versus just holding the assets.</p><p>Let’s create an example to understand this better.</p><p>Imagine that Alice has some tokens in her wallet, so she wants to become a liquidity provider to earn some yield. For our example, she is going to create a new DAI/WETH pool in Uniswap. The current market price of WETH is $3,000, so to avoid arbitrage, she will need to initiate the pool by putting 3000 DAI for every WETH.</p><p>She will initiate the pool by putting 10 WETH and 30,000 DAI in, with a total USD value of $60,000 (we need to keep this number in mind).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*xF9lCM4mH_2m-ZkGg7Atxw.png" /></figure><p>*To make it simple, we will not take the transaction fees into consideration.</p><p>Great, so now Alice has become an LP of this DAI/WETH Uniswap pool. Now, let’s imagine that the price of WETH goes up to $4,687. As you should know by now, this will create a huge arbitrage opportunity, so immediately, an arbitrageur will buy ETH in Alice’s pool until the price is at par with the outside market.</p><p>So, after some arbitrage, Alice’s pool will look something like this (again, we are not considering the transaction fees):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*HdQMd06iIqCrux4iFQEbnw.png" /></figure><p>As we can see, after some arbitrage, now the pool has 8 WETH instead of 10 and 37,500 DAI instead of 30,000 (what Alice initially supplied). The total amount of the pool is now $75,000 ((8ETH * $4,687.5) + 37,500)).</p><p>Here comes the problem: If Alice had just held the assets, she would have had more money. Remember that initially, she supplied the pool with 10 WETH and 30,000 DAI. So, in the end, she had an impermanent loss of $1,875:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*XDuOOaNoM_0ugSsrhgo2rw.png" /></figure><p>For this example, we did not contemplate the profit from transaction fees (0.3%), but the concept remains unchanged.</p><p>It is called “impermanent” because the loss only applies if the LPs sell at the present time. If the assets fluctuate, then that loss can be mitigated.</p><p>Hopefully, the concept is clear by now! If still in doubt, I highly recommend watching <a href="https://www.youtube.com/watch?v=8XJ1MSTEuU0">this video</a>.</p><h3>Liquidity / LP Tokens</h3><p>Big amounts of liquidity are what make Uniswap an attractive system to use. Without enough liquidity, the system becomes inefficient, particularly for big trades relative to the total liquidity of the pool.</p><p><em>Note: For big trades (relative to the pool), it is better to use an aggregator to decrease slippage as much as possible.</em></p><p>Ok! So the first thing we need to understand is, how are LP tokens minted and burned?</p><p>When a liquidity provider provides liquidity to a pool, it receives its LP tokens proportionally to its amount of liquidity.</p><p>Let’s unpack this.</p><p>A Uniswap pool is just a smart contract that “holds” a certain amount of reserves (token x and y). The liquidity providers provide these reserves. But, this pool also has an in-house token called “LP token.” This token is unique to each pool, and the main purpose is to keep track of the liquidity each liquidity provider has injected. You can think of this token as a certificate of your liquidity. This token also accrues the 0.3% fee that Uniswap charges.</p><p>The smart contract pool imports “UniswapV2ERC20.sol” (you can find it <a href="https://github.com/Uniswap/v2-core/blob/master/contracts/UniswapV2ERC20.sol">here</a>), which is basically a contract that has basic ERC20 functionality (minting, burning, transfer, etc..).</p><p>The LP tokens are “stored” inside of this UniswapV2ERC20.sol. Every time a liquidity provider provides liquidity, some amount of tokens are minted to his address. Inversely, every time the liquidity provider takes liquidity out, the LP tokens are burned.</p><p>So, how does this work?</p><p>If we think about it from a high level, a liquidity provider can a) provide liquidity and b) take out the liquidity. Uniswap implements this mechanism in two functions: mint() and burn().</p><p>Let’s first go with the mint function. You can find the full function implementation <a href="https://github.com/Uniswap/v2-core/blob/master/contracts/UniswapV2Pair.sol#L110">here</a>.</p><p>In order to calculate the LP tokens that a liquidity provider receives, we first need to know if there is liquidity or if it is the first time someone is providing liquidity.</p><p>Here is the piece of code (inside of the mint function) that we are interested in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*ofrmguD2_Yey3hgRVEdAag.png" /></figure><p>The MINIMUM_LIQUIDITY is a constant variable equal to 1000:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*LR5vZw3ZTHQGZxae9cgaLQ.png" /></figure><p>To understand this better, we are going to go through an example.</p><p><strong>Note</strong>: In Ethereum, the currency for computation is WEI (ETH * 10 **18). This also applies to most of the ERC-20 tokens. For simplicity, we will write the numbers without the 18 zeroes, but every time there is a hardcoded number like MAXIMUM_LIQUIDITY = 1000, we will just accommodate that number instead.</p><p>Let’s suppose that Alice (a liquidity provider) just created a new DAI/WETH pool.</p><p>She will supply 10,000 DAI and 2 WETH:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*VyIsyt4GaPR_n5wlXcSWDA.png" /></figure><p>Before Alice, the total supply of the pool was 0, so the first thing that is going to happen is mint 1000 tokens to the address 0 (this is done to maintain a minimum liquidity):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xuI4ZnzJFgsBB2hqaFfdfA.png" /></figure><p>Note: <em>Every time there is a mint, the totalSupply variable gets updated</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*HM3TzTbdov0VrnXLsM-4Ig.png" /></figure><p>We then get the amount of LP tokens that are going to be minted to the liquidity provider (Alice). For our example, the result was 141.42. <br>Again, this is the formula to determine that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vMNRtw0ys8SWBSZlVoSZtA.png" /></figure><p>Great, so now our pool consists of the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*daY1B0A43CKFqdiAypeuug.png" /></figure><p>Total supply means the total amount of LP tokens there are in circulation (do not confuse it with the x and y reserves).</p><p>Now, let’s imagine that Alice wants to withdraw every DAI and WETH she put into the pool. For the sake of simplicity, let’s suppose that the reserves remain the same.</p><p>In order for Alice to remove her liquidity, she needs to call the burn function, but prior to that, she needs to transfer all her LP tokens to the pool’s address. Let’s understand how this works. Here is the complete burn function implementation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*l_J6nU5ip4czjcqvrZxcJQ.png" /></figure><p>If we see line 187, the variable liquidity is the amount of LP tokens that the contract’s address hold. Hence, that is why I mentioned that Alice needs to transfer the LP tokens prior to the function call. Then, in lines 191 and 192 are the amounts of tokens x and y to be transferred to Alice.</p><p>Following our example, let’s unpack this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*0wIDUKcORqPdnKGUD2jQQg.png" /></figure><p>As you can see, amount0 = 10000 and amount1 = 2. That is the initial amount that Alice supplied!</p><p>After the amounts are calculated, they are transferred and then burned.</p><p>This is the magic behind LP tokens!</p><p>As a final note on this topic, if we remember, the protocol charges a 0.3% trading fee. This fee goes to the liquidity providers. The way the fee is technically accrued is by increasing the reserves of x and y in every trade. This will positively impact the amount of LP tokens each liquidity provider holds (proportionally to their holdings).</p><p>If we go back to the burn function, these two lines of code are what calculates the number of tokens x and y to send to the liquidity provider when they want to exchange their LP tokens for the x and y tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*BBBv2Rk5si09wTfUoxzm5w.png" /></figure><p>Every time a trader executes a swap, it needs to send a buffer of 0.3% relative to the size of the trade. That 0.3% increments the reserves of the pool. Therefore, increasing the value of <em>balance0 </em>and <em>balance1</em> in the burn function.</p><h3>System’s CORE Implementation</h3><p>Now that we have a solid understanding of the individual components let’s go to the actual implementation.</p><p>This part will be much faster, as the core topics were already covered.</p><h4>Protocol Architecture</h4><p>Uniswap V2 is a binary smart contract system. It is composed of the <a href="https://github.com/Uniswap/v2-core">V2-Core</a> and <a href="https://github.com/Uniswap/v2-periphery">V2-Periphery</a>.</p><ul><li>V2-Core are the low-level base contracts. These smart contracts are responsible for the system’s functionality.</li><li>V2-Periphery are helper contracts that allow frontend applications and developers to integrate with the core contracts by applying safety checks and abstracting away certain things.</li></ul><p>In simpler terms, V2-Core is the part of the protocol that implements the core features (swapping, minting, burning, etc.). In contrast, V2-Periphery is one layer up. It is a set of contracts and libraries that make the integration easier for the developers.</p><p>The Uniswap team also architected this modular codebase approach to reduce security-critical vulnerabilities by having the bare minimum in V2-Core. In other words, they only implemented what is necessary for V2-Core, so there is less code to audit (therefore more secure). All the helper functions were thrown to V2-Periphery.</p><p>We will only focus on V2-Core. The simple reason is that if you know how V2-Core works, you also know how V2-Periphery works (but not the other way around).</p><p>Again, you can find the V2-Core repo <a href="https://github.com/Uniswap/v2-core/tree/master/contracts">here</a>.</p><p>There are three main contracts:</p><ol><li>UniswapV2ERC20.sol: This contract is responsible for handling the LP tokens. It is a basic ERC20 contract, so we will not go over this.</li><li>UniswapV2Factory.sol: This is the factory that is responsible for deploying new pools (pairs) and also to keep track of them.</li><li>UniswapV2Pair.sol: This is where the action happens (the pool implementation).</li></ol><h4>Uniswap V2 Factory</h4><p>Again, the factory contract is mainly responsible for creating new contract pairs (UniswapV2Pair.sol). Here<a href="https://etherscan.io/address/0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f"> is the V2 factory contract on Etherscan</a>.</p><p>In order to concentrate liquidity, there can only be one smart contract per pair. In other words, if there is a WETH/UNI pair contract already, the factory won’t allow you to create the same pair. Of course, you can bypass that (by deploying the pair contract directly), but the core principle here is to concentrate liquidity as much as possible to avoid price slippage and have more liquidity.</p><p>Here is the function that creates pairs in UniswapV2Factory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*bINdbXGVdyl33xTQuQKZog.png" /></figure><p>One thing that’s probably still in question is, what determines the order of x and y?</p><p>The pairs are grouped by hexadecimal order, as you can see in line 25:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*93_xqfDaudwsomN0zf07Dg.png" /></figure><p>Line 27 checks that the pair is unique:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KFA1EAR-bBI85uJ96Ywkrw.png" /></figure><p>Lines 30–32 create the pair (UniswapV2Pair.sol) using create2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oN7q7igEXi8FIwitkxc08Q.png" /></figure><p>Then it initializes the contract with the address of each token and adds them to an array and mapping.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2YCYRFUV3rx7lQiT2ur53w.png" /></figure><p>Another important point is that the factory can turn on a fee to charge a percentage per swap (you can check that yourself; it is pretty trivial).</p><p>That’s it for the factory. It is a very simple and straightforward factory implementation, nothing complicated.</p><h4>Uniswap V2 Pair</h4><p>UniswapV2Pair.sol is the foundation of UniswapV2. Here<a href="https://github.com/Uniswap/v2-core/blob/master/contracts/UniswapV2Pair.sol"> is the contract.</a></p><p>This contract is responsible for handling unique pools (each pool = one contract).</p><p>The basic functionality of this contract is to swap, mint , and burn. We already went into detail as to how these components work, so we will just give them one quick brush.</p><p>Swap(): The swap function is the star of Uniswap. Every time you want to trade one token for another, the function gets called. You can see the full function implementation <a href="https://github.com/Uniswap/v2-core/blob/master/contracts/UniswapV2Pair.sol#L159">here</a>. The basic task of this function is to enforce that newK is greater than or equal to k:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*xPx6Rdy9EOGlYjievbUAwQ.png" /></figure><p>Mint(): The mint function is responsible for minting LP tokens every time a liquidity provider provides liquidity. You can find it <a href="https://github.com/Uniswap/v2-core/blob/master/contracts/UniswapV2Pair.sol#L110">here</a>.</p><p>Burn(): The burn function is responsible for burning LP tokens every time a liquidity provider wants to take his assets out of the pool. You can find it <a href="https://github.com/Uniswap/v2-core/blob/master/contracts/UniswapV2Pair.sol#L134">here</a>.</p><p>You made it!</p><p>You just learned how most automated market makers&#39; engine works!</p><h4>Note on Flash Loans</h4><p>Flash loans are a very important topic that we did not cover in this post. The reason why is that we are going to cover it in depth in the next post about AAVE.</p><p>Hopefully, you enjoyed it!</p><p>References:</p><iframe src="https://drive.google.com/viewerng/viewer?url=https%3A//uniswap.org/whitepaper.pdf&amp;embedded=true" width="600" height="780" frameborder="0" scrolling="no"><a href="https://medium.com/media/baddfd8e032920cefbf0558849a4e0fa/href">https://medium.com/media/baddfd8e032920cefbf0558849a4e0fa/href</a></iframe><p><a href="https://docs.uniswap.org/protocol/V2/concepts/protocol-overview/how-uniswap-works">How Uniswap works | Uniswap</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FIL7cRj5vzEU%3Fstart%3D438%26feature%3Doembed%26start%3D438&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DIL7cRj5vzEU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FIL7cRj5vzEU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b938f1c9d389e98ccd176a183c6a75e/href">https://medium.com/media/9b938f1c9d389e98ccd176a183c6a75e/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98075c826254" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/uniswap-v2-in-depth-98075c826254">A Deep Dive Into the Uniswap V2 Protocol</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Survive in the Ethereum Dark Forest]]></title>
            <link>https://medium.com/better-programming/how-to-survive-in-the-ethereum-dark-forest-f21c9eca4bfe?source=rss-25fc5577e294------2</link>
            <guid isPermaLink="false">https://medium.com/p/f21c9eca4bfe</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[web3]]></category>
            <dc:creator><![CDATA[Rodrigo Herrera I]]></dc:creator>
            <pubDate>Sat, 16 Apr 2022 14:00:04 GMT</pubDate>
            <atom:updated>2022-04-24T17:22:35.315Z</atom:updated>
            <content:encoded><![CDATA[<h4>Avoid a front-running bot from eating you</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*732aKxnO7AspAgBY3shpTQ.png" /><figcaption>Google images</figcaption></figure><p><a href="https://www.paradigm.xyz/2020/08/ethereum-is-a-dark-forest">Ethereum is a Dark Forest </a>is a term popularized in crypto by Dan and Georgios from paradigm (if you haven’t read the post, I highly recommend it).</p><p>But “The Dark Forest” <a href="https://en.wikipedia.org/wiki/The_Dark_Forest">is actually a science fiction book </a>that brings the concept of a dark forest. This concept basically means that if you are detected a predator will kill you.</p><h4><strong>Ok, so how does this relate to Ethereum?</strong></h4><p>To be more precise, this problem applies to almost all chains, but we will focus on Ethereum<a href="https://defillama.com/chains"> because it is the chain with the biggest TVL by far.</a></p><p>Following the dark forest analogy, the predators are bots searching for any opportunity there is to make a profit for themselves. Just keep in mind, that a lot of times (not always) the profit they make, is at the expense of the users.</p><p>The purpose of this post is to understand on a high level how this predator bots operate, and how to avoid them. In order to truly understand what is going on, we will take a first-principles approach and actually interact with one of this predator on the Ethereum Mainnet.</p><h4><strong><em>Prerequisites</em></strong></h4><p>You will fully grasp everything if you have the following skills, but you can also understand the overall idea if you don’t:</p><ol><li>General<strong> </strong>understanding of how the EVM works.</li><li>Solidity / JS.</li></ol><p>Before starting our journey, we need to understand a couple of concepts.</p><h3><strong>M.E.V</strong></h3><p>MEV is formerly known as <strong><em>Miner Extractable Value</em></strong> and more recently as <a href="https://ethereum.org/en/developers/docs/mev/#top"><strong><em>Maximal Extractable Value</em></strong></a> refers to the maximum value that can be extracted from block production in excess of the standard block reward and gas fees by including, excluding, and changing the order of transactions in a block.</p><p>Without going into too much detail, what MEV means, is the amount of money that a certain entity (miner, searcher, etc…) can extract by changing something about the transaction ordering.</p><p>This concept is going to be completely clear after we interact with the predator.</p><h3><strong>The Mempool</strong></h3><p><a href="https://www.blocknative.com/blog/mempool-intro">The Mempool refers to the set of in-memory data structures inside an Ethereum node that stores candidate transactions before they are mined.</a></p><p>What does this mean?</p><p>Think about for a second what happens behind the scenes when you send a transaction. What happens when you press send in your wallet?</p><p>The short answer is that you are entering the Dark Forest.</p><p>When you send a transaction, you are signing a bunch of data, usually an object that looks like this: <br><em>* There are more fields than the object shown, this is only to make it simple ..</em></p><pre>{<br> to: &quot;0x123.....,<br> value: 1000....., <br> data: &quot;0x123...,<br> gasPrice: 100....</pre><pre>}</pre><p>The moment that you press “send”, you are signing the transaction intent and your wallet provider is forwarding it to a node (usually running go-Ethereum).</p><p>The problem with this, is that your transaction is not immediately inside of the blockchain a.k.a “safe zone”, but on the PUBLIC<strong> </strong>Mempool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*blLAmGgO2GUXCnzG2yYoyA.png" /><figcaption><a href="https://www.blocknative.com/blog/mempool-intro">https://www.blocknative.com/blog/mempool-intro</a></figcaption></figure><p>That’s right, everyone can see all the pending transactions*. This has tremendous implications (as we will see).</p><p>Just for you to have an idea, at any given time, there are <a href="https://etherscan.io/txsPending">around 180,000 pending transactions on Ethereum</a> (waiting on the Mempool), and a block usually contains around 180 transactions.</p><p><em>*Unless we use a service like FlashBots (as we will).</em></p><h3><strong>The Predator</strong></h3><p>Ok, now that we have a general understanding of what MEV and the Mempool are, let’s see all of this in real action.</p><p>CAUTION: You should not do this unless you really know what you are doing !!!</p><p>For the sake of research, we will loose some ETH to the predator.</p><p>Let’s start!</p><p><strong>NOTE:</strong> The complete repo with all of the files can be found here: <a href="https://github.com/rodrigoherrerai/MEV-EXAMPLE">https://github.com/rodrigoherrerai/MEV-EXAMPLE</a></p><p>So the first thing we are going to do is deploying a super simple smart contract:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c9cfab5a19d3f6061d28cdfc4b51cfa/href">https://medium.com/media/2c9cfab5a19d3f6061d28cdfc4b51cfa/href</a></iframe><p>This contract can do 3 basic things:</p><ol><li>Receive ETH.</li><li>Transfer the contract’s balance to whoever calls the function.</li><li>Emits an event when someone calls the _transfer function.</li></ol><p>I will go ahead and deploy the contract. <a href="https://etherscan.io/tx/0x8e3c0b38c58d92415ecdb1ec4f6e3ebd012eb8005d566fe5414f9a6d6413e47a">Here is the transaction’s hash</a>, and <a href="https://etherscan.io/address/0xD4D6112c07420f413bdDE19b80E350CA013379c5#code">here is the contract.</a></p><p>Now that we have the contract up and running on Mainnet, we are going to send some ETH to it, <a href="https://etherscan.io/tx/0xc50ed258bba75a4d31a46b70bff20359a6be0c07a3308ca4e63b7835e16dd53e">here is transaction hash for 0.01 ETH</a>.</p><p>To better understand what is going to happen next, just imagine that you are searching for different contracts, and you encounter the contract that we just deployed.</p><p>While checking the code on Etherscan, it takes you 2 seconds to realise that the contract is completely vulnerable. You just need to call the _transfer() function and it will send you all the funds right ??</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e0-_bbiwhOLra39e3lLEdQ.png" /><figcaption>source code on Etherscan</figcaption></figure><p>To your surprise, the contract has some ETH!</p><p>Well here are the bad news, if you are not well aware of everything we just talked about, you are falling into a trap.</p><p>It is true that whoever calls the _transfer() function will receive the contract’s balance. The problem is to make sure that you are the first one to call it. And by that, I do not mean to hurry and just call the function as fast as possible.</p><h4><strong>So then, what is the problem?</strong></h4><p>As you remember from our previous explanation, before a transaction gets into the actual block, it goes through the public Mempool.</p><h4><strong>Are you ready to hear the truth?</strong></h4><p>Every time a user sends a transaction to the public Mempool, the transaction gets inspected by thousands* of bots to see if they can make a profit out of it. <a href="https://ethereum.org/en/developers/docs/mev/#top">There are different types of attacks</a>, discussing each one of them is out of the scope of this post. For our particular case, we are going to focus on generalized frontrunners. <br><em>*It can be more, it can be less, but the number is big.</em></p><p>Generalized frontrunners are basically bots that are observing the mempool, simulating each transaction, copying the potentially profitable transaction’s code, replacing addresses with the frontrunner&#39;s address, and running the transaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N_jd-harV0x7GJipWVqaDA.png" /></figure><p><strong>NOTE: </strong>The drawing can be a bit misleading, in reality, there is not one mempool, but each node has its own pending transactions. The overall point remains intact.</p><h3><strong>Ready, Set, Go</strong></h3><p>Time for reality.</p><p>We will try to call the _transfer() function from the smart contract that we deployed. If you have paid attention, you should know by now (at least in theory), that the transaction will be front-run by a bot.</p><h4><strong>Are you ready?</strong></h4><p>The script will basically listen for the contract’s “Transferred” event and whenever is called, it will let us know. And just after we trigger the listener, we will call the _transfer() function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c8802644c8e56f19052f2f1a4db5516/href">https://medium.com/media/6c8802644c8e56f19052f2f1a4db5516/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cKH_z9flHBjY5imfQHb_QA.png" /></figure><p><a href="https://etherscan.io/tx/0xecf142c95ed695e98b146de05b0a56f57b9d22661d0cfe8b8d992b3fb16d0583">Here is the transaction’ hash.</a></p><p>Funny enough, this is the name of the bot that front-run us:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*10uBP44unV798_mqfqmG0w.png" /></figure><h4><strong>How did this happen?</strong></h4><p>Well, pretty simple. The bot simulated our transaction while it was on the mempool, saw that it was profitable, and then execute it before us.</p><h3><strong>The Solution</strong></h3><p>Hopefully, by now you understand the severity of this.</p><p>The good news is that there is a solution.</p><p><a href="https://docs.flashbots.net/">The solution is FlashBots</a>. FlashBots has different tools and services, but for our particular use case, we are going to focus on <a href="https://docs.flashbots.net/flashbots-auction/searchers/quick-start">FlashBots Auction.</a></p><p>What FlashBots Auction does, is that it allows us to send private transactions to the miners. This means, that our transaction will not go through the public mempool. Therefore, the predators won’t eat us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*dokw_ExsfEYeB63CZ84R8Q.png" /></figure><p>Script:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c52eb6b8b3d85a13740b69291e65b11/href">https://medium.com/media/9c52eb6b8b3d85a13740b69291e65b11/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gaJVfkVVsxElDMDjSkKS9w.png" /></figure><p><a href="https://etherscan.io/tx/0xcba58d75c1abf9667f5ed69bdd77d56d657e4557a93dcbd725a8fc0bd888816b">Here is the transaction’ hash</a>.</p><p>The reason why the bot didn’t screw us this time, is because the bot did not know about the existence of our transaction.</p><h3><strong>Key Takeaways</strong></h3><p>Currently, base layers have a very adversarial environment. The only way to mitigate this is by developing secure systems and open-source projects like FlashBots.</p><p>You need to be very careful as a user to not fall into traps. But even more important, the responsibility really lies on the dapp and system developers.</p><p>Good luck out there!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f21c9eca4bfe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/how-to-survive-in-the-ethereum-dark-forest-f21c9eca4bfe">How to Survive in the Ethereum Dark Forest</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>