<?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 Ben Haslam on Medium]]></title>
        <description><![CDATA[Stories by Ben Haslam on Medium]]></description>
        <link>https://medium.com/@ben.haslam?source=rss-9de9b3b3045a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MZV0L9J1ZBnMoVcEfcBcZA.png</url>
            <title>Stories by Ben Haslam on Medium</title>
            <link>https://medium.com/@ben.haslam?source=rss-9de9b3b3045a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 04:07:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ben.haslam/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[How I made a Uniswap interface from scratch]]></title>
            <link>https://medium.com/clearmatics/how-i-made-a-uniswap-interface-from-scratch-b51e1027ca87?source=rss-9de9b3b3045a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b51e1027ca87</guid>
            <category><![CDATA[interfaces]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[uniswap]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[automated-market-maker]]></category>
            <dc:creator><![CDATA[Ben Haslam]]></dc:creator>
            <pubDate>Thu, 23 Sep 2021 14:05:29 GMT</pubDate>
            <atom:updated>2022-04-06T09:09:00.319Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intro</h3><p>With the goal of allowing users to easily make swaps between different coins and deploy or remove liquidity on the <a href="https://bakerloo.autonity.network/index.html">Autonity</a> network with a UI, rather than using scripts, I decided to make an interface for Uniswap contracts deployed on the network.</p><p>The <a href="https://app.uniswap.org/#/swap">official Uniswap interface</a> proved difficult to fork for the private network, due to its very expansive codebase and problems connecting to a wallet. As I wanted to have a smaller codebase that I understood top to bottom, I decided to write my own simpler application, with the help of my awesome intern <a href="https://github.com/MattFrench019">Matt</a>.</p><p>We used <a href="https://reactjs.org/">ReactJS</a> for the project, with the <a href="https://docs.ethers.io/v5/">EthersJS</a> module to connect to the blockchain via metamask in the browser, and <a href="https://material-ui.com/">Material-UI</a> for the frontend. As it was a static site, we used github pages to host the application.</p><p>This first blog describes the code for the swap part of the application. I’ll first go through the functions needed to connect and make calls and transactions with the Ethereum blockchain backend, and secondly explain the React frontend, which makes extensive use of React hooks and Material-UI. This is written with the expectation that the reader already has a good understanding of ReactJS, as well as a knowledge of how <a href="https://uniswap.org/blog/uniswap-v2/">Uniswap V2</a> automated market makers (AMMs) work (see this <a href="https://uniswap.org/blog/uniswap-v2/">article</a>). I won’t explain generic React components such as the NavBar, or the redirect page for when an Ethereum wallet can’t be found, as this blog will be long enough without that!</p><p>Checkout the <a href="https://ben-haslam.github.io/Alternative-Uniswap-Interface/">interface here</a>, and the raw code at the <a href="https://github.com/Ben-Haslam/Alternative-Uniswap-Interface">repo here</a>.</p><p><em>Please note, this blog describes the state of the interface as of </em><a href="https://github.com/Ben-Haslam/Alternative-Uniswap-Interface/tree/b70144647b93ac03843b630740f276bce3e1ef98"><em>this commit</em></a><em>. It has since been updated to have support for multiple networks, and displays different default coins depending on the network, as well as a few other small changes.</em></p><h3>Ethereum Functions</h3><h4>Connecting to the blockchain</h4><p>These functions are needed to connect to the blockchain via a wallet in the browser, to fetch information from the blockchain via calls, and to use contracts on the network to make swaps via transactions.</p><p>My original plan was to use the javascript module Web3 to connect to the blockchain with metamask in the browser, but metamask dropped support for it in January 2021, so I instead used EthersJS. EthersJS is a much smaller module than Web3, which means your application will load faster.</p><p>In the file ethereumFunctions.js, the first function is getProvider, which connects to the Ethereum provider (metamask or another wallet) in the browser, then the function getSigner, which is used to sign transactions. Using the EthersJS Contract class, are functions that return contract objects for the Router, Weth and Factory contracts that I had deployed onto the blockchain previously. For these the Contract class took the address, ABI of the deployed smart contract and the EthersJS signer as parameters.</p><p>Also defined is the function getAccount, which prompts the user to select accounts to use from the connected wallet.</p><p><em>ethereumFunctions.js</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e50653ee7b93fa71e4b69bc44af0fad/href">https://medium.com/media/8e50653ee7b93fa71e4b69bc44af0fad/href</a></iframe><p>These functions were all imported into the CoinSwapper/CoinSwapper.js file, and used to set their corresponding state variables using React.useState hooks, from line 70:</p><p><em>CoinSwapper/CoinSwapper.js</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/170524b33766de388d6255058a82a07e/href">https://medium.com/media/170524b33766de388d6255058a82a07e/href</a></iframe><h4>ERC20 token functions</h4><p>The next two functions in the ethereumFunctions.js file make calls to the network to fetch information on the token addresses chosen or provided by the user.</p><p>doesTokenExist does a check to make sure the address provided corresponds to a token deployed on the blockchain:</p><p><em>ethereumFunctions.js</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e74cafba64901e21f9da920f464efaa8/href">https://medium.com/media/e74cafba64901e21f9da920f464efaa8/href</a></iframe><p>getBalanceAndSymbol checks if a provided address is the address of the Weth contract on the blockchain, in which case it returns the AUT (the native coin of the Autonity blockchain, equivalent to ETH) balance of the user. Otherwise it returns the ERC20 token balance of the user, along with the symbol of the token:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ef975d913f734d12b35197370ccb1f9/href">https://medium.com/media/2ef975d913f734d12b35197370ccb1f9/href</a></iframe><p>This function checks if the address is the Weth address by comparing it to COINS.AUTONITY.address, an array of the default tokens exported from constants/coins.js.</p><h4>The swap function</h4><p>The swapTokens function in ethereumFunctions.js makes a transaction to the Router contract on the blockchain to perform one of three different swaps (AUT to token, token to AUT, token to token), depending on the token addresses provided to it, address1 and address2.</p><ul><li>If address1 is the address of the Weth contract, it calls the Router function swapExactETHForTokens</li><li>If address2 is the address of the Weth contract, it calls the Router function swapExactTokensForETH</li><li>If neither address1 or address2 is the address of the Weth contract, the swapTokens function calls the Router function swapExactTokensForTokens</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2a9e6ffb23bafe83fc074b000f8f5ff/href">https://medium.com/media/f2a9e6ffb23bafe83fc074b000f8f5ff/href</a></iframe><p>The function getAmountOut is used to get a preview of a swap. It calls the Router function getAmountsOut with the amount of the first token and an array of the addresses of the tokens to be swapped as parameters. It returns the amount out of the second token.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90d2d3f312f475b39f0ae58a2ea04d59/href">https://medium.com/media/90d2d3f312f475b39f0ae58a2ea04d59/href</a></iframe><h4>The reserves function</h4><p>Finally, the GetReserves function in ethereumFunctions.js returns the liquidity pool reserves for a given pair of tokens, as well as the liquidity token balance for the user. Internally this function calls another function fetchReserves, which fetches the reserves by making a call to the pair contract then making sure the reserves are returned in the right order.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13cfde30b26fe28f98c8ab6606f418e3/href">https://medium.com/media/13cfde30b26fe28f98c8ab6606f418e3/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c65b5482a491fd383b20c8b878ab79df/href">https://medium.com/media/c65b5482a491fd383b20c8b878ab79df/href</a></iframe><h3>React Frontend</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*76PX96wvUmybf9a_sUc4qA.png" /></figure><p>The frontend of the application makes extensive use of Material-UI components such as Grid, Container, Paper, Typography, as well as various buttons and more. Rather than explaining the workings of every component in the application, I will aim to give a high level overview, which will make the most sense if you are reading through the code at the same time. If you are not familiar with Material-UI I recommend reading up on some of their great documentation <a href="https://material-ui.com/">here</a>.</p><p>The file CoinSwapper.js exports a function CoinSwapper, which returns the React component used to select tokens and make swaps. This function itself makes use of some other custom React components, which I will explain first before going through the internal functions and hooks that make the CoinSwapper component work.</p><h4>Coin Dialog component</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V9Z7TBDm4bjKVUSBt00ibQ.png" /></figure><p>The CoinDialog component renders the menu of coins that opens upon clicking one of the ‘SELECT’ buttons. This extends the React Dialog component, which renders a window that opens in front of the rest of the app, used to ask for a decision. It is defined in CoinSwapper/CoinDialog.js</p><p>Inside the CoinDialog component, there is first a modified version of Material-UI&#39;s DialogTitle component, with the addition of a close button which on click calls the exit function that closes CoinDialog.</p><p>Next there is a React TextField component, which enables the user to paste the address of a token to be used. On change, this sets the state variable address to the user&#39;s input.</p><p>The next part is a mapping that maps each of the default tokens in Constants/coins to a custom CoinButton component (see below), that when clicked calls the exit function that closes CoinDialog returning the address of the selected tokens.</p><p>Finally, there is the Enter button, which on click calls the submit function, which checks a token exists with the address in the TextField with the Ethereum function doesTokenExist, before calling exit to close CoinDialog returning the address.</p><p><em>CoinSwapper/CoinDialog.js</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cefc27fdcaa4a201b85679d5bf5b9de/href">https://medium.com/media/2cefc27fdcaa4a201b85679d5bf5b9de/href</a></iframe><p>This component, as well as all the others, makes use of the Material-UI makeStyles function for the styling, a CSS in JS solution that is easy to use with other Material-UI components and allows for theme nesting and dynamic styles.</p><h4>Coin Button component</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UN-QsGu0fROVPhh0TqsPRA.png" /></figure><p>The CoinButton component, defined in CoinSwapper/CoinButton.js, extends the Material-UI ButtonBase component, which contains text of the token symbol (coinAbbr) and token name (coinName), which are passed in via props.</p><p><em>CoinSwapper/CoinButton.js</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab6b9d297038808db8db37246f8573ea/href">https://medium.com/media/ab6b9d297038808db8db37246f8573ea/href</a></iframe><h4>Coin Field component</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MNkx8QXk5JU8AFB3BB0KZw.png" /></figure><p>The CoinField component, defined in CoinSwapper/CoinField, renders the input bar with a &quot;SELECT&quot; button used to select each token and input an amount for swapping. The component is relatively simple and consists of Material-UI components Fab (floating action button) and InputBase (a text field), both wrapped in Grid components for spacing. The relative properties for the Fab and InputBase components are passed into the CoinField component via props.</p><p><em>CoinSwapper/CoinField.js</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48f6647826cc759a0fc43fab023b83d5/href">https://medium.com/media/48f6647826cc759a0fc43fab023b83d5/href</a></iframe><h4>Loading button</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j-wTCV6rPiSymhQNRpVzSw.png" /></figure><p>The LoadingButton component, defined in Components/LoadingButton.js, renders the ‘SWAP’ button on the bottom of the main CoinSwapper component. It extends the Material-UI Button component, so it will be disabled depending on the valid prop, and displays a spinning loading icon on click until the swap transaction is complete.</p><p><em>Components/LoadingButton.js</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fef7e63b5cb0c90271adf2578d60a370/href">https://medium.com/media/fef7e63b5cb0c90271adf2578d60a370/href</a></iframe><h3>Coin Swapper Function</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dqN-Wz9-XZGG6lijEPoJMw.png" /></figure><h4>The Return statement</h4><p>The main function of the application, CoinSwapper, in CoinSwapper/CoinSwapper.js returns a boxed in component that contains two CoinDialog components, which only open when one of two CoinField components is selected. Next there are Material-UI Typography components which display the balances and reserves of the two selected tokens.</p><p>Finally there is the LoadingButton component at the bottom, and a short instructional paragraph with a link to the AUT faucet.</p><p><em>CoinSwapper/CoinSwapper.js</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3aa3cfe299fb5ca2a61553a82052dedb/href">https://medium.com/media/3aa3cfe299fb5ca2a61553a82052dedb/href</a></iframe><p>When the LoadingButton is clicked, it calls the internal function swap (see below), which then calls the swapTokens Ethereum function with the state variables coin1.address, coin2.address and field1Value as arguments. This will first prompt the user to allow the spending of coin 1 with a metamask notification, then with another notification prompt the user to confirm the transaction. When that is done, the values in field1 and field2 will reset.</p><h4>State variables</h4><p>The return statement above references several state variables that keep track of the state of the application. These are:</p><ul><li>dialog1Open — Keeps a record of weather the first dialog window is open</li><li>dialog2Open — Keeps a record of weather the first dialog window is open</li><li>coin1 — array of address, symbol, balance for coin1</li><li>coin2 — array of address, symbol, balance for coin2</li><li>reserves — Stores the liquidity reserves in the pool for coin1 and coin2.</li><li>field1Value — Stores the user’s input in field1 (the value of coin1 to be swapped)</li><li>field2Value — Stores the user’s input in field2 (the value of coin2 to be swapped)</li><li>loading — boolean to control the loading button</li></ul><p>These are defined with React.useState hooks from line 83:</p><p><em>CoinSwapper/CoinSwapper.js</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca351e83a0fc1be859a7585f07acfccc/href">https://medium.com/media/ca351e83a0fc1be859a7585f07acfccc/href</a></iframe><p>These state variables are used in the following functions, and also used to display information to the user in the prior mentioned return statement.</p><h4>Internal functions</h4><p>Also referenced in the return statement above are several internal functions, these are:</p><ul><li>switchFields</li><li>handleChange</li><li>formatBalance</li><li>formatReserve</li><li>isButtonEnabled</li><li>onToken1Selected</li><li>onToken2Selected</li><li>swap</li></ul><p>switchFields switches the top and bottom coins. This is called when users hit the swap button or select the opposite token in the dialog (e.g. if coin1 is TokenA and the user selects TokenB when choosing coin2):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/343022e1bc6cd947fbc1c5a26130fb31/href">https://medium.com/media/343022e1bc6cd947fbc1c5a26130fb31/href</a></iframe><p>handleChange is a common internal function used in ReactJS, which takes an HTML event, pulls the data out, and puts it into a state variable. Here it used to set the field1 value when the value in the first coinFied changes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c70dea5e40d5499c65d9ce3588930cb9/href">https://medium.com/media/c70dea5e40d5499c65d9ce3588930cb9/href</a></iframe><p>formatBalance / formatReserveturn the account&#39;s balance / reserves into something nice and readable:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6d1dfc84378725a8a5904f439ced4c9/href">https://medium.com/media/d6d1dfc84378725a8a5904f439ced4c9/href</a></iframe><p>isButtonEnabled determines whether the button should be enabled or not:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00595556416779b93d31e47ee5ad5c98/href">https://medium.com/media/00595556416779b93d31e47ee5ad5c98/href</a></iframe><p>onToken1Selected / onToken2Selected are called when the dialog window for coin1 / coin2 exits, and sets the relevant state variables:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9032cfaa86d22830386b4a8318c1c62/href">https://medium.com/media/a9032cfaa86d22830386b4a8318c1c62/href</a></iframe><p>swap calls the swapTokens Ethereum function to make the swap, then resets necessary state variables:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eeddbe0dda2a0f8fc6a462aa258678ff/href">https://medium.com/media/eeddbe0dda2a0f8fc6a462aa258678ff/href</a></iframe><p>Line 16 in the swap function uses enqueueSnackbar, a component from the node module Notistack. Notistack is a great library for making temporary notifications. Check the repo <a href="https://github.com/iamhosseindhv/notistack">here</a>.</p><h4>useEffect hooks</h4><p>Finally, in CoinSwapper/CoinSwapper.js, there are four useEffect hooks, which are used to keep the application up to date with the latest changes. The lambda (code) within each hook is run when one of the dependencies changes. The dependencies are defined in the array of variables passed to the function after the lambda expression.</p><p>The first useEffect is called when either of the state variables coin1.address or coin2.address change. This means that when the user selects a different coin to convert between, or the coins are swapped, the new reserves will be calculated:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae871ce140615945e1505ded66abc102/href">https://medium.com/media/ae871ce140615945e1505ded66abc102/href</a></iframe><p>The second hook is called when any of the state variables field1Value coin1.address or coin2.address change. It attempts to calculate and set the state variable field2Value. This means that if the user enters a new value into the conversion box or the conversion rate changes, the value in the output box will change:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3c004738525cfdb5050dc738cfcf0de/href">https://medium.com/media/c3c004738525cfdb5050dc738cfcf0de/href</a></iframe><p>The third hook creates a timeout that will run every ~10 seconds, its role is to check if the user’s balance has updated and changed. This allows them to see when a transaction completes by looking at the balance output:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db0e61ee91348e3741e6057a3357e638/href">https://medium.com/media/db0e61ee91348e3741e6057a3357e638/href</a></iframe><p>The final hook will run when the component first mounts. It is used to set the account:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8096914522088739d5c7f7679d9572b7/href">https://medium.com/media/8096914522088739d5c7f7679d9572b7/href</a></iframe><h3>Conclusion</h3><p>The first section of this blog covered the Ethereum functions needed to make calls and transactions to the blockchain. The next section went through the custom components, internal functions and hooks needed to make the main swap functionality work.</p><p>I have yet to mention any of the remove/deploy liquidity functionality. That is the topic of the next blog, <a href="https://medium.com/@ben.haslam/uniswap-interface-liquidity-functionality-a048a0a7ed8e">here</a>.</p><p>To tip the author, you can use this ethereum address: 0xe7EeDB184E63Fe049EebA79EfeAc72939cB1461D</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b51e1027ca87" width="1" height="1" alt=""><hr><p><a href="https://medium.com/clearmatics/how-i-made-a-uniswap-interface-from-scratch-b51e1027ca87">How I made a Uniswap interface from scratch</a> was originally published in <a href="https://medium.com/clearmatics">clearmatics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uniswap Interface Liquidity functionality]]></title>
            <link>https://medium.com/@ben.haslam/uniswap-interface-liquidity-functionality-a048a0a7ed8e?source=rss-9de9b3b3045a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a048a0a7ed8e</guid>
            <category><![CDATA[uniswap]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[automated-market-maker]]></category>
            <category><![CDATA[liquidity-pool]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Ben Haslam]]></dc:creator>
            <pubDate>Fri, 10 Sep 2021 10:56:07 GMT</pubDate>
            <atom:updated>2022-02-10T17:42:11.795Z</atom:updated>
            <content:encoded><![CDATA[<p>In the first part of this blog, I explained the Ethereum functions and frontend code for the swap page of the application. If you have not read the first blog, find it <a href="https://medium.com/clearmatics/how-i-made-a-uniswap-interface-from-scratch-b51e1027ca87">here</a>.</p><p>For the page to add or remove liquidity, we kept the same design language as the swap page, so again used <a href="https://reactjs.org/">ReactJS</a>, <a href="https://docs.ethers.io/v5/">EthersJS</a> and <a href="https://material-ui.com/">Material-UI</a>.</p><p>In this blog, I will keep the structure the same, first going through the functions needed to connect to the Ethereum blockchain backend, and then the ReactJS frontend. As the add/remove liquidity page of the application shares many functions and components with the swap page that were already described in the last blog, I will not explain them in detail here. Again, this blog is written with the expectation that the reader already has a good understanding of ReactJS, as well as a knowledge of how <a href="https://uniswap.org/blog/uniswap-v2/">Uniswap V2</a> automated market makers (AMMs) work.</p><p>Checkout the <a href="https://ben-haslam.github.io/Alternative-Uniswap-Interface/">interface here</a>, and the raw code at the <a href="https://github.com/Ben-Haslam/Alternative-Uniswap-Interface/tree/b70144647b93ac03843b630740f276bce3e1ef98">repo here</a>.</p><h3>Ethereum Functions</h3><h4>Connecting to the blockchain</h4><p>The functions needed to initially connect to the blockchain and instigate contract objects for the liquidity page are exactly the same as those needed for the swap page, defined in the same file ethereumFunctions.js .</p><p><em>ethereumFunctions.js</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e50653ee7b93fa71e4b69bc44af0fad/href">https://medium.com/media/8e50653ee7b93fa71e4b69bc44af0fad/href</a></iframe><p>These functions were all imported into the LiquidityDeployer/LiquidityDeployer.js file, and used to set their corresponding state variables using React.useState hooks, from line 64:</p><p><em>LiquidityDeployer/LiquidityDeployer.js</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/170524b33766de388d6255058a82a07e/href">https://medium.com/media/170524b33766de388d6255058a82a07e/href</a></iframe><p>The Ethereum functions doesTokenExist , getBalanceAndSymbol , fetchReserves and GetReserves are all used in the liquidity page the same way they are used in the swap page as described in the previous blog.</p><h4>Add Liquidity</h4><p>The Ethereum functions specific for the liquidity page are defined in the LiquidityDeployer/LiquidityFunctions.js file. The addLiquidity function has a similar layout to the swapTokens function described in the previous blog. It approves the router to spend given amounts for the contracts of the two provided addresses, then makes a transaction to the router contract on the blockchain to perform one of three different liquidity additions (AUT + token, token + AUT, token + token), depending on the pair of addresses provided to it, address1 and address2:</p><p><em>LiquidityDeployer/LiquidityFunctions.js</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8096914522088739d5c7f7679d9572b7/href">https://medium.com/media/8096914522088739d5c7f7679d9572b7/href</a></iframe><h4>Remove liquidity</h4><p>The next Ethereum function in LiquidityDeployer/LiquidityFunctions.js is removeLiquidity. First it approves the router to spend the given amount for the pair contract of the two provided addresses (as the pair contract itself is ERC20 compatible, and is used to hold the liquidity pool tokens). It then makes a transaction to the router contract on the blockchain to perform one of three different liquidity removals (AUT + token, token + AUT, token + token), depending on the pair of addresses provided to it, address1 and address2 :</p><p><em>LiquidityDeployer/LiquidityFunctions.js</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8096914522088739d5c7f7679d9572b7/href">https://medium.com/media/8096914522088739d5c7f7679d9572b7/href</a></iframe><h4>Add liquidity quote</h4><p>One necessary feature of the liquidity page was that the user would see a preview of adding the liquidity before actually doing it. I initially wanted to do this with static calls, but these make the application cumbersome, and the Ethers.js method of doing static calls seemed to have some bugs at the time of writing. Instead, I went through the smart contracts and found a way to do it analytically, so the preview would update automatically as the user changes the input values, without having to wait for a static call.</p><p>To add liquidity, the user chooses the tokens then inputs the desired values of each token to be added to the liquidity pool. The amount of each token that is actually added has to match the ratio of the reserves already in the pool, so the maximum possible amount of both tokens is first found using equation 1:</p><p><em>Ain = Input of coin A</em></p><p><em>Bin = Optimum input of coin B</em></p><p><em>Ra = Reserves of coin A</em></p><p><em>Rb = Reserves of coin B</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*5vEmY3-reHmzqf3ggeZNBg.png" /><figcaption>Equation 1</figcaption></figure><p>This is calculated for first using the input for coin A as amount1. If the output amount2 is larger than the input for coin B, then the input for coin B is instead used to set the amounts of liquidity added.</p><p>The amount of liquidity tokens created for the user is given by the geometric mean of the inputs of A and B:</p><p><em>Lout = Liquidity tokens out</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*NKqym3bKg0BSKFASBgMPQg.png" /><figcaption>Equation 2</figcaption></figure><p>The code for this is defined in the function quoteAddLiquidity, which uses the internal function quote:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aff8184b6951de9f2de46544fc4969c5/href">https://medium.com/media/aff8184b6951de9f2de46544fc4969c5/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8096914522088739d5c7f7679d9572b7/href">https://medium.com/media/8096914522088739d5c7f7679d9572b7/href</a></iframe><h4>Remove Liquidity Quote</h4><p>Another requirement was a preview for removing liquidity. Again, rather than implementing a static call, I decided to produce the preview analytically, by writing functions that replicate the mathematical operations that take place in the smart contracts on chain.</p><p>There are actually two different scenarios for this situation, depending on whether the factory contract used to make the liquidity pool (pair contract) for the two coins has the protocol fee turned on or not. I will go through the mathematics of both scenarios, starting with fee off.</p><p><strong><em>Removing liquidity with the protocol fee off</em></strong></p><p><em>T = Liquidity Tokens Total Supply</em></p><p><em>Lin = Liquidity Tokens In</em></p><p><em>Ra = Reserves of coin A</em></p><p><em>Rb = Reserves of coin B</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*99LdI7UbxL9NFyOXb133BQ.png" /><figcaption>Equation 3</figcaption></figure><p>It is tempting to think that the <em>Liquidity Tokens Total Supply (T) </em>should be equal to the geometric mean of the all the reserves, given equation 2. This is not actually the case, as the ratio of the reserves <em>Ra/Rb</em> shifts with every swap, meaning the total supply T is usually slightly offset from the geometric mean of reserves. This is only not the case if there have been no swaps, or if all the swaps effectively cancel out.</p><p><strong><em>Removing liquidity with the protocol fee on</em></strong></p><p>All trades made with Uniswap V2 contracts have a 0.3% fee that is added to the liquidity pool, allowing the liquidity providers to make profit when they remove liquidity. With the protocol fee on, 1/6 of the fees go to a specific address, and the accumulated fees are collected only when liquidity is deposited or withdrawn. A derivation can be found in section 2.4 of the <a href="https://uniswap.org/whitepaper.pdf">Uniswap V2 whitepaper</a>, but the resultant equations are shown below:</p><p><em>F = Protocol Fee Liquidity</em></p><p><em>Klast = reserve0 * reserve1, as of the most recent liquidity event (liquidity added or removed)</em></p><p><em>T = Liquidity Tokens Total Supply</em></p><p><em>Lin = Liquidity Tokens In</em></p><p><em>Ra = Reserves of coin A</em></p><p><em>Rb = Reserves of coin B</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*E-WFIz35Nl-6GmKZNB83ow.png" /><figcaption>Equation 4</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*9coK-8H27-2WCf06w67Qig.png" /><figcaption>Equation 5</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*TV5u42XmOcXgJaENyhrZyA.png" /><figcaption>Equation 6</figcaption></figure><p><strong><em>The code</em></strong></p><p>The code for all this is defined in the function quoteRemoveLiquidity , in the file LiquidityDeployer/LiquidityFunctions.js . It does a check to see if the protocol fee is turned on, if so it finds the protocol fee liquidity and modifies the Total Supply (equations 4 &amp; 5). Finally, it calculates the output using equation 3.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd2c749f53f4136c49936883954f66c3/href">https://medium.com/media/bd2c749f53f4136c49936883954f66c3/href</a></iframe><h3>React Frontend</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*zYiFKPbW7kbcTeS9aWZlFA.png" /></figure><p>The frontend of this application mostly makes use of the same custom components described in the last blog so I wont go over them. It also makes extensive use of Material-UI components such as Grid, Container, Paper andTypography , among others.</p><p>The main component of the liquidity page is described in the file Liquidity/Liquidity.js, which returns the React component used to add or remove liquidity pictured above. This component uses three custom components:</p><ul><li>SwitchButton</li><li>LiquidityDeployer</li><li>LiquidityRemover</li></ul><p>The component SwitchButtonis a custom button element, which is used to set a boolean value deploy to either true or false.</p><p>The main Liquidity component then contains an internal function deploy_or_remove , which returns either the LiquidityDeployer component or the LiquidityRemover component, depending on the boolean value deploy. This allows the user to switch the main component between deploying liquidity and removing liquidity with the button group at the top.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f219b4c96f8f7b9c8981d8c6725438a/href">https://medium.com/media/4f219b4c96f8f7b9c8981d8c6725438a/href</a></iframe><h4>Switch Button Component</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*Nu7pfIhN8-jPLKM0f6MHmA.png" /></figure><p>The switch button component composed of a Material-UI ButtonGroup component, itself containing the two Button components. On click, each of these call an internal function changeStyles , which sets the clicked button’s colour to red, and the other one to grey. The also each set the deploy boolean on click, via the setDeploy function which is passed into the SwitchButton component with props.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f41cac85fba12adc03863aafa47f26fd/href">https://medium.com/media/f41cac85fba12adc03863aafa47f26fd/href</a></iframe><h4>Liquidity Deployer Component</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*Jd1SJl8hz93v-jutREu36Q.png" /></figure><p>The frontend code for the LiquidityDeployer component is very similar to that of the CoinSwapper component described in the last blog, so I will only explain the new key features that set it apart.</p><p><em>Liquidity/LiquidityDeployer.js</em></p><p><strong>State variables</strong></p><p>There are two new state variables that the LiquidityDeployer component has in comparison to the CoinSwapper component:</p><ul><li>liquidityTokens — Stores the user’s balance of liquidity tokens</li><li>liquidityOut — Used when getting a quote for adding liquidity</li></ul><p>These are defined from line 104:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fcede7306a226bab319858248d6f616d/href">https://medium.com/media/fcede7306a226bab319858248d6f616d/href</a></iframe><p><strong>Deploy function</strong></p><p>The LiquidityDeployer component has the same internal functions as the CoinSwapper component, except that rather than the swap internal function, it has a function called deploy, for deploying liquidity.</p><p>The deploy function first disables the LoadingButton, then calls the Ethereum function addLiquidity, passing in the addresses of the two selected coins and the input values in field1 and field2.</p><p>If the transaction was successful, then the LoadingButton is enabled, field1 and field2 are cleared and a success message is rendered using <a href="https://github.com/iamhosseindhv/notistack">notistack</a> (enqueueSnackbar). Otherwise, a failure message is sent instead.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d29e52fd94758fbb8c384ccc5a2f7a5f/href">https://medium.com/media/d29e52fd94758fbb8c384ccc5a2f7a5f/href</a></iframe><p><strong>UseEffect hook</strong></p><p>All the UseEffect hooks in the LiquidityDeployer component are the same as those in the CoinSwapper component, except instead of the second one. Rather than calling the Ethereum function getReserves to give a preview of a swap, it instead calls the Ethereum function quoteAddLiquidity , with the selected coin addresses and both field values.</p><p>It uses the result to set the state variable liquidity_out , giving a preview of the liquidity deployment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f240231095bfb00752ef291cf94d1ea/href">https://medium.com/media/8f240231095bfb00752ef291cf94d1ea/href</a></iframe><h4>The return statement</h4><p>The code in the return statement for the LiquidityDeployer component is very similar to that of the CoinSwapper component, so I won’t go through it all here.</p><p>A few things to note is that the return statement contains an extra Material-UI paper component, which displays the liquidity_out state variable, which is an array of the inputs of coin one and coin two, as well as the liquidity tokens out.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b5b649cc82356afeb8f7ba241e5773f/href">https://medium.com/media/1b5b649cc82356afeb8f7ba241e5773f/href</a></iframe><p>This renders the preview of the liquidity deposit, in the red box:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*CM_d0vWUg85Ce0qPZbY-Cw.png" /></figure><h4>Liquidity Remover component</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*Bf0mwtmTIeACDmXv-3npaw.png" /></figure><p>The LiquidityRemover Component is presented to the user upon clicking the ‘REMOVE LIQUIDITY’ button. The code for this component is mostly the same as that for the LiquidityDeployer component, save for a few modifications I’ll briefly go through.</p><p><strong>Remove Liquidity Fields</strong></p><p>The most obvious change is in the two input fields. Instead of using the component CoinField, as described in the previous blog, the LiquidityRemover component uses two modified versions of it. RemoveLiquidityField1 and RemoveLiquidityField2 are both defined in the file Coinswapper/CoinField.js .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*NTu2ttLfIGQgefXIE4Hibg.png" /></figure><p>RemoveLiquidityField1 is essentially the same as CoinField , except the text input is more separate from the button. This is so it is clear to the user that their input is for the liquidity pool tokens to be removed, rather than for the first coin.</p><p>RemoveLiquidityField2 removes the text input entirely, as only one text input is needed for the remove liquidity functionality.</p><p><strong>Other Changes</strong></p><p>The other changes are trivial, essentially swapping the add liquidity functionality for remove liquidity functionality.</p><ul><li>Rather than the new state variable liquidityOut , the LiquidityRemover component has the state variable tokensOut, used to store the input and output for the liquidity removal preview:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec38f42059b651665c84afdf09335d7e/href">https://medium.com/media/ec38f42059b651665c84afdf09335d7e/href</a></iframe><ul><li>Instead of the internal function deploy, the LiquidityRemover component has the internal function remove, which calls the removeLiquidity Ethereum function:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3acb3657183e54298b6b455d9ce62e29/href">https://medium.com/media/3acb3657183e54298b6b455d9ce62e29/href</a></iframe><ul><li>Rather than giving an preview of liquidity deployment, the second useEffect hook is used to give a preview of liquidity removal, by calling the Ethereum function quoteRemoveLiquidity:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57ef5a4b87372d26036bce65e809831a/href">https://medium.com/media/57ef5a4b87372d26036bce65e809831a/href</a></iframe><ul><li>The return statement has some trivial changes, displaying the state variable tokensOut rather than liquidityOut , to give a preview of the liquidity removal in the red box.</li></ul><h3>Conclusion</h3><p>That covers the code and equations needed to make the remove/deploy of liquidity functionality work. The first blog was on the swap functionality, and went much further into the React frontend, you can read that <a href="https://medium.com/@ben.haslam/how-i-made-a-uniswap-interface-from-scratch-29ae176210fc">here</a>.</p><p>This interface now provides a simple alternative to the official Uniswap interface for the the <a href="https://bakerloo.autonity.network/index.html">Autonity</a> network, but there is still some room for improvement.</p><p>The main improvement to note is that this interface is for Uniswap V2 contracts, not Uniswap V3. To upgrade to Uniswap V3, many of the Ethereum functions would have to be completely rewritten, especially those for deploying/removing liquidity. The reason I did not initially use Uniswap V3 for the Autonity network is because, unlike V2, the <a href="https://www.coindesk.com/tech/2021/03/23/uniswap-v3-introduces-new-license-to-spoil-future-sushis/">Uniswap V3 core licence prohibits the copying of the code</a> for two years.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a048a0a7ed8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>