<?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 Simeon Campbell on Medium]]></title>
        <description><![CDATA[Stories by Simeon Campbell on Medium]]></description>
        <link>https://medium.com/@simeon.h.campbell?source=rss-4ee435f783c4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*PomAepFsNYvKXnNR</url>
            <title>Stories by Simeon Campbell on Medium</title>
            <link>https://medium.com/@simeon.h.campbell?source=rss-4ee435f783c4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 10:25:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@simeon.h.campbell/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[Uniswap V3 - A Deep Dive: Using Inheritance and Interfaces to Produce Re-usable Smart-Contract…]]></title>
            <link>https://coinsbench.com/uniswap-v3-a-deep-dive-using-inheritance-and-interfaces-to-produce-re-usable-smart-contract-855c5bb83602?source=rss-4ee435f783c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/855c5bb83602</guid>
            <category><![CDATA[uniswap]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[defi]]></category>
            <dc:creator><![CDATA[Simeon Campbell]]></dc:creator>
            <pubDate>Sat, 27 Jul 2024 07:44:44 GMT</pubDate>
            <atom:updated>2024-07-29T12:54:43.998Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Uniswap V3 - A Deep Dive: Using </strong>Inheritance and <strong>Interfaces to Produce Re-usable Smart-Contract Libraries</strong></h3><figure><img alt="A futuristic digital illustration featuring a 3D unicorn head, symbolizing Uniswap, with “V3” prominently displayed. Surrounding the unicorn are holographic elements depicting smart contract code, charts, and blockchain symbols, emphasizing the themes of interfaces, inheritance, and re-usable smart contract libraries in Uniswap V3. The image conveys advanced technology and innovation, fitting for the article." src="https://cdn-images-1.medium.com/max/1024/1*4Yp63w9BiEuOTbaeeD_8Fg.png" /></figure><p>Here we will explore one of the most influential smart contract protocols, in crypto, since the start of the DeFi movement: Uniswap V3.</p><p>The aim is to explore how the protocol uses inheritance and interfaces to provide re-usable smart-contract libraries. And why, implementing reusable libraries, like openZeppelin or Uniswap, is a no-brainer when deploying code on-chain.</p><p>We begin our journey traveling through the history of Defi and all versions of Uniswap leading up to V3. Followed by a breakdown of the Uniswap V3 protocol and its architecture. We will then look at what reusable smart contract libraries are. Before diving deeper, we will look at what inheritance’s and interface’s roles in re-usable smart contract libraries are. As well as looking at real world example, in the form of a flashswap arbitrage trading bot. Before finally, discussing the benefits the protocol brings, along with the challenges Uniswap and the crypto Industry at large face.</p><p>So get comfortable, we will begin with a brief history of DeFi, leading up to Uniswap V3.</p><h3>“Defi” : The Beginning of a Financial Revolution</h3><p>In August 2018, a group of developers and entrepreneurs were trying to come up with a name for a group of decentralized financial applications being developed by themselves and a small group of others. It is believed by many that it was from this that the term “DeFi” was born. Short for decentralized finance and spoken as “defy”, made it the perfect term for the revolutionary applications meant to defy the traditional banking industry. [11]</p><p>An early key Dapp to be released into the Defi ecosystem was MakerDao. The <a href="https://makerdao.com/en/whitepaper/sai/#overview-of-the-dai-stablecoin-system">original whitepaper</a> was released in December 2017.</p><blockquote>We believe that stable digital assets like Dai are essential to realizing the full potential of blockchain technology. Unlike other Stablecoins, Dai is completely decentralized [5]</blockquote><p>MakerDao allowed anybody to put their Ethereum up as collateral and receive the decentralized stablecoin Dai (Originally Sai) In return.</p><blockquote>it can be freely sent to others, used as payments for goods and services, or held as long-term savings. Importantly, the generation of Dai also creates the components needed for a robust decentralized lending platform. [5]</blockquote><p>After MakerDao came a plethora of others. For example, Compound introduced the concept of ‘yield farming’ or ‘liquidity mining’. Here anybody could provide liquidity to lending pools or pools for token swaps and receive a relative share of rewards for doing so.</p><p>Before DeFi, these types of complex financial instruments were only available to people working in the financial sector and usually had a high financial barrier to entry. Now anybody could put their money to work. They just had to learn how to operate an Ethereum wallet.</p><h3>The Evolution of Uniswap and the Automatic Market Maker</h3><p>The idea of the automatic market maker is widely believed to be first theorized by Vitalik Buterin, in a famous reddit post: “Let’s run on-chain decentralized exchanges the way we run prediction markets”.</p><blockquote>The mechanism would look something like this. The market contains an internal state, PRICE, which is the current market price. It would also have two parameters, FEE, and DEPTH. If a user wants to buy ORDER_AMOUNT coins, they would raise the price to PRICE + ORDER_AMOUNT / DEPTH, and pay ORDER_AMOUNT * (PRICE + ORDER_AMOUNT / DEPTH / 2) * (1 + FEE). Essentially, this constitutes buying an infinitesimal number of coins at every price point between the old price and the new price. [4]</blockquote><p>Hayden Adams, Uniswap’s founder and inventor, was the first to successfully put the theory into practice, creating the first working mechanism for the automated market maker.</p><blockquote>Most exchanges maintain an order book and facilitate matches between buyers and sellers. Uniswap smart contracts hold liquidity reserves of various tokens, and trades are executed directly against these reserves. Prices are set automatically using the <strong>constant product (x*y=k) market maker mechanism</strong>, which keeps overall reserves in relative equilibrium. Reserves are pooled between a network of liquidity providers who supply the system with tokens in exchange for a proportional share of transaction fees. [1]</blockquote><p>The role of the automated market maker, is like that of a market maker in the traditional sense, to keep the market liquid. A traditional market maker would carry out trades on their own exchange, using their own money. However, with Uniswap’s automated market maker, liquidity is provided by users.</p><blockquote>The prices of tokens in a pool are determined by the supply of the tokens, that is by <strong>the amounts of reserves of the tokens</strong> that the pool is holding. Token prices are simply relations of reserves:</blockquote><blockquote>Px ​= x/y ​, Py ​= y/x​</blockquote><blockquote>Where <em>Px</em>​ and <em>Py</em>​ are prices of tokens in terms of the other token.​ [7]</blockquote><p>For example:</p><p>in a UNI/USDT pool token x would be UNI and token y would be USDT. Say UNI is 10 dollars on an arbitrary date.</p><p>So..</p><p>Px is the price of Uni = 10/1 or 10 USDT</p><p>Py is the price of Usdt = 1/10 or 0.1 UNI</p><h3><strong>Uniswap V1</strong></h3><p>First launched in November 2018, Uniswap quickly gained a firm foothold as one of the most used protocols in the DeFi ecosystem. Anybody could swap Ethereum tokens directly and securely, without a centralized intermediary. In addition, any user could create an ETH/ERC-20 token pool through the factory contract, if one did not already exist. Then, anybody could provide liquidity and earn a relative percentage of the swap fees.</p><h3>Uniswap V2</h3><p>The second version of Uniswap was released in May of 2020. It brought with it the necessary improvements to keep Uniswap in a commanding position as one the leading innovators in the space.</p><h4>ERC20/ERC20 Pairs</h4><p>One of the key features were direct ERC-20/ERC-20 trades. Users could now create pools between any pair of ERC-20 tokens, which allowed a far wider range of trading pairs.</p><h4>Flashswaps</h4><p>Another intriguing addition, was ‘flashswaps’. A flashswap “<em>allows a user to receive and use an asset before paying for it, as long as they make the payment within the same atomic transaction</em>” [2]. Flashswaps allow users to profit from price discrepancies on different pools without having any up-front capital. Furthermore, this incentivizes people to keep prices consistent and stable, because if the price on one pair went far off from another, any code-savvy arbitrager can snap up the opportunity and keep the profit.</p><h4>UNI Governance Token</h4><p>One more notable event, during the V2 era, was the distribution of Uniswap’s UNI governance token. The aim was to de-centralize ownership of the protocol across the entire community. Everyone that held the UNI token had the right to vote on any matters regarding the Uniswap protocol.</p><blockquote>A community-managed treasury opens up a world of infinite possibilities. We hope to see a variety of experimentation, including ecosystem grants and public goods funding, both of which can foster additional Uniswap ecosystem growth. Uniswap has set the standard for automated liquidity provision: it is now time to set the benchmark for responsible but radical, long-term aligned on-chain governance systems. [8]</blockquote><p>The token was airdropped to any wallet that had interacted with the uniswap protocol, before the snapshot on September 1st 2020. All eligible wallets received 400 UNI tokens for free, which was around 1400 usd at the time of the airdrop. Liquidity providers, also got an extra share of the total supply. If anybody timed the market well enough, they could have sold theirs for around 17,000 dollars!</p><h3>Summary of key features</h3><p><strong>Uniswap V1</strong></p><ul><li>The successful implementation of the automated market maker (AMM)</li><li>ERC-20 to ERC-20 trades (although you would still have to trade between 2 pools)</li><li>Highly gas-efficient swaps</li></ul><p><strong>Uniswap V2</strong></p><ul><li>Direct ERC-20/ERC-20 trades</li><li>Flashswaps</li><li>Improved price oracles</li></ul><p><strong>Uniswap V3</strong></p><ul><li>Concentrated liquidity</li><li>Range Orders</li><li>Multiple fee tiers</li><li>Non-Fungible liquidity</li><li>Governance and Oracle upgrades</li></ul><h3>An overview of Uniswap V3</h3><p>Uniswap V3 was deployed in May 2021. It brought with it a host of new innovations, which allowed for more varied and efficient use of liquidity, as well as more accurate and stable pricing.</p><h4>Concentrated Liquidity</h4><p>The first and probably the most significant was concentrated liquidity, a radical new way to greatly increase the efficiency in which liquidity could be put to work.</p><p>In Uniswap V2, any liquidity provided was equally spread across the entire spectrum from 0 to infinity. With concentrated liquidity however, “<em>Liquidity providers (LPs) are given the ability to concentrate their liquidity by “bounding” it within an arbitrary price range.</em>” [3] Therefore the total range of liquidity would stretch between the price points that market participants deem worthwhile or likely to be hit, making it work closer to a centralized exchange order book.</p><p>Below is the liquidity chart of the USDC/ETH 0.05% fee pool.</p><figure><img alt="A graph showing the concentrated liquidity for the USDC/ETH pool in Uniswap V3. The graph highlights the active tick range, with price ranges marked in green ($1900 — $2200), white (ETH Price: $3087), and red ($3250 — $4100). The chart also shows the exchange rates of 1 USDC = 0.0003236 WETH and 1 WETH = 3090.23 USDC, demonstrating how liquidity is distributed within specific price ranges." src="https://cdn-images-1.medium.com/max/1024/1*_Qq2PJKtQnU8m8ln6BX9-g.png" /><figcaption>Fig 1: Uniswap V3 USDC/WETH 0.05% Pool. Source: https://app.uniswap.org/explore/pools</figcaption></figure><p>As you can see in the chart, liquidity is distributed in larger chunks at specific price points. Some are around the current price. These would be getting a far larger share of the fees than would be possible in V2.</p><p>Furthermore, this reduces potential <strong>slippage </strong>and greatly increases the order size a trade can absorb. We will look at <a href="https://app.uniswap.org/explore/pools/ethereum/0x88e6A0c2dDD26FEEb64F039a2c41296FcB3f5640">the pool above</a> as an example. We can zoom in on the specific ticks and how much of whichever token they hold. The Average tick range is the tick where the price at which the pool is now trading. We can work out how much ETH it would take to move price 1%. On the 0.05% pool above, we would need to absorb all the ETH for 10 ticks in total, which in this case around 2400 ETH. At time of writing this would mean that roughly 840,000 USDC would need to spend to move the price up by 1%.</p><p>Outside of the range around the current price, you can also see large chunks of liquidity around significant upper and lower price targets. These large pockets are likely ‘range orders’, which we will come to next.</p><h4>Range Orders</h4><p>The range order, similar to a limit order on a centralized exchange, with some key differences:</p><blockquote>- There is a limit to how narrow a position’s range can be. While the price is within that range, the limit order might be partially executed.</blockquote><blockquote>- When the position has been crossed, it needs to be withdrawn. If it is not, and the price crosses back across that range, the position will be traded back, effectively reversing the trade. [3]</blockquote><figure><img alt="A diagram illustrating range orders in Uniswap V3. The left side shows a liquidity position with 0% DAI and 100% ETH, where the market price is below the LP range ($1500 vs. $1600-$1601 DAI/ETH). The right side depicts a liquidity position with 100% DAI and 0% ETH, where the market price is within the LP range ($1650 vs. $1600-$1601 DAI/ETH). This visual explains how liquidity is allocated within specific price ranges in Uniswap V3." src="https://cdn-images-1.medium.com/max/993/1*0f5F_54VgkTCOJaByeQ4_g.png" /><figcaption>Fig 2. Uniswap V3 Range orders. Source: https://docs.uniswap.org/concepts/protocol/range-orders</figcaption></figure><p>With range orders, you only provide 1 token as liquidity. Say you wanted to sell your ETH for 3500 USDT. First you would provide the liquidity in a tight range, say between 3500–3501. Then once the price crosses 3501, all your ETH will have been converted into USDT. Furthermore, you will have earned fees, rather than paying the fees to a centralized exchange. However, you must withdraw the liquidity, before the price falls back below. Or else, the liquidity will be converted back to ETH.</p><h4>Multiple Fee Tiers</h4><p>Uniswap V3 also introduced multiple fee tiers. At launch the fees ranged from 0.05%, 0.3% or 1%.</p><blockquote>All pools are created by the same factory contract. The factory contract initially allows pools to be created at three fee tiers: 0.05%, 0.30%, and 1%. Additional fee tiers can be enabled by UNI governance. [3]</blockquote><p>The main idea to split into different fee tiers was to satisfy different types of assets. For example, users of a low-volatility asset like a stablecoin, “<em>will likely congregate in the lowest fee tier, as the price risk for liquidity providers holding these assets is very low, and those swapping will be motivated to pursue an execution price closest to 1:1 as they can get.</em>” [9]</p><p>Whereas providers of highly volatile or rarely traded assets could be expected to “<em>naturally gravitate towards a higher fee — as liquidity providers will be motivated to offset the cost risk of holding these assets for the duration of their position.</em>” [9]</p><h4>Non-Fungible Liquidity</h4><p>In V2, any fees earned would be re-invested back into the pool, meaning it would grow over time. Each LP would get their relative share of the entire pool. “<em>In Uniswap v1 and v2, the pool contract is also an ERC-20 token contract, whose tokens represent liquidity held in the pool.” [3]</em></p><blockquote>In Uniswap v3, due to the non-fungible nature of positions, this is no longer possible. Instead, fee earnings are stored separately and held as the tokens in which the fees are paid. [3]</blockquote><p>This separation of fees, stops the compounding of fees over time. However, it allows LPs to manage their fee earnings separatly from their liquidity positions, providing more flexibility and control over positions.`</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*V9-hrq3sbIFsJg11JlgFdA.png" /><figcaption>Fig 3: Uniswap V3 USDC/WETH 0.05% Pool. Source: https://app.uniswap.org/explore/pools</figcaption></figure><p>The image above shows the liquidity sitting at 1 tick. In this case at the price tick of 3071.75 USDC. There is a total of 159,000 USDC at this price point. There could be several different liquidity positions, all adding to the total liquidity held at this price point (also known as a tick).</p><h4>Governance</h4><p>UNI governance allows for the community to add flexible fee tiers and change the owner of the factory contract.</p><blockquote>In Uniswap v3, UNI governance has more flexibility in choosing the fraction of swap fees that go to the protocol, and is able to choose any fraction. [3]</blockquote><blockquote>UNI governance also has the ability to add additional fee tiers. When it adds a new fee tier, it can also define the tickSpacing (see Section 6.1) corresponding to that fee tier. [3]</blockquote><blockquote>UNI governance has the power to transfer ownership to another address. [3]</blockquote><p>The governance structure is designed so that the community can adapt the protocol over time, in a secure and decentralized way.</p><h4>Oracle Upgrades</h4><p>In Uniswap V2, pools tracked prices every time a trade happened and required users to manually record the desired values to then calculate an average price over time.</p><p>V3 records all the necessary data needed to compute a time-weighted average price (TWAP) on-chain, “<em>allowing external contracts to compute onchain TWAPs over recent periods</em>” [3] without having to store the data locally.</p><h3>UniswapV3 Architecture</h3><p>The next thing we need to break down is the smart contract architecture of Uniswap V3. We will briefly break down each of the main smart contracts to gain a high-level overview of them and each contract’s role in the overall protocol.</p><p>The Uniswap library of smart contracts is split into two main groups:</p><ol><li><strong>Uniswap/V3-core</strong></li><li><strong>Uniswap/V3-periphery</strong></li></ol><h3><strong>UniswapV3 Core</strong> Contracts</h3><p>contain the core logic and functions of the Uniswap protocol. They are the contracts that can hold and manipulate user funds. These contracts are kept as short and simple as possible. This gives the contracts the lowest attack surface possible, increasing security.</p><p>Let’s have a look at what each one does.</p><h4>UniswapV3Factory</h4><p>The first is the UniswapV3Factory.sol<strong> </strong>smart contract. In solidity the term ‘factory pattern’ is used for contracts that create other contracts. In the case of Uniswap, the factory contract does 3 main things:</p><ol><li>Allows any user to create new pools, provided the pool does not exist already.</li><li>The owner can transfer ownership of the factory contract.</li><li>Allows the owner of the contract to add a new fee tier, with a desired tick spacing.</li></ol><h4>UniswapV3Pool</h4><p>Any pool contract, created by the factory contract, acts as the AMM (automated market maker) for that particular pool. It has all the functionality necessary to carry out this job. The main things it does are:</p><ol><li>Give users price and tick information.</li><li>Set the initial price of the pool.</li><li>Mint new NFT liquidity positions.</li><li>Collect fees and close liquidity positions.</li><li>facilitate normal token swaps and flashswaps.</li></ol><h3>UniswapV3 Periphery Contracts</h3><p>The periphery contracts provide a more user-friendly way to interact with the core contracts. Built to be used on top of the core contracts, they distill some of the complex low-level aspects of the core contracts, making it easier for developers to integrate Uniswap into other applications. This system of separation gives the periphery contracts freedom to be modified and develop, without compromising the core protocol.</p><p>Let’s see what each one does:</p><h4>SwapRouter.sol</h4><p>The Swap router provides a more user-friendly interface for carrying out different types of swaps, through any Uniswap V3 pool contract.</p><p>the different functions cover:</p><ol><li>single swaps, where the input or output amount can be specified.</li><li>multi-hop swaps where the input or output amount and swap path can be specified.</li><li>A callback function, which can be used to add extra actions to a swap. Usually used when the Flash function is called, to carry out any desired arbitrage action before paying back any borrowed tokens.</li></ol><h4>NonfungiblePositionManager.sol</h4><p>The position manager contract is the interface for managing concentrated liquidity positions.</p><p>It includes the functions to do the following:</p><ol><li>Mint new positions.</li><li>Increase / decrease existing positions.</li><li>Collect any accumulated fees.</li></ol><h3>Reusable smart contract libraries</h3><p>Now we understand of the overall architecture of Uniswap, we can define what a re-usable smart contract library is: a tried and well-audited piece of code, that can be re-used in different contexts. Described by the Ethereum foundation as “building blocks”.</p><blockquote>There are many open source smart contract libraries available that provide reusable building blocks for your project that can save you from having to reinvent the wheel. [6]</blockquote><p>Smart contract libraries are divided into two main camps according to the Ethereum docs: behaviors and standards.</p><p><strong>Behaviors</strong> are little tried and tested bits of functionality, for example openZepellin’s safeMath, which prevents overflows and underflows when using uint and ints when developing smart contracts.</p><p><strong>Standards</strong> ensure interoperability by using token and practice standards, developed and created by different parties, in the Ethereum community. The ERC-20 token standard is a well-known example, which provides a well-audited framework for EVM compatible tokens. Most altcoins on any EVM chain follow the ERC-20 standard. The standard continues to be developed today.</p><p>There are many smart contract libraries in the blockchain space. Uniswap protocol has its own smart contract library as well as utilizing third-party smart-contract libraries like OpenZeppelin.</p><h4>OpenZeppelin</h4><p>Launched in 2015 with a mission to make smart contract development more secure and accessible. The company creates tools and templates that enable developers to write more secure code, as well as auditing many of the top blockchain protocols, spanning across many different core blockchains. There re-usable smart contract libraries are the most widely used across the blockchain space.</p><p>If Uniswap has set the standards for Defi protocols and decentralized exchanges in general, OpenZeppelin has done the same, for smart contracts in a much broader sense. If you have heard the term tokens, you are talking about the ERC-20 token standard. Or non-fungible tokens (NFT’s), you are talking about the ERC-721 or ERC-1155. Both of which set out as Ethereum improvement proposals (EIPs) by Ethereum core developers, which openZeppelin then developed into secure implementations of both.</p><p>Let’s break down the pieces necessary for creating these types of re-usable smart contract libraries: Inheritance and interfaces.</p><h3>Inheritance</h3><p>Inheritance in solidity is when a smart contract inherits all the functionality from another smart contract. This means that you can call any function from the inherited contract.</p><p>The use of inheritance in Solidity enables and increases modularity in the development process. Modularity in computer programming refers to splitting a system into separate components, that run separatly but work together, making code easier to modify and maintain.</p><h4>Inheriting utility smart contracts in Uniswap</h4><p>Utility smart contracts are generally very simple, some containing just 1 function. The Uniswap protocol has many of its own utility contracts in the ‘libraries’ folder in each of the core and periphery repositories. These fall into the <strong>behavior</strong> category of re-usable smart contracts. The main smart contracts inherit from its library of utility smart contracts that each serve different purposes. These libraries can be used as and when needed.</p><h4>LowGasSafeMath</h4><p>A widely re-used utility smart contract, is LowGasSafeMath, in the Uniswap core repository contracts/libraries folder.</p><pre>// SPDX-License-Identifier: GPL-2.0-or-later<br>pragma solidity &gt;=0.7.0;<br><br>library LowGasSafeMath {<br>   <br>    function add(uint256 x, uint256 y) internal pure returns (uint256 z) {<br>        require((z = x + y) &gt;= x);<br>    }<br><br>  <br>    function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {<br>        require((z = x - y) &lt;= x);<br>    }<br><br>    function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {<br>        require(x == 0 || (z = x * y) / x == y);<br>    }<br><br>    function add(int256 x, int256 y) internal pure returns (int256 z) {<br>        require((z = x + y) &gt;= x == (y &gt;= 0));<br>    }<br><br>    <br>    function sub(int256 x, int256 y) internal pure returns (int256 z) {<br>        require((z = x - y) &lt;= x == (y &gt;= 0));<br>    }<br>}</pre><p>It takes the basic arithmetic operations addition, subtraction and multiplication, then reverts if an over or underflow occurs.</p><p>An overflow is when the maximum number is exceeded for a given integer type. For example, an int8 has a maximum value of 127 (128 –1 because 0 is a value, with 128 values total). say you had to work out 127 + 1. if you used an int8, the answer would be 0 because when an overflow happens, you just go back to that first possible value and start again.</p><p>They then use the require statement to cause a revert. There are several options when it comes to reverting a function in Solidity but require is the cheapest in terms of gas cost for single operations.</p><p>If you wish to go deeper on gas optimization in error handling, y<a href="https://medium.com/coinsbench/solidity-error-handling-notes-on-require-revert-and-assert-6fe8140f555c">ou can learn more about require, revert and assert here</a>.</p><h4>Utility Contract inheritance <strong><em>implementation</em></strong></h4><p>Its time to look at a working example of inheritance in action. We should look no further than the UniswapV3Pool smart contract, that implements LowGasSafeMath. I will only paste the relevant parts of the code, head over to the Uniswap github for the full code.</p><pre>// UniswapV3Pool.sol<br><br>pragma solidity =0.7.6;<br><br>import &#39;./libraries/LowGasSafeMath.sol&#39;;<br><br>contract UniswapV3Pool is IUniswapV3Pool, NoDelegateCall {<br>  <br>  using LowGasSafeMath for uint256;<br>  using LowGasSafeMath for int256;<br><br>}</pre><p>To use the code in a library, it must first be imported just under the pragma statement. Then in the contract, just above the state variables declare the use of LowGasSafeMath for whichever uint or int type you need.</p><p>Now whenever an arithmetic operation is carried out, lets take 1+1 as an example. Solidity is actually carrying out the code below.</p><pre>1 + 1 === add(1, 1)</pre><p>using the add( ) function from the LowGasSafeMath library.</p><h3>Interfaces</h3><p>Interfaces in Solidity are essentially a list of functions from another smart contract. None of these functions can be specifically implimented in an interface. Rather, they tell any users of these functions how they work, without showing the inner workings of the function.</p><p>This abstraction, makes it easier for devs to build using the interface as an interface function will work more like an off-the-shelf part. All you need to know is what goes in and what goes out.</p><p><a href="https://medium.com/coinsbench/solidity-interfaces-facilitating-interaction-modularity-and-dapp-upgradability-baeb750cb37a">You can go deeper into the subject of interfaces here.</a></p><h4>The use of Interfaces in Uniswap</h4><p>Interfaces in Uniswap make it far easier to interact with the core contracts of the protocol. Each repository will have an interface for most (if not all) of the main smart contracts in the protocol. Interface files use an ‘I’ before the files name to distinguish them from standard smart contracts, for example IQuoter.sol is the interface for the Quoter.sol smart contract.</p><p>In the context of re-usable smart contract libraries, interfaces fall under the <strong>standard </strong>category. Uniswap interfaces have provided industry standards in running and interacting with decentralized exchanges (DEX’s).</p><p>Uniswap is the most forked Defi protocol, with many new projects forking the protocol and then modifying it for their own purpose. The most famous of which is probably SushiSwap, which became a major name the ‘Defi summer’ of 2020, combining Uniswaps Dex utility with yield farming.</p><h4>The ERC-20 Smart Contract And Uniswap</h4><p>The ERC-20 token smart contract by openZeppelin acts as a base contract for developing most new tokens on the Ethereum blockchain. It follows all the necessary rules set in EIP20 by the Ethereum core developers.</p><blockquote>A standard interface allows any tokens on Ethereum to be re-used by other applications: from wallets to decentralized exchanges. [12]</blockquote><p>ERC-20 is an essential part of UniswapV3. Every token traded on Uniswap (and any other DEX on an EVM chain) follows the ERC-20 standard. All versions of Uniswap have been built around it.</p><p>A token standard is essential for the smooth operation of an open-source decentralized exchange. If every new coin came with totally different functionality, it would be highly time consuming to add new tokens to a protocol, because developers would potentially have to write new apis to interact with each one separately. Furthermore, from a security perspective, this would be a nightmare.</p><p>A standard creates an inclusive space, where the idea of an ‘Ethereum token’ is clearly defined and agreed upon by the community, allowing developers to create protocols that work smoothly, with any token that is created.</p><h4>Initializing Interfaces in smart contracts</h4><p>Interfaces are implemented by first declaring the interface. This can be done in two ways.</p><ol><li>import them, as you would any other smart contract.</li></ol><pre>import&quot;@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol&quot;</pre><p>2. Declare them in the solidity file.</p><pre>interface ISwapRouter {<br>    struct ExactInputParams {<br>        bytes path;<br>        address recipient;<br>        uint256 deadline;<br>        uint256 amountIn;<br>        uint256 amountOutMinimum;<br>    }<br>    <br>    function exactInputSingle(<br>        ExactInputSingleParams calldata params<br>    ) external payable returns (uint256 amountOut);<br>}</pre><p>After that you utilize the imported interface like so.</p><pre>contract interfaceTest{<br>    address constant SWAP_ROUTER = 0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45;<br>    <br>    ISwapRouter public router;<br>    <br>    constructor() {<br>        router = ISwapRouter(SWAP_ROUTER);<br>    }<br>}</pre><p>Once the interface is initialized using the deployed smart contract it works with, you can call functions directly. Here’s a test example:</p><pre>router.exactInput(params)</pre><h4>ISwapRouter.sol</h4><p>A widely used Uniswap V3 interface is the ISwapRouter. The swap router contains functions to carry out more complicated token swaps. For example, a developer can implement a function that carries out several swaps one-after-the other. Also known as a ‘multi-hop swap’.</p><p>The functions themselves are quite complicated. However, the interface abstracts this complexity, allowing developers to build more complex arbitrage trading strategies, without having to worry about all the workings under the hood.</p><p>ISwapRouter has 4 main swap functions:</p><ol><li>exactInputSingle</li><li>exactInput</li><li>exactOutputSingle</li><li>exactOutput</li></ol><p>We will take a look at <strong>exactInput</strong>, as this is the function that enables multi-hop swaps and is the swap type (input) that people will be the most familiar with. The ‘input’ means that the user would declare the amount of tokens they wish to give to the trade. Conversely, you declare the amount of tokens you want to get back from the trade, in the ‘output’ functions.</p><pre>// SPDX-License-Identifier: GPL-2.0-or-later<br>pragma solidity &gt;=0.7.5;<br>pragma abicoder v2;<br><br>import &#39;@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol&#39;;<br><br>/// @title Router token swapping functionality<br>/// @notice Functions for swapping tokens via Uniswap V3<br><br>    struct ExactInputParams {<br>        bytes path;<br>        address recipient;<br>        uint256 deadline;<br>        uint256 amountIn;<br>        uint256 amountOutMinimum;<br>    }<br><br>    /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path<br>    /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata<br>    /// @return amountOut The amount of the received token<br>    function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);<br><br>}</pre><p>As you can see, the exactInput( ) function takes an ExactInputParams{ } struct as input. The path is the part where you can specify multiple hops. based on the order of inputs the function will determine which tokens to swap and between which pools.</p><h4>Arbitrage example Real-world use case</h4><p>Let’s look at a real-world use case for the exactInput swap. Say you saw a price difference between two different pools of the same token. An exactInput swap would be an effective tool in profiting from this arbitrage opportunity.</p><figure><img alt="A diagram illustrating stablecoin arbitrage between two USDT/USDC pools with different prices. Pool 0 has a 1:1 price ratio, and Pool 1 has a 1:1.1 ratio. The trade process shows an initial wallet balance of 100 USDT. In Trade 1, 100 USDT buys USDC in Pool 1 at 1 USDT = 0.90909 USDC, resulting in 110 USDC. In Trade 2, 110 USDC buys USDT in Pool 0 at 1 USDC = 1 USDT, resulting in 110 USDT. The final wallet balance is 110 USDT, showing a 10 USDT profit." src="https://cdn-images-1.medium.com/max/952/1*qqjlbqWSNXLuYBfpuDkxDA.png" /><figcaption>Fig 4. Basic example of a stablecoin arbitrage trade between 2 different pools with the smae tokens.</figcaption></figure><p>The params struct might look something like this:</p><pre>ExactInputParams({<br>       path: [USDT_ADDRESS, 500, USDC_ADDRESS, 3000, USDT_ADDRESS]<br>       recipient: address(this),<br>       deadline: block.timestamp,<br>       amountIn: 100000000,<br>       amountOutMinimum: 110000000,<br>                });</pre><p>Let’s go through the path parameter:</p><p><strong><em>path[0] (USDT_ADDRESS)</em></strong>: TokenIn for the first swap on pool 0.</p><p><strong><em>path[1] (500)</em></strong>: Fee tier for pool 0.</p><p><strong><em>path[2] (USDC_ADDRESS)</em></strong>: Token out from swap on pool 0 / tokenIn for second swap on pool 1.</p><p><strong><em>path[3] (3000)</em></strong>: Fee tier for pool1.</p><p><strong><em>path[4] (USDT_ADDRESS)</em></strong>: TokenOut for the second trade.</p><p>You can code as many hops as you like in a multi-hop swap. The trade-off being, the more hops you add, the more difficult it will be to find profitable trade routes, However the more hops, the higher the profit potential.</p><p>From the path, the function gets all the necessary information you need for each swap, Including:</p><ul><li>Token in / token out.</li><li>Pool address — under the hood getPool( ) would be called using each token address + the fee amount.</li><li>The order of the swaps</li></ul><p>This is just one of many brilliant engineering decisions you will find, if you study the Uniswap protocol. Where a complex operation is achieved with the least code possible, making complex financial operations more accessible for developers. Moreover, these contracts have been well audited and have stood the test of time.</p><p>Uniswap has never been drained of any funds. Which is truly remarkable, as hackers surely have tried, as it has the highest total value locked of any DEX in the defi space.</p><h4><a href="https://github.com/SimSimButDifferent/UniV3FlashSwapDualArbBot">Uniswap V3 FlashSwap Arbitrage Bot</a></h4><p>Theoretically, you could use a multi-hop trade to do this in a single function call, although in practice, it would be better to build a bot to scan different pools looking for opportunities.</p><p>I have built an open-source <a href="https://github.com/SimSimButDifferent/UniV3FlashSwapDualArbBot/tree/arbitrum">UniswapV3 flashswap arbitrage bot</a>, as part of my research into this topic. It scans selected pools for arbitrage opportunities between two different tokens and two different pools, like the example above. It utilizes both flashswaps and exactInput swaps.</p><p>Fork the repository and deploy your own, if you want to see a basic implementation of this type of trading system.</p><h3>Uniswap V3 Benefits and challanges</h3><p>Uniswap brought many changes to the original vision of the automated market maker concept. With substantial changes come many benefits. And yet also many new challenges as a result. Here are some of the benefits and challenges summarized.</p><h4>Benefits</h4><ul><li>Increased capital efficiency</li><li>More Stable pricing</li><li>Higher fees for LP’s</li><li>Increased customization</li><li>Better + more flexible user experience</li></ul><h4>Challenges</h4><ul><li>Complexity in managing positions</li><li>Potential risks / security considerations</li><li>Market and regulatory challenges.</li></ul><p>The introduction of concentrated liquidity brought with it higher capital efficiency by giving LP’s and pool creators greater customization over many different aspects of pools and positions. However, with greater customization comes greater complexity, with higher complexity, comes less accessibility.</p><h4>Market and Regulatory challenges</h4><figure><img alt="A grand digital illustration featuring a majestic unicorn, symbolizing Uniswap, embossed on a large coin flanked by classical columns. The unicorn has a flowing pink mane, and the coin includes intricate designs and the inscription “S.E.C.”" src="https://cdn-images-1.medium.com/max/1024/1*Uc1OoQ-1K5iEyRQhYafVmA.png" /><figcaption>Fig 5. Uniswap vows to contest SEC’s legal threat. Source: <a href="https://cryptobriefing.com/uniswap-pushes-back-sec-threatens-lawsuit/">https://docs.uniswap.org/concepts/protocol/range-orders</a></figcaption></figure><p>When I first read about Bitcoin back in 2012, it was painted as a way to service illicit activity on the internet. It was not taken seriously by any financial authority at all.</p><p>We still hear this today, although the tides seem to be shifting. At time of writing (July 2024), The SEC has spent the last couple of years throwing lawsuits at as many decentralized, open-source protocols as they could, in the name of “protecting users”. Unfortunately they failed to protect users from the Luna collapse, FTX, 3 Arrows capital, vaporizing $60 billion, 8 billion and 3.5 billion dollars, respectively, in value. But they did try to protect users from Uniswap, claiming that it is an unregistered securities exchange.</p><blockquote>We believe the SEC should embrace open source technology that improves on outdated commercial and financial systems, instead of attempting to litigate it out of existence. The Uniswap protocol is secure, low cost, transparent infrastructure that “protects investors and maintains fair, orderly, and efficient markets.” Ironically, that’s the SEC’s mission. [10]</blockquote><p>Crypto has been going through the classic cycle of: first they ignore you, then they fight you, then you win. This article was written before the US election 2024 and just at the beginning of the year, pretty much all parties were anti-crypto. Now in July both Donald Trump and Robert Kennedy Jr, are confirmed attendees (among other notable political figures) to the Bitcoin conference 2024. Times are changing.</p><h3>Summary</h3><p>So, putting it all together. We set the scene with the rise of Defi and how Uniswap blossomed as one of the most influential and innovative open-source defi protocols. Then going through some of the most game-changing features of V3, most notably, concentrated liquidity.</p><p>After that, we broke down the Uniswap V3 architecture, into its separate repositories:</p><p><strong>Uniswap/v3-core:</strong> For the core smart contracts that handle any user funds. Written as simple and secure as possible.</p><p><strong>Uniswap/v3-periphery:</strong> Provide more user-friendly ways to interact with the core protocols.</p><p>Moving forward, we defined a reusable smart contract library as a well-audited piece of code, that can be reused in different contexts. And broke down the two different types of reusable contracts and the roles of inheritance and interfaces in each.</p><p>Firstly, <strong>behaviors</strong> which are reusable bits of utility functionality, like LowGasSafeMath that causes a revert if an uint or int overflow occurs. These generally use inheritance, to be utilized in other smart contracts and are only used as and when needed. Secondly, <strong>standards </strong>are used to enable interoperability between different tokens and protocols. Set out as ERC’s by the Ethereum community, these are generally implemented using interfaces, the most notable being IERC20 token interface by OpenZeppelin, implemented by the vast majority of EVM based altcoins.</p><p>Getting deeper, we looked at a real-world example in the form of DEX-arbitrage, using the IswapRouter interface, utilizing multi-hop swap function (exactInput( )). Moving on to my Uniswap V3 FlashSwap Arbitrage Bot, to see a working implementation of this example.</p><p>Finally, we explored the benefits and challenges of Uniswap, like the trade-off between customizability and accessibility when providing liquidity and the on-going challenges Uniswap and all crypto faces in the regulatory landscape.</p><h3>Final thoughts</h3><p>So, going full circle… How does Uniswap use inheritance and interfaces to provide reusable smart contract libraries and why is it a no-brainer to use them, when deploying code to a blockchain?</p><p>Uniswap uses Inheritance to create little utility functions that solve specific problems and can be inherited by any smart contract as and when they are needed.</p><p>Interfaces like ERC-20 by OpenZeppelin, are used to, adhere to the token standards laid out by the Ethereum community, ensuring that they remain relevant for the long term. However, Uniswap’s interfaces such as IUniswapPool and ISwapRouter have been the standard for how a decentralized exchange is built and is operated. Uniswap the most forked Defi protocol in the cryptocurrency space, being used as a base for a huge number of decentralized applications that came after it.</p><p>Many protocols try to ‘re-invent the wheel’ and create something truly new, some fork Uniswap and attempt to add additional features to it. In both instances, there are many examples where huge amounts of tokens fell prey to attackers. Two notable examples were Uranium finance and Burger Swap. Between them they lost around $64 million dollars between them. In both examples the exchanges had directly or indirectly forked Uniswap.</p><p>Making changes without proper auditing of the code before deployment led the funds to be lost. The largest exploits have occurred on bridges, which make the Uniswap forks seem tiny. The biggest was the Ronin bridge, to the on-chain game Axie-infinity, with a whopping 600 million dollars in ETH and USDC being stolen in March 2022.</p><p>In 2024, why is Uniswap still a top DEX? It has been in existence for over 5 years, now spread across over 20 different EVM chains and Layer 2’s and has still never been hacked. Uniswap labs have been pioneers in developing the architecture and standards for the automated market maker, developing secure and stable standards for the rest of the Defi community to follow and learn from.</p><p>Using reusable smart contracts from a company like Uniswap labs or OpenZeppelin is a no-brainer because you can rest-assured that their smart contracts have been battle tested by the best auditors and leading minds in the crypto industry.</p><p>So why wouldn’t you use them as the base building blocks for your next project?</p><p>Although, if you do… Always ensure that your protocol has been sufficiently attacked before deploying to the blockchain.</p><h3>References</h3><p><em>[1] Adams, Hayden. 2018. “Uniswap Whitepaper”</em></p><p><em>[2] Adams, Hayden. Robinson, Dan. Zinsmeister, Noah. 2020. “Uniswap V2 Core”</em></p><p><em>[3] Adams, Hayden. Robinson, Dan. Zinsmeister, Noah. 2021. “Uniswap V3 Core”</em></p><p><em>[4] Buterin, Vitalik. 2016. “Let’s run on-chain decentralized exchanges the way we run prediction markets”</em></p><p><em>[5] Dao, Maker. 2017. “The Dai Stablecoin System” (Original)</em></p><p>[6] Foundation, Ethereum. “Smart Contract Libraries”</p><p><em>[7] Kuznetstov, Ivan (Jeiwon). 2022. “Uniswap V3 Development Book”</em></p><p>[8] Labs, Uniswap. 2020. “https://blog.uniswap.org/uni”</p><p>[9] Labs, Uniswap. 2021. “https://docs.uniswap.org/concepts/protocol/fees”</p><p>[10] Labs, Uniswap. 2024. <em>“The fight for defi continues”</em></p><p><em>[11] Russo, Camila. 2022. “What Is Decentralized Finance?: A Deep Dive by The Defiant”</em></p><p>[12]<em> Vogelsteller, Fabian. Buterin Vitalik. 2015. “Ethereum Improvement Proposal 20 (EIP20)”</em></p><h3>My socials</h3><p>Github — <a href="https://github.com/SimSimButDifferent">https://github.com/SimSimButDifferent</a></p><p>Twitter — <a href="https://twitter.com/Simsimbutdev">https://twitter.com/Simsimbutdev</a></p><h3>My Other relavent works</h3><h4>Articles</h4><p><a href="https://medium.com/coinsbench/solidity-interfaces-facilitating-interaction-modularity-and-dapp-upgradability-baeb750cb37a"><em>Solidity Interfaces — The building blocks of modern dApps</em></a></p><p><a href="https://medium.com/coinsbench/solidity-error-handling-notes-on-require-revert-and-assert-6fe8140f555c"><em>Solidity error handling — notes on require, revert and assert</em></a></p><h4>My Smart Contract projects</h4><p><a href="https://github.com/SimSimButDifferent/UniV3FlashSwapDualArbBot">Uniswap V3 FlashSwap Arbitrage Bot</a></p><p><a href="https://github.com/SimSimButDifferent/RCVotingSystemSmartContract">Ranked Choice Voting System Smart Contract</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=855c5bb83602" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/uniswap-v3-a-deep-dive-using-inheritance-and-interfaces-to-produce-re-usable-smart-contract-855c5bb83602">Uniswap V3 - A Deep Dive: Using Inheritance and Interfaces to Produce Re-usable Smart-Contract…</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solidity error handling — notes on require, revert and assert]]></title>
            <link>https://coinsbench.com/solidity-error-handling-notes-on-require-revert-and-assert-6fe8140f555c?source=rss-4ee435f783c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fe8140f555c</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Simeon Campbell]]></dc:creator>
            <pubDate>Wed, 29 May 2024 09:27:59 GMT</pubDate>
            <atom:updated>2024-05-31T16:34:54.114Z</atom:updated>
            <content:encoded><![CDATA[<h3>Solidity error handling — notes on require, revert and assert</h3><figure><img alt="A retro pixel art illustration showing a futuristic computer screen with “ERROR” messages related to Solidity error handling, featuring “require,” “revert,” and “assert.” A hand with the Ethereum logo emerges from the ground, symbolizing control over blockchain errors. The sci-fi background includes floating shapes, futuristic buildings, and warning signs, highlighting the importance of proper error handling in Solidity." src="https://cdn-images-1.medium.com/max/1024/1*W_TeiNXlH1j8GeEFTpIaDw.png" /></figure><p>Error handling is a key part of the solidity programming language. This is for a number of reasons, although two main ones stand out. Firstly, blockchain’s immutable nature means that once something is published, it cannot be altered.</p><p>in addition, writing data to a blockchain can be incredibly expensive. This is because the amount of gas that a transaction costs, is based on the base transaction cost, plus the cost of execution of any smart contract logic included within the transaction.</p><p>The gas system incentivizes us to create systems that are as gas efficient as possible. Error handling is one aspect of Solidity that is utilized to do this. In more traditional programming languages, error handling was usually done using ‘if/else’ statements.</p><pre>if(input &lt;= 0) {<br>    return &quot;input must be above zero&quot;<br>}</pre><p>In solidity, you can still use ‘if’ statements, however there are 3 other ways we can stop a bad transaction, before it has completed. This is highly important as it saves any gas that has so far not been used.</p><h3><strong>require</strong></h3><pre>require(input &gt; 0, &quot;input must be above zero&quot;);</pre><p>Firstly, the ‘require’ statement is slightly different to the ‘if’ statement because whatever is declared in the brackets must be true, whereas in an if statement you can declare something be equal (==) or not equal to (!=).</p><p>So, while the ‘if’ statement says “if the input in less than or equal to 0, then return the error message”, whereas the require statement says, “the input must be above zero, otherwise return the error message”.</p><p>You can choose whether to add a return message by adding a comma followed by a string of the message after it. The simplicity of the require statement makes it ideal for one-time simple error handling, such as handling user inputs and checking things before any other code has been executed.</p><h3>revert</h3><p>Secondly, the revert statement is generally used within an ‘if/else’ statement to return custom errors. These custom errors are declared when the contract is initially deployed and are clearly visible at the top of the smart contract.</p><pre>pragma solidity ^0.8.0;<br><br>/* errors */<br>error Wallet__InputMustBeAboveZero();<br><br>contract Wallet {<br>    function input(string input) public view {<br>        if(input &lt;= 0){<br>            return Wallet__InputMustBeAboveZero()<br>        }<br>    }<br>}       </pre><p>So, for the input handling example, there is just an unnecessary amount of code, where with a require statement, it could all be handled on just one line. However, revert statements and custom errors really come into their own on more complex error handling. This is because the errors are far more organized in a batch at the top of the contract.</p><p>So, instead of having to find each error in various require statements you can go to the top of the contract and simply search for that error and make any changes you need to.</p><h3>assert</h3><p>Finally, ‘assert’ makes sure that something is working as it should. The purpose is to make sure that functions and variables, that should not change, are as they should be.</p><pre> function transfer(address to, uint256 amount) public {<br>        require(balances[msg.sender] &gt;= amount, &quot;Insufficient balance&quot;);<br><br>        uint256 previousBalances = balances[msg.sender] + balances[to];<br>        <br>        balances[msg.sender] -= amount;<br>        balances[to] += amount;<br><br>        // Assert that the total balances remain the same<br>        assert(balances[msg.sender] + balances[to] == previousBalances);<br>    }</pre><p>In the function above, after the transfer balances have been updated, you can use the assert statement to ensure that the total of all balances has remained the same. If the balance was not the same, this would show a major bug within the code. The assert code is used to catch bugs in the code, not for validating user inputs.</p><h3>A brief gas study of require, revert and assert</h3><p>I did a brief gas study on each, so I could make a more informed decision when considering which to use and when. The function I used was my ‘deposit’ function from my Eth wallet contract.</p><pre>error EthWallet__DepositMustBeAboveZero();<br><br>function deposit() public payable {<br>        <br>        uint depositAmount = msg.value;<br>        <br>        // --------------------------------------------<br>        if (depositAmount &lt;= 0) {<br>            revert EthWallet__DepositMustBeAboveZero();<br>        }<br>        // --------------------------------------------<br><br>        if (users[msg.sender].userBalance &gt; 0) {<br>            users[msg.sender].userBalance += depositAmount;<br>        } else {<br>            users[msg.sender] = User(msg.sender, depositAmount, 0, 0);<br>        }<br>    }</pre><p>I quickly realised that it was more gas efficient to do any checks before declaring any variables. This seems obvious, but it is now cemented in my mind. Below are the results when the deposit amount is zero.</p><p><strong>revert</strong></p><p>Transaction cost: 21283</p><p>Gas execution cost: 219 gas</p><p><strong>require</strong></p><pre>require(depositAmount &gt; 0, &quot;deposit must be above zero&quot;)</pre><p>Transaction cost: 21243</p><p>Gas execution cost: 179 gas</p><p><strong>assert</strong></p><pre>assert(depositAmount &gt; 0)</pre><p>Transaction cost: 21285</p><p>Gas execution cost: 221 gas</p><p>In this case the choice is clear. The ‘require’ statement was the cheapest gas execution cost. Furthermore, I am simply validating user input. So, it is not necessary to declare a global error message. Moreover, the code looks tidier because the whole statement fits nicely on one line. Below is the final deposit function, as it was after I carried out this study.</p><pre>function deposit() public payable {<br>        <br>        // --------------------------------------------<br>        require(depositAmount &gt; 0, &quot;deposit must be above zero&quot;)<br>        // --------------------------------------------<br><br>        uint depositAmount = msg.value;<br><br>        if (users[msg.sender].userBalance &gt; 0) {<br>            users[msg.sender].userBalance += depositAmount;<br>        } else {<br>            users[msg.sender] = User(msg.sender, depositAmount, 0, 0);<br>        }<br>    }</pre><h3>Conclusion</h3><p>In conclusion, for my purpose of checking the user input for function. the ‘require’ statement is the clear winner. However, as contracts grow in complexity and error statements grow in number, the ‘revert’ statement becomes much more appealing. This is because having a list of errors at the top of your smart contract can greatly increase the readability and changeability of your code.</p><p>On the other hand, the ‘assert’ function is not really suited for use in my deposit function. Assert tests for invariants and fails only if there is a bug in the code. It is great for making sure that variables are the expected values or functions are producing the expected outcomes.</p><p>Error handling is a key part of efficient front and backend web3 development. They can be used to guide the end user through, the use of a smart contract or app. Also, by carefully choosing which to use for each scenario, smart contract developer can create contracts that are as gas optimized as possible, ultimately saving everyone that precious gas.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fe8140f555c" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/solidity-error-handling-notes-on-require-revert-and-assert-6fe8140f555c">Solidity error handling — notes on require, revert and assert</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Notes on View and Pure modifiers in Solidity]]></title>
            <link>https://coinsbench.com/notes-on-view-and-pure-modifiers-in-solidity-befc5415634c?source=rss-4ee435f783c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/befc5415634c</guid>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity-tutorial]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Simeon Campbell]]></dc:creator>
            <pubDate>Thu, 02 May 2024 02:43:01 GMT</pubDate>
            <atom:updated>2024-05-03T12:07:24.225Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A digital illustration showing a character with an Ethereum logo for a head, standing in an ancient library. The character is holding a calculator and giving a thumbs-up. The library is filled with rows of old books, lit by candles, conveying a blend of old-world knowledge and modern technology. This image symbolizes the integration of traditional learning with blockchain technology." src="https://cdn-images-1.medium.com/max/1024/1*u7sx48E2wgso0VJct1_MKw.png" /></figure><p>Why are there so many different modifiers for functions in the Ethereum EVM’s programming language Solidity? To answer this question, you must first understand what the Ethereum blockchain is.</p><h3>What is the Ethereum Blockchain?</h3><p>The Ethereum blockchain can be accurately described as a ‘decentralized immutable distributed ledger’. This may seem a little overwhelming, so let’s break it down.</p><ul><li><strong>Decentralized</strong> — There is no single centralized entity responsible for the ledger, but rather an entire network / community.</li><li><strong>Immutable </strong>— It cannot be altered.</li><li><strong>A distributed ledger</strong> — A shared accounting of the information and transactions.</li></ul><p>So blockchains are just accounting systems that are openly shared by a wide number of people, where the information cannot be changed.</p><p>We see words like view , pure or payable appear after the function name. These are called modifiers, but what do they mean?</p><figure><img alt="Solidity’s list of Modifiers from the official Solidity Docs cheetsheet. It can be found at — https://docs.soliditylang.org/en/v0.8.23/cheatsheet.html#modifiers" src="https://cdn-images-1.medium.com/max/937/0*wSHS8xXiiojMGsZA" /><figcaption>From the Solidity docs cheetsheet — <a href="https://docs.soliditylang.org/en/v0.8.23/cheatsheet.html#modifiers">https://docs.soliditylang.org/en/v0.8.23/cheatsheet.html#modifiers</a></figcaption></figure><p>There are many modifiers to choose from. For example:</p><ul><li>payable allows for ETH to be received by a smart contract address.</li><li>immutable is used for state variables to be written and stored at construction time of the contract and stored on the blockchain forever.</li></ul><p>The two that we are talking about today are the pure and view modifiers.</p><h3>View Modifier</h3><p>The view modifier declares that the function in question can only view and return blockchain data. It can’t write to or alter the state of the blockchain. One very common use of view functions is a get or a getter function.</p><pre>function getUserBalance() public view returns (uint) {  <br>    return users[msg.sender].userBalance;<br>} </pre><p>For example, if you have a state variable that can change, using the contract, you may need access to the information. These are created automatically, with the public modifier on the variable itself. Or if the variable is private, you will have to write your own. Furthermore, if you declare a function as a view function, there is absolutely no way of spending gas when calling that function.</p><h3>Pure Modifier</h3><p>The pure function declares that you can’t write, alter, or even read the state of the blockchain. These functions are used for calculations carried out, that are not part of transactions that will be recorded on the blockchain.</p><pre>function addition(uint a, uint b) public pure returns (uint) { <br>    return a + b; <br>} </pre><p>One thing that they both have in common is that they are free to use, meaning they do not cost any gas. This is because they do not write any data to the blockchain. Of course, you could add some sort of calculation of math to a variable before it is returned, in a view function, if that is appropriate to your smart contract.</p><h3>Conclusion</h3><p>In conclusion, the view and pure modifiers are essential building blocks of the solidity (and indeed any blockchain) programming language. Due to the economic incentives of the gas feature, a smart contract wants to try to use as little gas as possible. Smart contract developers can utilize the view modifier to access public blockchain information, without having to write a transaction to do so.</p><p>In addition, they can use the pure modifier to carry out any mathematics off chain at no cost, before only using the return values in write functions, where necessary. The immutable nature of blockchains is certainly an excellent feature, which gives their trustless nature. The gas cost, however, is necessary, as it incentivizes people to write worthy information to the blockchains. pure and view functions give the programmer freedom over when and where to write to the blockchain. This allows for the most efficient smart contracts, whilst allowing blockchains to maintain their trustlessness.</p><h3>References</h3><p><a href="https://docs.soliditylang.org/en/v0.8.23/cheatsheet.html#modifiers">Solidity Cheetsheet — Modifiers</a></p><h3>My socials</h3><p>Github — <a href="https://github.com/SimSimButDifferent">https://github.com/SimSimButDifferent</a></p><p>Twitter — <a href="https://twitter.com/Simsimbutdev">https://twitter.com/Simsimbutdev</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=befc5415634c" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/notes-on-view-and-pure-modifiers-in-solidity-befc5415634c">Notes on View and Pure modifiers in Solidity</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethereum gas costs, data types and control structures — A brief take]]></title>
            <link>https://coinsbench.com/ethereum-gas-costs-data-types-and-control-structures-a-brief-take-7fd03aaa9a00?source=rss-4ee435f783c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fd03aaa9a00</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[solidity-academy]]></category>
            <dc:creator><![CDATA[Simeon Campbell]]></dc:creator>
            <pubDate>Mon, 22 Apr 2024 03:02:04 GMT</pubDate>
            <atom:updated>2024-04-28T13:08:30.159Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ethereum gas costs, data types and control structures — A brief take</h3><figure><img alt="A retro-styled digital artwork depicting an old-fashioned gas station with vintage fuel pumps, set against a backdrop of a hazy sunrise over a deserted country road. The gas station sign has been humorously modified to display the Ethereum cryptocurrency logo on top and gas prices replaced with “ED” and “SUB” followed by Ethereum’s denomination names such as “wei” and “gwei,” humorously referencing “gas” used in Ethereum transactions." src="https://cdn-images-1.medium.com/max/1024/1*zwvWwU_3BtSOgNQc9Zj_lQ.png" /></figure><p>Ethereum gas is used when altering the state of the blockchain. Writing data to the Blockchain is expensive to carry out. This prevents people from spamming the blockchain for no reason, whilst rewarding the miners for keeping the network secure.</p><p>Let’s look at an example, like carrying out a trade on the decentralized exchange Uniswap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PRK3--8gmxHW8pSlhuzslw.png" /></figure><p>It all seems to happen instantaneously. However, there would be at least 3 steps to this process, all happening within the 1 transaction. Firstly, Checking the balance. Second, transferring tokens. And finally, updating the wallet balance. Each of these steps would incur their own specific amount of gas, which is relevant to the number of bytes required to carry out the transaction.</p><p>This is why there are so many different sizes of uint and int numbers. for example, if you know that a function using a uint will only require a number between 1–15, then you could use a uint8, as you know that you would not exceed the maximum number possible and therefore would save on any un-necessary gas costs.</p><pre>// Using uint8 for values between 1-15 to save gas<br>function incrementCounter() public {<br>    uint8 counter;<br>    counter += 1; // Safely increments counter within the uint8 range<br>}</pre><p>It is critical to prevent infinite loops, when using for loops, in solidity. Of course, this is because there would be an infinite amount of gas payable, and time taken for a given transaction. This is why the gas limit is part of solidity, which protects people from transactions that could potentially drain a user’s entire wallet.</p><p>In conclusion, when writing solidity code, the best programmers will meticulously choose the optimal data type and carefully craft their control structures to minimize gas costs for users of decentralized protocols like Uniswap. It is crucial when learning Solidity to keep up with best practices regarding gas optimization, in your own projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fd03aaa9a00" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/ethereum-gas-costs-data-types-and-control-structures-a-brief-take-7fd03aaa9a00">Ethereum gas costs, data types and control structures — A brief take</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solidity Interfaces — The Building Blocks of Modern dApps]]></title>
            <link>https://coinsbench.com/solidity-interfaces-facilitating-interaction-modularity-and-dapp-upgradability-baeb750cb37a?source=rss-4ee435f783c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/baeb750cb37a</guid>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[smartcontractdevelopment]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Simeon Campbell]]></dc:creator>
            <pubDate>Fri, 29 Mar 2024 07:46:13 GMT</pubDate>
            <atom:updated>2024-04-03T12:39:43.132Z</atom:updated>
            <content:encoded><![CDATA[<h3>Solidity Interfaces — The building blocks of modern dApps</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iJxHV5mI2h6z85qgAZaHQQ.png" /></figure><p>Bitcoin was the first blockchain to be introduced to the world back in 2009. It has proven through the years its resilience as a store of value. As of 2024, the largest money managers, hedge funds and even countries count it as a valuable part of their portfolios and balance sheets.</p><p>Some years later Vitalik Buterin released the Ethereum blockchain. But why did we need another blockchain anyway?</p><p>What sets Ethereum apart from the Bitcoin, Is its execution layer. Also known as the Ethereum virtual machine (EVM). The EVM allows for code to be written and stored on the blockchain. One ‘code file’ on the EVM is commonly known as a ‘smart contract’. This functionality essentially makes Ethereum a worldwide decentralized computer.</p><p>Smart contracts are the building blocks for all decentralized apps that are widely used today. Apps like Uniswap, Aave, Curve were some of the first examples, from the world of decentralized finance (Defi). But these projects paved the way for all the other dapps that exist today.</p><p>Here I will explore the role of ‘interfaces’ in Ethereum’s Solidity programming language. They are the glue that holds all the other separate smart contract pieces of decentralized dapps together. Interfaces are crucial in allowing modularity and upgradability for decentralized applications.</p><h3>Understanding Interfaces in Solidity</h3><p>Interfaces are used to define how a smart contract can work with another smart contract. Although they look like smart contracts, there is one glaring difference. They cannot have any functions implemented, meaning they don’t show how the function code works. Have a look at the simple example below:</p><pre>// Define the interface<br>interface IGreeter {<br>    function greet() external view returns (string memory);<br>}<br><br>// External contract implementing the interface<br>contract Greeter is IGreeter {<br>    function greet() external pure override returns (string memory) {<br>        return &quot;Hello, Solidity!&quot;;<br>    }<br>}<br><br>// Contract using the interface to interact with Greeter<br>contract GreeterClient {<br>    function fetchGreeting(address _greeterContract) external view returns (string memory) {<br>        IGreeter greeter = IGreeter(_greeterContract);<br>        return greeter.greet();<br>    }<br>}j</pre><p>The interface provides the necessary details needed to call the function and nothing else. This abstraction makes it far simpler for devs and users to interact with the smart contract because they don’t need to see all the extra lines of code that make the function work. They just need to know what goes in and what comes out.</p><p>Think about it in terms of driving a car. Millions of people drive cars every day. Is it necessary for them to know how to build one? Of course not, they simply need to know how to drive it.</p><h3>Facilitating Smart Contract Interaction</h3><p>Aside from only displaying the function signatures, they also act as a place to store all of the external functions in a particular smart contract. You can see this keyword in the example above. Known as a &#39;function visibility specifier&#39;, these allow the programmer to specify, how and if, other people or contracts can interact with a specific solidity function.</p><p>You can find a list of all the different visibility specifiers <a href="https://docs.soliditylang.org/en/v0.8.25/cheatsheet.html#function-visibility-specifiers">here</a> In the official Solidity documentation. The external specifier makes the function externally visible. Put simply, this allows the function to be called by other smart contracts.</p><p>Lets look at a well known example: The <a href="https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol">IERC20 interface</a>. I have highlighted the transfer function. This function simply moves the balance of a given ERC20 token from one address to another. This is thankfully presented in a very straight-forward way, compared to the full function code below. As you will notice it actually uses three functions together. But as users, do we need to know this information? Of course not. We just need to know what information the function needs and what will happen.</p><pre>pragma solidity ^0.8.20;<br><br>interface IERC20 {<br><br>    function transfer(address to, uint256 value) external returns (bool)<br>}<br><br>// ---------------------------------------------------------------------<br><br>pragma solidity ^0.8.20;<br><br>contract ERC20 is IERC20 {<br>    <br>    function transfer(address to, uint256 value) public virtual returns (bool) {<br>        address owner = _msgSender();<br>        _transfer(owner, to, value);<br>        return true;<br>    }<br><br>   <br>    function _transfer(address from, address to, uint256 value) internal {<br>        if (from == address(0)) {<br>            revert ERC20InvalidSender(address(0));<br>        }<br>        if (to == address(0)) {<br>            revert ERC20InvalidReceiver(address(0));<br>        }<br>        _update(from, to, value);<br>    }<br><br>    <br>    function _update(address from, address to, uint256 value) internal virtual {<br>        if (from == address(0)) {<br>            _totalSupply += value;<br>        } else {<br>            uint256 fromBalance = _balances[from];<br>            if (fromBalance &lt; value) {<br>                revert ERC20InsufficientBalance(from, fromBalance, value);<br>            }<br>            unchecked {<br>                _balances[from] = fromBalance - value;<br>            }<br>        }<br><br>        if (to == address(0)) {<br>            unchecked {<br>                _totalSupply -= value;<br>            }<br>        } else {<br>            unchecked {<br>                _balances[to] += value;<br>            }<br>        }<br><br>        emit Transfer(from, to, value);<br>    }<br>}</pre><h3>Enhancing Modularity with Interfaces</h3><p>Modularity in computer programming is the concept of breaking something big down into smaller, more manageable chunks. Decentralized apps are usually split up into multiple different smart contracts, each with their own specific purpose.</p><p>Some benefits of modularity are:</p><ul><li>The abstraction allows developers to focus on a high-level functionality, by not seeing all the code in one place.</li><li>Being broken down into little chunks allows for much easier maintenance and debugging, due to the code being well organized and not having to sift through thousands of lines of code, one by one.</li><li>A module can be modified without affecting the entire system. This is because if something did break when you are modifying the block, you know exactly where the issue is.</li></ul><p>You can think of each Interface as a building block Interfaces allow developers to re-use existing smart contracts and create new ones. The interface being the standard that the new contract will adhere to.</p><p>One common example are factory Contracts. Factory contracts are the widely used name for a smart contract that creates instances of existing smart contracts. For example, IUniswapV2Factory below. This interface is for interacting with the UniswapV2Factory contract. We can see the createPair function, which creates a new pair that can be traded on Uniswap and returns the new smart contract address. Each pair added simply adds another working block to the Uniswap protocol.</p><pre>pragma solidity &gt;=0.5.0;<br><br>interface IUniswapV2Factory {<br>  event PairCreated(address indexed token0, address indexed token1, address pair, uint);<br><br>  function createPair(address tokenA, address tokenB) external returns (address pair);<br>}</pre><h3>Upgradability and Interfaces</h3><p>Although blockchains immutability is one of their greatest strengths. It also poses as a restriction when talking about upgrading or handling bugs in dapp development. In traditional programming, if you found a bug, you would simply fix the bug and release a new version. In the blockchain world it is not quite that simple. Say we have a Defi app. All of the user information about their balances is kept on-chain in the form of state variables. Say then, that we found a critical bug, that would allow a hacker to drain the entire smart contract balance. How are the user balances protected?</p><figure><img alt="A diagram of the Smart Contract Proxy Upgrade Pattern showing the interaction between the user, Proxy Contract, Implementation Contracts, and Interface. The Proxy Contract is immutable, handles user interactions, and contains state variables and an upgrade function. Three mutable Implementation Contracts (V0, V1, V2) handle business rules and can be upgraded. An Interface lists all external functions and ensures consistency across Implementation Contracts." src="https://cdn-images-1.medium.com/max/1024/1*GNX2TK5R_aYkyf3DNII__Q.png" /><figcaption>A visualisation of a simple Proxy upgrade pattern.</figcaption></figure><p>The answer to creating truly upgradable smart contracts lies in separating a contracts logic from its storage. One way to do this is the proxy upgrade pattern. In its most basic form, it can be split into 3 contracts. I will be following the terminology from the <a href="https://docs.openzeppelin.com/upgrades-plugins/1.x/proxies">openZeppelin documentation about this pattern</a> for the titles of the different contracts.</p><p><strong><em>Proxy Contract</em></strong></p><ul><li>immutable</li><li>User interaction done through the proxy contract address</li><li>Stores all the state variables</li></ul><p><strong><em>Implementation Contract</em></strong></p><ul><li>Handles any logic, rules or functions that govorn how the dapp works (for example: max withdraw, minimum colateral amount etc)</li><li>Functions should adhere to the interfaces specification</li><li>When upgrading, it is this file that will change.</li></ul><p><strong><em>Implementation Contract Interface</em></strong></p><ul><li>All external functions from the implementation contract specified</li></ul><h4>What is the difference between a normal smart contract and a proxy smart contract?</h4><p>In a standard smart contract, state variables and business logic are all kept in the same file. To upgrade a standard single smart contract, you have to literally create a new contract. No state variables can be saved. A proxy contract, however acts as a gateway for user interaction, by delegating calls (asking another contract to make function calls on its behalf) to the implementation contract.</p><p>Below is a basic proxy upgrade pattern. The proxy contract, as you can see, has no specific function data specified at all. The magic is in the fallback function. Which throws the function call to the contract to which the proxy is pointing at. Essentially the call data is copied and sent to the implementation contract. Then the return data is retrieved and sent back to the caller.</p><p>This is based on the <a href="https://docs.openzeppelin.com/upgrades-plugins/1.x/proxies#proxy-forwarding">proxy forwarding section</a> of the OpenZeppelin proxy upgrade pattern article, I highly recommend reading this for a deeper understanding of upgradable smart contracts.</p><pre>// ILogicContract.sol<br>pragma solidity ^0.8.0;<br><br>interface ILogicContract {<br>    function getVersion() external view returns (string memory);<br>}<br><br>// --------------------------------------------------------------<br><br>// LogicContractV1.sol<br>pragma solidity ^0.8.0;<br><br>import &quot;./ILogicContract.sol&quot;;<br><br>contract LogicContractV1 is ILogicContract {<br>    function getVersion() external pure override returns (string memory) {<br>        return &quot;V1.0&quot;;<br>    }<br>}<br><br>// --------------------------------------------------------------<br><br>// ProxyContract.sol<br>pragma solidity ^0.8.0;<br><br>contract ProxyContract {<br>    address public implementation;<br><br>    // The constructor takes the implimentation contract address as input.<br>    constructor(address _initialImplementation) {<br>        implementation = _initialImplementation;<br>    }<br><br>    // Function to set the state variable to the new upgraded contract address.<br>    function upgradeImplementation(address _newImplementation) public {<br>        implementation = _newImplementation;<br>    }<br>    <br>    // <br>    fallback() external payable {<br>        // Retrieves the address of the current implementation contract.<br>        address _impl = implementation;<br>        require(_impl != address(0));<br>        <br>        // Assembly block allows for low-level operations .<br>        assembly {<br>            // (1) copy incoming call data<br>            calldatacopy(0, 0, calldatasize())<br>            <br>            // // (2) forward call to logic contract<br>            let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0)<br>            <br>            // (3) retrieve return data<br>            returndatacopy(0, 0, returndatasize())<br>            <br>            // (4) forward return data back to caller<br>            switch result<br>            case 0 { revert(ptr, size) }<br>            default { return(ptr, size) }<br>        }<br>    }<br>}</pre><p>The idea with the proxy upgrade pattern is that the proxy contract simply points at the Implementation contract and directs function calls from the proxy contract to the contract is it pointing at. So, from the front end, the contract address does not change. Meaning you do not have to tinker with anything on the front end when you upgrade the implementation contract to the next version. You simply point the proxy contract at the new contract.</p><p>The interface is used to standardize the functions in the dapp, to ensure the user experience will not be affected when upgrading the implementation contract. This is because everything from the user’s perspective is still the same. What goes in and what comes out is still the same.</p><p>Furthermore, because no state variables are stored on the implementation contract, the state of the dapp remains unchanged. Therefore, all user balances and anything like that are kept secure on the immutable blockchain.</p><h3>Best Practices and Considerations for Solidity Interfaces</h3><p>It is highly important to build effective and useful interfaces. Security considerations are also highly important. Here are some best practices to consider when developing your own Solidity interfaces. Along with some Security considerations and how to mitigate them.</p><h4>Interface Best Practices</h4><ol><li><strong>Clear and consistent Naming:</strong> Use clear and descriptive function names. This makes it easy for developers to understand the purpose of each element.</li><li><strong>Documentation: </strong>Document interfaces thoroughly. Include descriptions of each function, its parameters and its return values.</li><li><strong>Interface Minimalism:</strong> Keep interfaces as minimal as possible. Don’t use any functions that are not absolutely necessary for the contract to interact with other contracts. This reduced the chances of potential security exploits.</li><li><strong>Versioning: </strong>In the event that you do need to make changes to an interface, create a new version, to avoid breaking existing contracts that implement the interface.</li><li><strong>Security Considerations: </strong>Always consider security implications when designing interfaces. For example, avoid using interfaces to link to sensitive information.</li></ol><h4>Potential Security Implications of Improperly Implemented Interfaces</h4><ol><li><strong>Reentrancy Attacks:</strong> These occur when an external contract is called before status is updated. This can allow hackers to call a function, like a withdraw function, over and over again, in a single transaction.</li><li><strong>Upgradability Issues:</strong> If an interface is not designed with future upgrades in mind, It may not be possible to upgrade a contract without breaking its functionality.</li></ol><h4>Mitigating Security Risks</h4><ol><li><strong>Use Reentrancy Guards:</strong> Implement <a href="https://docs.openzeppelin.com/contracts/4.x/api/security#ReentrancyGuard">reentrancy guards</a> in your contracts.</li><li><strong>Design For Upgradability:</strong> Use patterns like the <a href="https://docs.openzeppelin.com/upgrades-plugins/1.x/proxies">proxy upgrade pattern</a> to make your contracts more upgradable.</li><li><strong>Code Audits:</strong> Regularly audit your smart contracts and interfaces. This way you can catch and fix vulnerabilities before they can be exploited.</li><li><strong>Community Feedback:</strong> There are always blockchain developers happy to give feedback in the community. I would recommend the <a href="https://discord.com/invite/cyfrin">cyfrin updrift discord</a>. They regularly share and discuss each others projects and ideas.</li></ol><p>By following these best practices and security considerations, you can design more effective solidity interfaces and mitigate potential risks before publishing your smart contracts.</p><h3>Conclusion</h3><p>So, to recap, Interfaces are a collection of external facing functions, from a particular smart contract. They define only what is necessary to interact with the functions. This abstraction turns each interface into a building block, which enhances modularity in programming Dapps. Interfaces also boost upgradability of smart contracts, by separating logic and storage, when used in upgrade patterns like the proxy upgrade pattern.</p><p>Best practices for designing and implementing are all geared towards clarity, minimalism and consistency across the naming and documentation of the functions included. In addition, ensure that security and upgradability implications have been thoroughly considered. Always audit your smart contracts before being released.</p><h4>Future outlook</h4><p>The blockchain space is constantly evolving. So too, will the role of interfaces. As decentralized apps continue to increase in size and complexity, effective interaction between different smart contract chunks will become ever more important.</p><p>Ai is at the forefront of innovation in 2024. In a blockchain context, this will probably mean huge, decentralized Ai models, which in turn will foster a plethora of new applications solving the problems of tomorrow. Interfaces will play a crucial role in how users and developers will interact with these systems and ensure they are safe and fair for everyone.</p><p>Today it is even more important for smart contract developers to continue their learning. Keeping up with the latest trends and tools is crucial to stay competitive and relevant in the ever-evolving world of smart contract development.</p><h3>Refrences</h3><p>Solidity Interfaces: <a href="https://docs.soliditylang.org/en/v0.8.25/contracts.html#interfaces">https://docs.soliditylang.org/en/v0.8.25/contracts.html#interfaces</a></p><p>Solidity function Visibility Specifiers and modifiers — <a href="https://docs.soliditylang.org/en/v0.8.25/cheatsheet.html#function-visibility-specifiers">https://docs.soliditylang.org/en/v0.8.25/cheatsheet.html#function-visibility-specifiers</a></p><p>OpenZeppelin Proxy Upgrade Pattern — <a href="https://docs.openzeppelin.com/upgrades-plugins/1.x/proxies">https://docs.openzeppelin.com/upgrades-plugins/1.x/proxies</a></p><p>OpenZeppelin Reentrancy Guard — <a href="https://docs.openzeppelin.com/contracts/4.x/api/security#ReentrancyGuard">https://docs.openzeppelin.com/contracts/4.x/api/security#ReentrancyGuard</a></p><h3>My socials</h3><p>Github — <a href="https://github.com/SimSimButDifferent">https://github.com/SimSimButDifferent</a></p><p>Twitter — <a href="https://twitter.com/Simsimbutdev">https://twitter.com/Simsimbutdev</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=baeb750cb37a" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/solidity-interfaces-facilitating-interaction-modularity-and-dapp-upgradability-baeb750cb37a">Solidity Interfaces — The Building Blocks of Modern dApps</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using structs and mappings to manage complex data in Solidity]]></title>
            <link>https://coinsbench.com/using-structs-and-mappings-to-manage-complex-data-in-solidity-7048c068ad58?source=rss-4ee435f783c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7048c068ad58</guid>
            <category><![CDATA[solidity-tutorial]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[mapping-solidity]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[structs-in-solidity]]></category>
            <dc:creator><![CDATA[Simeon Campbell]]></dc:creator>
            <pubDate>Fri, 01 Mar 2024 04:54:24 GMT</pubDate>
            <atom:updated>2024-03-28T09:47:11.273Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A computer generated image of a stack of metal filing cabinets with blue lights and cables coming out of them. The filing cabinets represent structs, a way to organize data in Solidity programming, and the cables and lights represent mappings, a way to store and retrieve data associated with structs." src="https://cdn-images-1.medium.com/max/1024/1*hUIXpEu25_gkQQcphnr4qA.jpeg" /></figure><p>Solidity is a statically typed programming language, used for writing smart contracts on Ethereum. The importance managing complex data, when writing smart contracts, can not be understated. This is because, the more steps a function has to take to complete, the higher the transaction cost will be, due to the computational cost, increasing with computation used. The most expensive is a change in the state of the blockchain, for example, writing data to the blockchain.</p><h3>Structs in Solidity</h3><p>Structs are a way to create new types in Solidity. These structs can include different data types. They can be used together with mappings and arrays, or even have mappings or arrays within them. Here is a simple struct of a user profile, from my OrderSystem.sol smart contract.</p><pre>struct UserProfile {<br>        // String name<br>        string name;<br>        <br>        // String age<br>        string age;<br>        <br>        // Array of current orders<br>        uint[] currentOrders;<br>        <br>        // Array of completed orders<br>        uint[] completedOrders;<br>    }</pre><h3>Mappings in solidity</h3><p>Mappings are ways of storing data by key. One data type is declared as a key for another type, being the data to be stored and retrieved. This is far less labor intensive than looping through an array, because, in a loop, the execution would read all of the data until it finds what it is looking for. Whereas with mappings you just need the key and without sifting through, you have the data.</p><pre>// mapping to store user profiles using address as key<br>mapping(address =&gt; UserProfile) private profiles;</pre><h3>Combining Structs and Mappings together</h3><p>Following on from the example above, I mapped the users address to their UserProfile struct, allowing quick, easy entry and retreival of user and order information. You can see it all in action with the two functions below. The first takes two strings, to add the name and age of the user. The second is a standard getter function, to retrieve this information, using the users address.</p><pre>// Sets the user profile details<br>function newUserProfile(string memory _name, string memory _age) public {<br>        <br>        profiles[msg.sender].name = _name;<br>        <br>        profiles[msg.sender].age = _age;<br>}<br><br>// Takes a users address as input, and returns user details.<br>function getProfile(<br>        address _user<br>    ) public view onlyOwner returns (string memory, string memory) {<br><br>        return (profiles[_user].name, profiles[_user].age);<br>    }</pre><h3>Benefits of using structs and mappings together</h3><p>The example below shows two different smart contracts. One uses a mapping to store and retrieve the data, whereas the other demonstrates the use of an array for the same purpose.</p><p>One noteable benefit is more organised and readable code. Storing the data in arrays, requires loops to sift through the data. Another is the noticable reduction in gas fees and transaction costs. I also noted the gas and execution fees for each function call. The storing of the user profile using a mapping saved around 38% on gas fees.</p><p>Another benefit is scalability and flexibility. The larger an array gets, the more computing power it will take to sift through the information. With mappings however there is just one key, that points to the exact piece of information, making it highly scalable.</p><pre>// SPDX-License-Identifier: MIT<br><br>pragma solidity ^0.8.0;<br><br>// -------------- MAPPING CONTRACT --------------<br>contract NewUserProfileMapping {<br><br>    // Maps an address to the users profile<br>    mapping(address =&gt; UserProfile) private profiles;<br><br>    // The user profile struct<br>    struct UserProfile {<br>            string name;<br>            string age;<br>    }<br><br>    // Sets the user profile details using a mapping<br>    function newUserProfileMap(string memory _name, string memory _age) public {<br>            <br>            profiles[msg.sender].name = _name;<br>            <br>            profiles[msg.sender].age = _age;<br>    }<br>    //gas 79582 gas<br>    // transaction cost 69201 gas <br>    // execution cost 47261 gas <br><br><br><br>    // Takes a users address as input, and returns user details.<br>    function getProfileMap(<br>            address _user<br>        ) public view returns (string memory, string memory) {<br><br>            return (profiles[_user].name, profiles[_user].age);<br>        }<br>    // execution cost 7104 gas (Cost only applies when called by a contract)<br><br>}<br><br>// -------------- ARRAY CONTRACT --------------<br>contract newUserProfileArray {<br><br>    // An array to store the user profile structs<br>    UserProfile[] private users;<br><br>    // The user profile struct<br>    struct UserProfile {<br>            string name;<br>            string age;<br>            address userAddress;<br>    }<br><br><br>    // Sets the user profile details and stores them in the array<br>    function newUserProfileArr(string memory _name, string memory _age) public {<br>            <br>            users.push(UserProfile(_name, _age, msg.sender));<br>    }<br>    // gas 130538 gas<br>    // transaction cost 113511 gas <br>    // execution cost 91571 gas <br><br><br><br>    // Takes a users address as input, loops through the array and returns user details.<br>    function getProfileArr() public view returns (string memory, string memory) {<br>            for (uint i = 0; i &lt; users.length; i++) {<br>                if (users[i].userAddress == msg.sender) {<br>                    return (users[i].name, users[i].age);<br>                }<br>            }<br>    <br>        return (&quot;&quot;, &quot;&quot;);<br>            <br>    }<br>    //  11885 gas (Cost only applies when called by a contract)<br>}</pre><h3>Challenges and Considerations</h3><h4>Gas Costs</h4><p>As you can see from the smart contract above, the gas saving when using mappings over arrays are absolutely huge. Even beyond the figures you can see above, when each function was only called once. You really see the difference when more new users are added to the array. Where the initial execution cost for a smart contract to call the getProfileLoop function was around 12,000 gas. Once I added 5 users to the array, the execution cost has nearly doubled to around 24,000. If you are new to smart contract development, I encourage you to paste the contract into remix and try it for yourself.</p><h4>Mapping Limitations</h4><p>One limitation of mappings is that we cannot be enumerated over. There are many cases in programming where, a list of data is highly necessary. In certain functions and cases, it is neccesary to iterate over everything in a list. One way of overcoming this is to use both together in a smart contract and reap the benefits of both. An example of this can be found in Patrick Collins’ smart contract lottery, where the address of all players in the lottery are kept in an array. You can <a href="https://github.com/SimSimButDifferent/hardhat-smartcontract-lottery-fcc/blob/master/contracts/lottery.sol">see the full code here</a>. This is so that a random number can be used as the array position to pick a winner. For beginners I would highly recommend following <a href="https://www.youtube.com/watch?v=gyMwXuJrbJQ&amp;t=60149s">Patrick Collins’ javascript course</a>, where he teaches you how to build your very own smart contract lottery, using chainlinks <a href="https://docs.chain.link/vrf">Verified Random Function</a>.</p><h3>Real world applications</h3><p>There are many decentralised applications that use structs and mappings. Some dapps that would benefit from the use of them would be: decentralised voting systems or marketplaces. Defi applications that offer lending, borrowing and insurance would also use them for management of user funds.</p><p>I created a simple order system, that used structs to manage user profiles and orders. However it is only arbitrary and purely for testing purposes. <a href="https://github.com/SimSimButDifferent/L5-SolidityOrderSystem">You can see the full code here</a>. I have not, as of the date of writing, coded it towards any real use case.</p><p>One example, is the well-known erc-20 token standard. If you want to look at the full contract code, you can <a href="https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol">see it here</a> on the openZeppelin github. The mapping below shows the mapping of an address, to a balance. This of course represents the user balance.</p><pre>// The users address has a balance value mapped to it.<br>mapping(address account =&gt; uint256) private _balances;<br><br>// Takes the address as input and returns the balance of that address.<br>function balanceOf(address account) public view virtual returns (uint256) {<br>        return _balances[account];<br>}</pre><p>The above is of course a very simple example of how the erc-20 smart contract utilises the balance. In the case of a transfer, the mapping would be used to take away a value from the ‘from’ user balance and add it to the ‘to’ user balance. Below is a simplified version of transfer function for reference.</p><pre>// Transfer function (simplified)<br>function transfer(address recipient, uint256 amount) public returns (bool) {<br>        require(_balances[msg.sender] &gt;= amount, &quot;Not enough tokens&quot;); <br><br>        _balances[msg.sender] -= amount;<br>        _balances[recipient] += amount;<br>        return true;<br>}</pre><h3>Conclusion</h3><p>To recap, structs are a way of creating new types in solidity, that can include several different data types. Mappings are a way of storing data using a key. You can combine structs and mappings together, for efficient information creation and retrieval. The benefits of using the two together are: noticably cleaner, tidier code. In addition to, more gas efficient smart contracts. All of this was tested using the two contracts <a href="https://medium.com/o/n4mrQRgV0aBMHEV5WQsn/s/Tienvu3ChtlMIblXrX2h/lesson-5/lesson-5-assignments-and-exercises/a1-using-structs-and-mappings-to-manage-complex-data-in-solidity#benefits-of-using-them-together">here</a>. On all metrics I tested in that particular context, mapping was the clear winner.</p><p>In conclusion, using mappings and structs together in smart contracts, is a fundimental and crucial concept for any smart contract developer to master. Doing this will enhance anyones ability to write clean, gas efficient and scalable smart contracts that will ultimately enhance the end user experience and smart contract security for the better.</p><h3>References</h3><p>Official Solidity Documentation — <a href="https://docs.soliditylang.org/en/v0.8.24/">https://docs.soliditylang.org/en/v0.8.24/</a></p><p>Open Zeppilin Github — <a href="https://github.com/OpenZeppelin">https://github.com/OpenZeppelin</a></p><p>Patrick Collins youtube channel — <a href="https://www.youtube.com/@PatrickAlphaC">https://www.youtube.com/@PatrickAlphaC</a></p><h3>My socials</h3><p>Github — <a href="https://github.com/SimSimButDifferent">https://github.com/SimSimButDifferent</a></p><p>Twitter — <a href="https://twitter.com/Simsimbutdev">https://twitter.com/Simsimbutdev</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7048c068ad58" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/using-structs-and-mappings-to-manage-complex-data-in-solidity-7048c068ad58">Using structs and mappings to manage complex data in Solidity</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>