<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Smart Contracts Archives - Be on the Right Side of Change</title>
	<atom:link href="https://blog.finxter.com/category/smart-contracts/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.finxter.com/category/smart-contracts/</link>
	<description></description>
	<lastBuildDate>Wed, 14 Jun 2023 19:33:32 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://blog.finxter.com/wp-content/uploads/2020/08/cropped-cropped-finxter_nobackground-32x32.png</url>
	<title>Smart Contracts Archives - Be on the Right Side of Change</title>
	<link>https://blog.finxter.com/category/smart-contracts/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Smart Contract to Store a Sentence on ETH</title>
		<link>https://blog.finxter.com/smart-contract-to-store-a-sentence-on-eth/</link>
		
		<dc:creator><![CDATA[Adam Schroeder]]></dc:creator>
		<pubDate>Wed, 14 Jun 2023 13:02:56 +0000</pubDate>
				<category><![CDATA[dApp]]></category>
		<category><![CDATA[Ethereum]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Smart Contracts]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1438484</guid>

					<description><![CDATA[<p>The following article is based on Adam&#8217;s CharmingData channel and GitHub repository. ♥️ In this tutorial, we will create, test, and deploy a smart contract called SimpleStorage. This contract will allow your users to create their own sentence and store it on the blockchain. It will also allow users to retrieve the last sentence stored ... <a title="Smart Contract to Store a Sentence on ETH" class="read-more" href="https://blog.finxter.com/smart-contract-to-store-a-sentence-on-eth/" aria-label="Read more about Smart Contract to Store a Sentence on ETH">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/smart-contract-to-store-a-sentence-on-eth/">Smart Contract to Store a Sentence on ETH</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p><em>The following article is based on Adam&#8217;s <a rel="noreferrer noopener" href="https://www.youtube.com/@CharmingData" data-type="URL" data-id="https://www.youtube.com/@CharmingData" target="_blank">CharmingData channel</a> and <a href="https://github.com/charmingdata/dApp-simple-storage" data-type="URL" data-id="https://github.com/charmingdata/dApp-simple-storage" target="_blank" rel="noreferrer noopener">GitHub</a> repository. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2665.png" alt="♥" class="wp-smiley" style="height: 1em; max-height: 1em;" /></em></p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="P1 - Create a Decentralized Application on the Blockchain for Beginners" width="937" height="527" src="https://www.youtube.com/embed/U4GursnbBGY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p></p>



<p>In this tutorial, we will create, test, and <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-deploy-smart-contract-to-polygon-in-brownie/" data-type="post" data-id="141343" target="_blank">deploy a smart contract</a> called <code>SimpleStorage</code>. This contract will allow your users to create their own sentence and store it on the blockchain. It will also allow users to retrieve the last sentence stored and display it on the page.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img fetchpriority="high" decoding="async" width="1024" height="525" src="https://blog.finxter.com/wp-content/uploads/2023/06/image-128-1024x525.png" alt="" class="wp-image-1439517" srcset="https://blog.finxter.com/wp-content/uploads/2023/06/image-128-1024x525.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/06/image-128-300x154.png 300w, https://blog.finxter.com/wp-content/uploads/2023/06/image-128-768x393.png 768w, https://blog.finxter.com/wp-content/uploads/2023/06/image-128-1536x787.png 1536w, https://blog.finxter.com/wp-content/uploads/2023/06/image-128.png 1747w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Consider the following <a href="https://blog.finxter.com/solidity-deep-dive-syllabus-video-tutorial-resources/" data-type="post" data-id="777532" target="_blank" rel="noreferrer noopener">Solidity</a> contract:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;

contract SimpleStorage {
    // Define a string called storeTheSentence. This is a state variable, which will be permanently stored in the blockchain.
    string storeTheSentence;

    constructor(string memory initialSentence) {
        // Assign the value of initialSentence to the storeTheSentence variable
        storeTheSentence = initialSentence;
    }

    // Declares a function called getSentence
    // Solidity funcions visibility: public, private, internal and external
    // Solidity view functions: https://www.geeksforgeeks.org/solidity-view-and-pure-functions/
    function getSentence() public view returns (string memory) {
        return storeTheSentence;
    }

    // Declare a function called setSentence
    // The function takes 1 input parameter, a string named newSentence, with the calldata data location in the Ethereum Virtual Machine
    function setSentence(string calldata newSentence) external {
        // Assign the value of newSentence to the storeTheSentence variable
        storeTheSentence = newSentence;
    }
}</pre>



<p>This is a simple smart contract written in Solidity, the most popular programming language for <a href="https://blog.finxter.com/introduction-to-smart-contracts-and-solidity/" data-type="post" data-id="445145" target="_blank" rel="noreferrer noopener">implementing smart contracts</a> on the Ethereum blockchain. The contract&#8217;s name is <code>SimpleStorage</code>, and it primarily focuses on storing and retrieving a string (a sequence of characters).</p>



<p>Here&#8217;s a brief breakdown of the contract:</p>



<ol class="wp-block-list">
<li><strong><a href="https://blog.finxter.com/state-variables-in-solidity/" data-type="post" data-id="765838" target="_blank" rel="noreferrer noopener">State variable</a> (<code>storeTheSentence</code>):</strong> This is a string variable that will store a sentence. This variable&#8217;s value is stored on the blockchain, making it a permanent, unerasable record.</li>



<li><strong>Constructor function:</strong> When the contract is first deployed to the <a href="https://blog.finxter.com/introduction-to-smart-contracts-and-solidity-part-3-blockchain-basics/" data-type="post" data-id="537705" target="_blank" rel="noreferrer noopener">Ethereum blockchain,</a> the constructor function is executed once. This function accepts one argument, a string (<code>initialSentence</code>), and assigns its value to the state variable <code>storeTheSentence</code>.</li>



<li><strong><code>getSentence()</code> function:</strong> This function is a <code>public view</code> function, which means anyone can call it to read the value of <code>storeTheSentence</code> without changing any data or state in the contract. It does not cost any gas to call this function because it doesn&#8217;t change the state of the blockchain.</li>



<li><strong><code>setSentence()</code> function:</strong> This function is declared as <code><a href="https://blog.finxter.com/solidity-internal-function-calls/" data-type="post" data-id="911324" target="_blank" rel="noreferrer noopener">external</a></code>, meaning it can only be called from outside the contract. It accepts one string argument (<code>newSentence</code>) and assigns its value to <code>storeTheSentence</code>, effectively updating the stored sentence. As this function modifies the state of the contract, it requires a transaction to be sent and will <a href="https://blog.finxter.com/introduction-to-ethereums-gas-in-solidity-development/" data-type="post" data-id="37644" target="_blank" rel="noreferrer noopener">cost gas</a> to execute.</li>
</ol>



<p>In essence, this contract allows anyone to store a sentence on the Ethereum blockchain and retrieve it. Due to the permanent and public nature of blockchain storage, the stored sentence would be visible to anyone and cannot be erased or modified once set (except by calling the <code>setSentence</code> function again).</p>



<p>Let&#8217;s learn how to set it up in a step-by-step manner next. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h2 class="wp-block-heading">Backend</h2>



<ol class="wp-block-list">
<li>Open the terminal (command line), create two new folders called <code>simple-storage</code> and <code>backend</code>. Go into the <code>backend</code> folder.</li>
</ol>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">mkdir simple-storage
cd simple-storage
mkdir backend
cd backend
</pre>



<ol class="wp-block-list" start="2">
<li>Set up a Hardhat project. Install the necessary libraries, by typing in the terminal:</li>
</ol>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">npm init --yes
npm install --save-dev --save-exact hardhat@2.14.0
npm install dotenv
</pre>



<ol class="wp-block-list" start="3">
<li>This library might be necessary to install as well, especially if you&#8217;re a Windows user:</li>
</ol>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">npm install --save-dev @nomicfoundation/hardhat-toolbox@2
</pre>



<ol class="wp-block-list" start="4">
<li>Make sure you are still in the <code>backend</code> directory. Now, create a sample contract project by typing in the terminal:</li>
</ol>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">npx hardhat
</pre>



<ul class="wp-block-list">
<li>Select <code>Create a Javascript Project</code>. Don&#8217;t change anything in the Hardhat project root, just click enter. Yes, add a <code>.gitignore</code>.</li>
</ul>



<ol class="wp-block-list" start="5">
<li>Open the <code>backend</code> folder and remove any present contracts inside the <code>contracts</code> folder. Insert your <code>SimpleStorage</code> contract.</li>



<li>Now, inside the <code>scripts</code> folder, replace the contect of the <code>deploy.js</code> file with the <a href="https://github.com/charmingdata/dApp-simple-storage/blob/main/backend/scripts/deploy.js" target="_blank" rel="noreferrer noopener">deploy.js code from this project</a>.</li>



<li>Create a <code>.env</code> file inside the <code>backend</code> folder. This will be used to store your wallet key and your Quicknode endpoint. A QuickNode API endpoint gives you quick access to a network of nodes. </li>
</ol>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="Metamask Wallet - Quick Installation and Set up" width="937" height="527" src="https://www.youtube.com/embed/kHF70SWFTYU?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<ul class="wp-block-list">
<li>Add these two lines inside the <code>.env</code> file, and update the content inside the quotation marks:</li>
</ul>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">QUICKNODE_HTTP_URL="your-quicknode-http-provider-goes-here-inside-the-quotation-marks"
PRIVATE_KEY="your-wallet-private-key-goes-here-inside-the-quotation-marks"
</pre>



<ol class="wp-block-list" start="8">
<li>Open the <code>hardhat.config.js</code> file inside the <code>backend</code> folder and replace its content with the <a href="https://github.com/charmingdata/dApp-simple-storage/blob/main/backend/hardhat.config.js">hardhat.config.js code from this project</a>.</li>



<li>Compile your Contract by going back to your terminal (ensure you are in the <code>backend</code> directory). And type:</li>
</ol>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">npx hardhat compile
</pre>



<ul class="wp-block-list">
<li>Every time you modify your contract (<code>SimpleStorage</code>), you will have to repeat the above compile step.</li>
</ul>



<ol class="wp-block-list" start="10">
<li>With your contract compiled, now we can deploy it to the sepolia testnet. In your terminal type:</li>
</ol>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">npx hardhat run scripts/deploy.js --network sepolia
</pre>



<p>Save the contract address that was printed out. Go to <a href="https://sepolia.etherscan.io/" target="_blank" rel="noreferrer noopener">https://sepolia.etherscan.io/</a> and insert the contract address into the Explorer input field. Take some time to explore the transaction details of your contract.</p>



<ul class="wp-block-list">
<li>Save this address somewhere. Don&#8217;t lose it!</li>
</ul>



<h2 class="wp-block-heading">Testing</h2>



<p>Every Contract should be tested before deployment. In this case we deployed first becuause it&#8217;s freaking exciting to see our contract deployed. But we need tests to make sure our contract has no bugs and is secure.</p>



<ol class="wp-block-list">
<li>Open the <code>test</code> folder and remove any present files inside of it. Create a new file called <code>testing.js</code>, and insert the <a href="https://github.com/charmingdata/dApp-simple-storage/blob/main/backend/test/testing.js">testing.js code from this project</a>.</li>



<li>Go back to the terminal, make sure you&#8217;re in the <code>backend</code> directory, and type:</li>
</ol>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">npx hardhat test
</pre>



<h2 class="wp-block-heading">Frontend</h2>



<p>In this section of the tutorial we&#8217;ll create a dApp (decentralized app) that will connect to your contract and its functions, allowing you to interact with it. In other words, we&#8217;re building an interface for the contract.</p>



<ol class="wp-block-list">
<li>Open the terminal (command line) and go into the <code>simple-storage</code> directory. Create a sample Next app by typing:</li>
</ol>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">npx create-next-app@13 frontend

</pre>



<ul class="wp-block-list">
<li>Make sure to choose these settings.</li>
</ul>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="835" height="183" src="https://blog.finxter.com/wp-content/uploads/2023/06/image-125.png" alt="" class="wp-image-1438553" srcset="https://blog.finxter.com/wp-content/uploads/2023/06/image-125.png 835w, https://blog.finxter.com/wp-content/uploads/2023/06/image-125-300x66.png 300w, https://blog.finxter.com/wp-content/uploads/2023/06/image-125-768x168.png 768w" sizes="auto, (max-width: 835px) 100vw, 835px" /></figure>
</div>


<ol class="wp-block-list" start="2">
<li>Before running the sample app, you&#8217;ll need to remove the <code>.git</code> file that was automatically created inside the new <code>frontend</code> folder. To remove the file, type this command inside the terminal:</li>
</ol>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Linux / macOS
cd frontend
rm -rf .git

# Windows
cd frontend
rm -r -fo .git
</pre>



<ol class="wp-block-list" start="3">
<li>Install these packages using your terminal (you should still be in the <code>frontend</code> directory).</li>
</ol>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">npm install web3modal
npm install ethers@5
</pre>



<ol class="wp-block-list" start="4">
<li>Create a new folder called <code>constants</code> within the <code>frontend</code> directory. Inside the <code>constants</code> folder create a new file called <code>index.js</code>. Add the following code inside <code>index.js</code>.</li>
</ol>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">export const MY_CONTRACT_ADDRESS = "MY_CONTRACT_ADDRESS";
export const abi = MY_ABI;
</pre>



<ul class="wp-block-list">
<li>Replace the <code>MY_ABI</code> with the <a href="https://blog.finxter.com/solidity-reference-types-array-slices-and-structs/" data-type="post" data-id="829701" target="_blank" rel="noreferrer noopener">abi array</a> that can be found in the following file: <code>backend/artifacts/contracts/SimpleStorage.json</code></li>



<li>Replace the <code>MY_CONTRACT_ADDRESS</code> with the address of the contract that you deployed in the Backend section of this tutorial.</li>
</ul>



<ol class="wp-block-list" start="5">
<li>Finally, to build the interface of the contract, open the <code>index.js</code> file under the <code>pages</code> folder (in the <code>frontend</code> folder) and replace its content with the <a href="https://github.com/charmingdata/dApp-simple-storage/blob/main/frontend/pages/index.js">index.js code from this project</a>.</li>



<li>Add the Charming Data images using the instructions below. Once you understand how to add images to your app, feel free to replace with your own images, in which case you would need to update the images&#8217; names inside the <code>pages/index.js</code> file (lines 143 &amp; 154)</li>
</ol>



<ul class="wp-block-list">
<li>Add the <a href="https://raw.githubusercontent.com/charmingdata/dApp-simple-storage/main/frontend/public/logo-charmingdata-small.ico">logo-charmingdata-small.ico</a> and <a href="https://github.com/charmingdata/dApp-simple-storage/blob/main/frontend/public/logocharmingdata.png">logocharmingdata.png</a> to the public folder inside the frontend directory. Do not change image names.</li>
</ul>



<ol class="wp-block-list" start="7">
<li>Go back to your terminal; make sure your in the <code>frontend</code> directory and type:</li>
</ol>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">npm run dev
</pre>



<h2 class="wp-block-heading">Sharing your dApp with others</h2>



<p>We will use Vercel to deploy the frontend of our contract. Before starting with Vercel you will need to create a GitHub account if you don&#8217;t have one and push your code into a GitHub repository:</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Push Code to your GitHub Account - Under 3 Minutes" width="937" height="527" src="https://www.youtube.com/embed/vpRkAoCqX3o?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<ol class="wp-block-list">
<li>Once your repositoy has been created in Github, go to <a href="https://vercel.com/login">Vercel</a> and create an account by connecting your GitHub account.</li>



<li>Once your GitHub account is connected, click the button to add a new project in Vercel.</li>
</ol>



<ul class="wp-block-list">
<li>add your repository (you might have to import it as well)</li>
</ul>



<ol class="wp-block-list" start="3">
<li>Select <code>Next.js</code> as the Framework Preset. In the Root Directory click Edit to select <code>frontend</code>.</li>



<li>Click Deploy, and wait a few minutes. When done, click your domain link to see your dApp.</li>
</ol>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>The previous text was originally written by Adam from <a href="https://github.com/charmingdata/dApp-simple-storage" data-type="URL" data-id="https://github.com/charmingdata/dApp-simple-storage" target="_blank" rel="noreferrer noopener">CharmingData</a>.</p>
<p>The post <a href="https://blog.finxter.com/smart-contract-to-store-a-sentence-on-eth/">Smart Contract to Store a Sentence on ETH</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Solidity Function Constructors &#8211; A Helpful Simplified Guide with Video</title>
		<link>https://blog.finxter.com/solidity-function-constructors-a-helpful-simplified-guide-with-video/</link>
		
		<dc:creator><![CDATA[Matija Horvat]]></dc:creator>
		<pubDate>Tue, 04 Apr 2023 14:54:41 +0000</pubDate>
				<category><![CDATA[dApp]]></category>
		<category><![CDATA[Ethereum]]></category>
		<category><![CDATA[Smart Contracts]]></category>
		<category><![CDATA[Solidity]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1266895</guid>

					<description><![CDATA[<p>In this article, we&#8217;ll learn about function constructors, a Solidity language feature enabling us to execute a function during smart contract creation. It&#8217;s part of our long-standing tradition to make this (and other) articles a faithful companion or a supplement to the official Solidity documentation. We&#8217;ll base this article on the original Solidity programming language ... <a title="Solidity Function Constructors &#8211; A Helpful Simplified Guide with Video" class="read-more" href="https://blog.finxter.com/solidity-function-constructors-a-helpful-simplified-guide-with-video/" aria-label="Read more about Solidity Function Constructors &#8211; A Helpful Simplified Guide with Video">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/solidity-function-constructors-a-helpful-simplified-guide-with-video/">Solidity Function Constructors &#8211; A Helpful Simplified Guide with Video</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In this article, we&#8217;ll learn about function constructors, a Solidity language feature enabling us to execute a function during smart contract creation.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Solidity Function Constructors - A Helpful Simplified Guide with Video" width="937" height="703" src="https://www.youtube.com/embed/IL9hIKJCQYs?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/04/Folie2.jpg" alt="" class="wp-image-1266971" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/Folie2.jpg 960w, https://blog.finxter.com/wp-content/uploads/2023/04/Folie2-300x169.jpg 300w, https://blog.finxter.com/wp-content/uploads/2023/04/Folie2-768x432.jpg 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>



<p>It&#8217;s part of our long-standing tradition to make this (and other) articles a faithful companion or a supplement to the official Solidity documentation. We&#8217;ll base this article on the original <a rel="noreferrer noopener" href="https://docs.soliditylang.org/en/v0.8.15/contracts.html#constructors" data-type="URL" data-id="https://docs.soliditylang.org/en/v0.8.15/contracts.html#constructors" target="_blank">Solidity programming language</a> content.</p>



<h2 class="wp-block-heading">Conceptual Overview</h2>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/04/Folie3.jpg" alt="" class="wp-image-1266974" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/Folie3.jpg 960w, https://blog.finxter.com/wp-content/uploads/2023/04/Folie3-300x169.jpg 300w, https://blog.finxter.com/wp-content/uploads/2023/04/Folie3-768x432.jpg 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>



<p>A constructor is a Solidity language feature that makes it possible to attach a specific behavior, i.e., a function, to the beginning of the <a rel="noreferrer noopener" href="https://blog.finxter.com/smart-contracts-discover-how-to-create-them-directly-and-indirectly/" data-type="post" data-id="978963" target="_blank">smart contract</a> lifecycle. It is executed only once &#8211; when a contract&#8217;s instance is created. A constructor is the right place to define the contract initialization code.</p>



<p>The initialization cycle starts with the state variables: in case of an inline initialization, they are set to their explicitly specified values. Otherwise, the state variables are set to their type-determined default value when inline initialization is omitted. The next step of the initialization cycle is the execution of the constructor code.</p>



<p>After the constructor execution concludes, the final code of the contract is ready and deployed to the blockchain. This is a good place for us to discuss the cost of the contract deployment, which is proportional to the length of the code. </p>



<p>When we say &#8220;code&#8221;, we imply all the functions that make up the public interface, i.e., functions whose visibility modifiers are <code>public</code> or <code>external</code>. </p>



<p>Besides, all the functions can be reached via function calls through the public interface functions. In contrast, the contract cost does not include the constructor code or the functions only called from the constructor and whose visibility is set to <code>internal</code>.</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f469-200d-1f4bb.png" alt="👩‍💻" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/solidity-internal-function-calls/" data-type="URL" data-id="https://blog.finxter.com/solidity-internal-function-calls/" target="_blank" rel="noreferrer noopener">Solidity Function Calls – Internal and External</a></p>



<h2 class="wp-block-heading">Default Constructor</h2>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/04/Folie4.jpg" alt="" class="wp-image-1266973" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/Folie4.jpg 960w, https://blog.finxter.com/wp-content/uploads/2023/04/Folie4-300x169.jpg 300w, https://blog.finxter.com/wp-content/uploads/2023/04/Folie4-768x432.jpg 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>



<p>As with most of our examples in previous articles, if we omit the constructor, the <a href="https://blog.finxter.com/how-to-install-the-solidity-compiler-overview-videos/" data-type="post" data-id="716526" target="_blank" rel="noreferrer noopener">compiler</a> will imply there&#8217;s a default constructor, which has no arguments and no body: <code>constructor() {}</code>, as showcased in this simple example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 &lt;0.9.0;

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 &lt;0.9.0;

contract A {

    // A default constructor can be omitted.
    constructor() {}
}
</pre>



<p>The sole purpose of a default constructor is to initialize the <a href="https://blog.finxter.com/state-variables-in-solidity/" data-type="post" data-id="765838" target="_blank" rel="noreferrer noopener">state variables</a> with their default, type-dependant values.</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Note</strong>: Don&#8217;t forget to include the <a href="https://blog.finxter.com/solidity-layout-pragmas-importing-and-comments/" data-type="post" data-id="716191" target="_blank" rel="noreferrer noopener">pragma directive</a> before trying each of the following examples; I&#8217;m deliberately omitting it to avoid unnecessary code duplication.</p>



<h2 class="wp-block-heading">Regular Constructor</h2>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/04/Folie5.jpg" alt="" class="wp-image-1266975" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/Folie5.jpg 960w, https://blog.finxter.com/wp-content/uploads/2023/04/Folie5-300x169.jpg 300w, https://blog.finxter.com/wp-content/uploads/2023/04/Folie5-768x432.jpg 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>



<p>First, we&#8217;ll take a look at a simplified example of a constructor that initializes the state variables to fixed values through a process called <strong><em>inline initialization</em></strong>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">contract A {
    uint public a;

    constructor() {
        a = 5;
    }
}
</pre>



<p>In this example, our state variable <code>A</code> is initialized to a fixed value of 5. Of course, this approach is excessive since we could have gotten exactly the same effect simply by doing the following:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">contract A {
    uint public a = 6;
}
</pre>



<p>However, these two examples are hard-coded and don&#8217;t demonstrate the real usefulness of constructors, but I showed them for the sake of completeness and better understanding. The following example will start to unveil the true versatility and purpose behind using constructors:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">contract A {
    uint public a;

    constructor(uint a_) {
        a = a_;
    }
}

contract B {
    A contract_A = new A(22);
    uint public a = contract_A.a();
}
</pre>



<p>Although more complex, this example shows how to declare a constructor that takes an argument via its parameter <code>uint _a</code>. This way, we can <a href="https://blog.finxter.com/smart-contracts-discover-how-to-create-them-directly-and-indirectly/" data-type="post" data-id="978963" target="_blank" rel="noreferrer noopener">dynamically instantiate our contract</a>, and that&#8217;s where the true power of parametrized constructors lies.</p>



<p>First, we declared contract A with a parametrized constructor. Then, we declared a new contract B in which we created an instance of contract A called <code>contract_A</code> by passing it argument 22. Finally, we assigned the value of the state variable <code>contract_A.a</code> to the state variable <code>b</code> by calling its getter function to confirm that <code>contract_A</code> is dynamically instantiated to the value of the given argument.</p>



<p>An even nicer, elegant example with the same effect can be achieved simply by deriving contract B from contract A by giving it an argument:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">contract A {
    uint public a;

    constructor(uint a_) {
        a = a_;
    }
}

contract B is A(22) {
}
</pre>



<h2 class="wp-block-heading"><a></a>Conclusion</h2>



<p>In this article, we learned about contract constructors.</p>



<p>First, we made a conceptual overview of a constructor in Solidity.</p>



<p>Second, we explained what a default constructor is.</p>



<p>Third, we showed how regular constructors can be declared and used through several illustrative, simple examples.</p>



<h2 class="wp-block-heading">What&#8217;s Next?</h2>



<p>This tutorial is part of our extended Solidity documentation with videos and more accessible examples and explanations. You can navigate the series here (all links open in a new tab):</p>



<div class="wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex">
<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://blog.finxter.com/solidity-function-overloading/" target="_blank" rel="noreferrer noopener"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f448.png" alt="👈" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Prev Tutorial</a></div>



<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://blog.finxter.com/solidity-deep-dive-syllabus-video-tutorial-resources/" target="_blank" rel="noreferrer noopener"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/261d.png" alt="☝" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Syllabus</a></div>



<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://blog.finxter.com/solidity-deep-dive-syllabus-video-tutorial-resources/" target="_blank" rel="noreferrer noopener"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Next Tutorial</a></div>
</div>
<p>The post <a href="https://blog.finxter.com/solidity-function-constructors-a-helpful-simplified-guide-with-video/">Solidity Function Constructors &#8211; A Helpful Simplified Guide with Video</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Solidity Function Overloading</title>
		<link>https://blog.finxter.com/solidity-function-overloading/</link>
		
		<dc:creator><![CDATA[Matija Horvat]]></dc:creator>
		<pubDate>Tue, 04 Apr 2023 13:46:16 +0000</pubDate>
				<category><![CDATA[dApp]]></category>
		<category><![CDATA[Ethereum]]></category>
		<category><![CDATA[Smart Contracts]]></category>
		<category><![CDATA[Solidity]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1266817</guid>

					<description><![CDATA[<p>In this article, we&#8217;ll learn about function overloading 🎛️🔁👷‍♂️💻🚀, a useful and interesting feature in the Solidity programming language. It&#8217;s part of our long-standing tradition to make this (and other) articles a faithful companion or a supplement to the official Solidity documentation. We&#8217;ll base this article on the original Solidity programming language content. Overview Function ... <a title="Solidity Function Overloading" class="read-more" href="https://blog.finxter.com/solidity-function-overloading/" aria-label="Read more about Solidity Function Overloading">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/solidity-function-overloading/">Solidity Function Overloading</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In this article, we&#8217;ll learn about <strong>function overloading</strong> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f39b.png" alt="🎛" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f501.png" alt="🔁" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f477-200d-2642-fe0f.png" alt="👷‍♂️" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4bb.png" alt="💻" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" />, a useful and interesting feature in the Solidity programming language.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Solidity Function Overloading" width="937" height="703" src="https://www.youtube.com/embed/h_41AphHuLM?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>It&#8217;s part of our long-standing tradition to make this (and other) articles a faithful companion or a supplement to the official Solidity documentation. We&#8217;ll base this article on the <a rel="noreferrer noopener" href="https://docs.soliditylang.org/en/v0.8.15/contracts.html#function-overloading" data-type="URL" data-id="https://docs.soliditylang.org/en/v0.8.15/contracts.html#function-overloading" target="_blank">original Solidity programming language content</a>.</p>



<h2 class="wp-block-heading"><a></a>Overview</h2>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-38.png" alt="" class="wp-image-1266867" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-38.png 960w, https://blog.finxter.com/wp-content/uploads/2023/04/image-38-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-38-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>



<p class="has-global-color-8-background-color has-background">Function overloading is a feature that enables us to define more than one function with the same name but with different combinations of function parameters in terms of their number and type. </p>



<p>Roughly speaking, we&#8217;d usually go with the function overloading approach when we need:</p>



<ul class="wp-block-list">
<li>Different variants of the same base functionality or business logic, i.e. a function performing the addition of integers vs floating-point numbers;</li>



<li>Specialized versions of one generalized base functionality, i.e., a function adding two integers instead of ten integers. In this case, a specialized version of the base functionality can be considered a function wrapper because it contains a call to the base function with some parameters commonly hardcoded to default values.</li>
</ul>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-39.png" alt="" class="wp-image-1266868" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-39.png 960w, https://blog.finxter.com/wp-content/uploads/2023/04/image-39-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-39-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Note</strong>: In a sense, overloading can also be applied to inherited functions, but in that case, we refer to it as <em>function overriding</em>. When a function overrides an inherited function, it has the same signature as the overridden function, i.e., the same function name, parameter number, and parameter type. Effectively, the overriding function redefines the inherited (base) function behavior, but only on a sub-class level. </p>



<p>With that said, let&#8217;s just remember that function overloading produces more variants of the same-name function, while function overriding just redefines an inherited function.</p>



<p>Function overloading <strong><em>cannot</em></strong> be achieved by renaming the function parameters, i.e., function parameter names don&#8217;t affect the function signature and cannot produce an overloaded function.</p>



<h2 class="wp-block-heading">Example &#8211; Function Overloading</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-40.png" alt="" class="wp-image-1266871" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-40.png 960w, https://blog.finxter.com/wp-content/uploads/2023/04/image-40-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-40-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>
</div>


<p>The following example shows how function overloading works. As we always do, we&#8217;ll analyze it segment by segment.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.16 &lt;0.9.0;</pre>



<p>A regular contract defines two functions with the same name, but with a different number of parameters and parameter types.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">contract A {</pre>



<p>The first function f takes only one parameter, value, of type uint. The function behavior is extremely simple: it just returns the received parameter value by assigning it to the output parameter out.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    function f(uint value) public pure returns (uint out) {
        out = value;
    }
</pre>



<p>The second function <code>f</code> takes one more parameter, really, of type <code><a href="https://blog.finxter.com/solidity-boolean-and-integer-types-a-helpful-guide-with-video/" data-type="post" data-id="728241" target="_blank" rel="noreferrer noopener">bool</a></code>, but also keeps the same parameter from the first function <code>f</code> definition, value.</p>



<p>The function behavior is just a shade more complex: it conditionally returns the received parameter value by assigning it to the output parameter out, i.e., if the parameter really is set to true. </p>



<p>Otherwise, the parameter out returns the default value, determined from its variable type <code>uint</code>, which is 0.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    function f(uint value, bool really) public pure returns (uint out) {
        if (really)
            out = value;
    }
}
</pre>



<h2 class="wp-block-heading">Example &#8211; Function Overloading in External Interface</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-41.png" alt="" class="wp-image-1266872" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-41.png 960w, https://blog.finxter.com/wp-content/uploads/2023/04/image-41-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-41-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>
</div>


<p>Before we analyze another example of function overloading specific to external interfaces, let&#8217;s shortly discuss what&#8217;s so special about external interfaces.</p>



<p>Functions in external interfaces introduce two kinds of types: <strong>Solidity types</strong> and <strong>external (ABI) types</strong>. For instance, Solidity can have multiple <a href="https://blog.finxter.com/solidity-members-of-address-types-and-type-information/" data-type="post" data-id="896974" target="_blank" rel="noreferrer noopener">address types</a>, such as <code>contract</code> and <code>address</code>. However, from the ABI perspective, the mentioned types are regarded as the same type, which would cause an error during the compilation if used in an overloading attempt, as in our example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.16 &lt;0.9.0;
</pre>



<p>A very simple example showing an attempted function overloading with different Solidity types, but the same (after compilation) ABI types.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">contract A {</pre>



<p>Input and output type <code>B</code> is contract type from the Solidity perspective, but it&#8217;s also address type from an ABI perspective.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    function f(B value) public pure returns (B out) {
        out = value;
    }
</pre>



<p>Input and output parameter types address are the same from the Solidity perspective and from the ABI perspective in both overloaded functions.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    function f(address value) public pure returns (address out) {
        out = value;
    }
}
</pre>



<p>Declares the placeholder contract <code>B</code> for parameter typing purposes.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">contract B {
}</pre>



<p>After compilation, both functions are declared as public (<strong>public =&nbsp; external + internal</strong>), take the same overloaded form and therefore cause an <a href="https://blog.finxter.com/solidity-error-handling-with-assert-require-and-revert-functions/" data-type="post" data-id="1257859" target="_blank" rel="noreferrer noopener">error</a>, since they both have input and output parameter types declared as <code>address</code>, hence causing improper overloading from ABI (compiler output) perspective:</p>



<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26a1.png" alt="⚡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <code><strong>TypeError: Function overload clash during conversion to external types for arguments.</strong></code></p>



<h2 class="wp-block-heading"><a></a>Implementation</h2>



<p>Now that we know what function overloading is, let&#8217;s see how it works. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-42.png" alt="" class="wp-image-1266873" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-42.png 960w, https://blog.finxter.com/wp-content/uploads/2023/04/image-42-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-42-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>
</div>


<p>A <strong>function call</strong> to an overloaded function is resolved by the function name and argument matching, meaning the right function in the current scope is selected depending on its name and the arguments in the function call. </p>



<p><strong>Specifically, overloaded functions are selected as candidates if their arguments are implicitly convertible to the expected parameter types.</strong> Of course, if the function parameter conversion fails for only one parameter, the resolution fails and the function candidate is entirely dismissed.</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Note</strong>: Function return parameters (types) are not part of the function resolution process.</p>



<p>To make the story of implicit conversion more clear, we&#8217;ll look at the example below:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.16 &lt;0.9.0;

contract A {
    function f(uint8 val) public pure returns (uint8 out) {
        out = val;
    }

    function f(uint256 val) public pure returns (uint256 out) {
        out = val;
    }
}
</pre>



<p>In this example, we have a function <code>f</code> overloaded in two instances: the first instance takes and returns a variable of <code>uint8</code> type, while the other instance takes and returns a variable of <code>uint256</code> type.</p>



<p>A call <code>f(50)</code> would return a type error because it&#8217;s ambiguous, i.e., it cannot precisely determine the right function instance since the argument 50 can be implicitly converted to match both functions. However, when we make a call <code>f(256)</code>, a function <code>f(uint256)</code> is the only one that matches the result of the implicit conversion of argument 256, so this call proceeds without any errors.</p>



<h2 class="wp-block-heading"><a></a>Conclusion</h2>



<p>This article taught us about function overloading and compared it with function overriding.</p>



<p>First, we made an overview to understand what we&#8217;re talking about.</p>



<p>Second, we went through an example showing how function overloading looks in its simplest form.</p>



<p>Third, we studied a bit more complex example of function overloading with regard to external interfaces.</p>



<p>Fourth, we went into just a bit more detail, showing how the overloaded function resolution works under the hood.</p>



<h2 class="wp-block-heading">What&#8217;s Next?</h2>



<p>This tutorial is part of our extended Solidity documentation with videos and more accessible examples and explanations. You can navigate the series here (all links open in a new tab):</p>



<div class="wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex">
<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://blog.finxter.com/soliditys-fallback-function-a-simple-guide/" target="_blank" rel="noreferrer noopener"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f448.png" alt="👈" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Prev Tutorial</a></div>



<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://blog.finxter.com/solidity-deep-dive-syllabus-video-tutorial-resources/" target="_blank" rel="noreferrer noopener"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/261d.png" alt="☝" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Syllabus</a></div>



<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://blog.finxter.com/solidity-function-constructors-a-helpful-simplified-guide-with-video/" target="_blank" rel="noreferrer noopener"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Next Tutorial</a></div>
</div>
<p>The post <a href="https://blog.finxter.com/solidity-function-overloading/">Solidity Function Overloading</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Solidity&#8217;s Fallback Function &#8211; A Simple Guide</title>
		<link>https://blog.finxter.com/soliditys-fallback-function-a-simple-guide/</link>
		
		<dc:creator><![CDATA[Matija Horvat]]></dc:creator>
		<pubDate>Tue, 04 Apr 2023 12:32:21 +0000</pubDate>
				<category><![CDATA[dApp]]></category>
		<category><![CDATA[Ethereum]]></category>
		<category><![CDATA[Smart Contracts]]></category>
		<category><![CDATA[Solidity]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1266535</guid>

					<description><![CDATA[<p>In this article, we will focus on the second topic of the interesting pair, the fallback function, as a follow-up on the receive ether function discussed in the previous article. It&#8217;s part of our long-standing tradition to make this (and other) articles a faithful companion, or a supplement to the official Solidity documentation. Overview The ... <a title="Solidity&#8217;s Fallback Function &#8211; A Simple Guide" class="read-more" href="https://blog.finxter.com/soliditys-fallback-function-a-simple-guide/" aria-label="Read more about Solidity&#8217;s Fallback Function &#8211; A Simple Guide">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/soliditys-fallback-function-a-simple-guide/">Solidity&#8217;s Fallback Function &#8211; A Simple Guide</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In this article, we will focus on the second topic of the interesting pair, the <strong><em>fallback function</em></strong>, as a follow-up on the <a href="https://blog.finxter.com/solidity-receive-ether-function/" data-type="post" data-id="1266480" target="_blank" rel="noreferrer noopener">receive ether function discussed in the previous article</a>.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Solidity&#039;s Fallback Function - A Simple Guide" width="937" height="703" src="https://www.youtube.com/embed/10ZiPPVaVEc?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>It&#8217;s part of our long-standing tradition to make this (and other) articles a faithful companion, or a supplement to the <a rel="noreferrer noopener" href="https://docs.soliditylang.org/en/v0.8.15/contracts.html#fallback-function" data-type="URL" data-id="https://docs.soliditylang.org/en/v0.8.15/contracts.html#fallback-function" target="_blank">official Solidity documentation</a>.</p>



<h2 class="wp-block-heading">Overview</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-30.png" alt="" class="wp-image-1266755" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-30.png 960w, https://blog.finxter.com/wp-content/uploads/2023/04/image-30-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-30-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>
</div>


<p>The purpose behind a fallback function, as the name suggests, is to serve as a function that executes when:</p>



<ul class="wp-block-list">
<li>A contract receives a call but cannot match any other function by the function signature;</li>



<li>When no data is supplied with the contract call and the contract doesn&#8217;t have the <a href="https://blog.finxter.com/solidity-receive-ether-function/" data-type="post" data-id="1266480" target="_blank" rel="noreferrer noopener">receive Ether function</a>.</li>
</ul>



<p>In a way, we can consider a fallback function as a default function that gets executed in the situations listed above.</p>



<h2 class="wp-block-heading">Implementation</h2>



<p>A fallback function must be declared with external visibility. One more important and potentially needed option is declaring a fallback function as virtual, meaning it can be overridden in an inheriting contract. </p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-31.png" alt="" class="wp-image-1266756" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-31.png 960w, https://blog.finxter.com/wp-content/uploads/2023/04/image-31-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-31-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>
</div>


<p>Declaring a fallback function as <code>payable</code> is possible, but not necessary; we&#8217;d declare it as <code>payable</code> only if the function must be able to receive Ether. </p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f911.png" alt="🤑" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/what-is-payable-in-solidity/" data-type="URL" data-id="https://blog.finxter.com/what-is-payable-in-solidity/" target="_blank" rel="noreferrer noopener">What is “payable” in Solidity?</a></p>



<p>However, it&#8217;s a better practice to always define a <code>receive()</code> function, even if we do have a <code>fallback()</code> function. In such case, a fallback function would be used only for otherwise unmatched function calls. A fallback function can also use function modifiers.</p>



<p>A <a rel="noreferrer noopener" href="https://blog.finxter.com/i-created-a-counter-smart-contract-with-ether-js-heres-how/" data-type="post" data-id="1002304" target="_blank">smart contract</a> can have at most one fallback function declared in one of the two following forms, both omitting the keyword <code>function</code> which we&#8217;d usually use when defining an ordinary function:</p>



<p><code>fallback() external [payable]</code></p>



<p>or</p>



<p><code>fallback(bytes calldata input) external [payable] returns (bytes memory output)</code></p>



<p>If we use the second form of a fallback function declaration instead of a receive Ether function, <code>input</code> will contain the full data sent to the contract (equal to <code>msg.data</code>) and it will return <code>msg.data</code> in output (check the console log after calling the function). The returned data will not be ABI-encoded and will be returned in the original form (without padding).</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Note</strong>: If a fallback function is activated when a contract is called from a <code>.send()</code> or <code>.transfer()</code> function, it will be limited to at most 2300 gas, which allows only basic logging. The same goes for the <code><a href="https://blog.finxter.com/solidity-receive-ether-function/" data-type="post" data-id="1266480" target="_blank" rel="noreferrer noopener">receive()</a></code> function in the previous article.</p>



<p>Operations consuming more than 2300 gas are:</p>



<ul class="wp-block-list">
<li>writing to storage,</li>



<li>creating a contract,</li>



<li>calling an external function that consumes a large amount of gas, and</li>



<li>sending Ether.</li>
</ul>



<p>They can only execute if the fallback function is called by the low-level <code>.call</code> function.</p>



<p>In general, a fallback function can do anything, including some complex operations. The only condition is that enough <strong>gas</strong> is available to execute the operations.</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-32.png" alt="" class="wp-image-1266757" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-32.png 960w, https://blog.finxter.com/wp-content/uploads/2023/04/image-32-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-32-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/introduction-to-ethereums-gas-in-solidity-development/" data-type="URL" data-id="https://blog.finxter.com/introduction-to-ethereums-gas-in-solidity-development/" target="_blank" rel="noreferrer noopener">Introduction to Ethereum’s Gas in Solidity Development</a></p>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26a1.png" alt="⚡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Warning</strong>: A <code>payable fallback</code> function also enables our contract to receive Ether when a receive Ether function is missing. Regardless, it is recommended to implement a <code>receive Ether</code> function as it will specifically handle the Ether transfers. The fallback function will only be used for &#8220;interface confusion&#8221; cases, i.e., when a contract receives a function call to a non-existing function.</p>



<p>To decode the input data of a function, we can check the first four bytes which represent the function selector and are compared to available function signatures. Then, we can use <code>abi.decode(...)</code> function combined with the array slice syntax for decoding the ABI-encoded (<a href="https://blog.finxter.com/solidity-layout-pragmas-importing-and-comments/" data-type="post" data-id="716191" target="_blank" rel="noreferrer noopener">Abstract Binary Interface</a>) data:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">(c, d) = abi.decode(input[4:], (uint256, uint256));</pre>



<p>However, we shouldn&#8217;t be comfortable with this approach and use it only when no other is available. Instead, we should rather use available functions.</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-33.png" alt="" class="wp-image-1266759" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-33.png 960w, https://blog.finxter.com/wp-content/uploads/2023/04/image-33-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-33-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-34.png" alt="" class="wp-image-1266760" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-34.png 960w, https://blog.finxter.com/wp-content/uploads/2023/04/image-34-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-34-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>



<h2 class="wp-block-heading">Example &#8211; The Source Code</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.2 &lt;0.9.0;

contract Test {
    uint x;
    fallback() external { x = 1; }
}

contract TestPayable {
    uint x;
    uint y;
    fallback() external payable { x = 1; y = msg.value; }
    receive() external payable { x = 2; y = msg.value; }
}

contract Caller {
    function callTest(Test test) public returns (bool) {

        (bool success,) = address(test).call(abi.encodeWithSignature("nonExistingFunction()"));
        require(success);

        address payable testPayable = payable(address(test));

        return testPayable.send(2 ether);
    }

    function callTestPayable(TestPayable test) public returns (bool) {
        (bool success,) = address(test).call(abi.encodeWithSignature("nonExistingFunction()"));
        require(success);

        (success,) = address(test).call{value: 1}(abi.encodeWithSignature("nonExistingFunction()"));
        require(success);

        (success,) = address(test).call{value: 2 ether}("");
        require(success);

        return true;
    }

    receive() external payable {}
}
</pre>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-35.png" alt="" class="wp-image-1266761" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-35.png 960w, https://blog.finxter.com/wp-content/uploads/2023/04/image-35-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-35-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-36.png" alt="" class="wp-image-1266762" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-36.png 960w, https://blog.finxter.com/wp-content/uploads/2023/04/image-36-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-36-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-37.png" alt="" class="wp-image-1266765" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-37.png 960w, https://blog.finxter.com/wp-content/uploads/2023/04/image-37-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-37-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>



<h2 class="wp-block-heading">Example &#8211; The Fallback Function</h2>



<p>Let&#8217;s look at the contract example, showing what a fallback function looks like.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.2 &lt;0.9.0;

contract Test {
    uint x;
    fallback() external { x = 1; }
}</pre>



<p>The fallback function will execute every time since no other function is declared, i.e., no function signature would match a function call. </p>



<p>Also, if we try sending Ether to this contract, an exception will be thrown since the fallback function is not defined as <code>payable</code> and it cannot receive Ether. </p>



<p>This can be fixed in two steps:</p>



<ol class="wp-block-list">
<li>Change the <code>external</code> keyword to <code>external payable</code>; </li>



<li>Remove <code>x = 1;</code> because this operation takes more than 2300 gas available. </li>
</ol>



<p>We won&#8217;t make the change here, but in case you want to play with it, that&#8217;s how you can do it.</p>



<h2 class="wp-block-heading">Example &#8211; Fallback Function + receive Ether Function</h2>



<p>This time, let&#8217;s look at a contract example showing a fallback function and a receive Ether function, according to the recommendation on a good way to structure our smart contract projects.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">contract TestPayable {
    uint x;
    uint y;</pre>



<p>The fallback function is called for all unmatched function messages sent to this contract, except for plain Ether transfers (only when there&#8217;s a receive function).</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">fallback() external payable { x = 1; y = msg.value; }</pre>



<p>Plain Ether transfers are calls with empty <code>calldata</code> and are processed by the <code>receive</code> function.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">receive() external payable { x = 2; y = msg.value; }
}</pre>



<p>In this example, we&#8217;ll build on both of the two previous examples and show how calls to the two examples differ.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">contract Caller {
    function callTest(Test test) public returns (bool) {
</pre>



<p>The <code>test</code> parameter receives an argument, i.e., a destination contract address. </p>



<p>Then, a call to the non-existing function is deliberately made. A tuple is returned: the first part of the result is stored in the success variable, while the rest is discarded. </p>



<p>The <code>fallback()</code> function will execute, and the function call will complete with the success variable set to true.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    (bool success,) = address(test).call(abi.encodeWithSignature("nonExistingFunction()"));
    require(success);</pre>



<p>Before we can call the <code>send()</code> function on the contract address received via parameter <code>test</code>, we must convert it from the <a href="https://blog.finxter.com/solidity-members-of-address-types-and-type-information/" data-type="post" data-id="896974" target="_blank" rel="noreferrer noopener"><code>address</code> type</a> to the <a href="https://blog.finxter.com/solidity-members-of-address-types-and-type-information/" data-type="post" data-id="896974" target="_blank" rel="noreferrer noopener"><code>address payable</code> type</a>. </p>



<p>This will allow us to call the <code>send()</code> function from the caller&#8217;s side, but the call itself will fail on the callee&#8217;s side because the <code>fallback()</code> function isn&#8217;t declared as <code>payable</code>, i.e., it cannot receive Ether.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    address payable testPayable = payable(address(test));
    return testPayable.send(2 ether);
}</pre>



<p>In contrast to the previous <code>callTest()</code> function, the <code>callTestPayable()</code> function can successfully send Ether to the destination contract because the answering functions are both declared as <code>payable</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">function callTestPayable(TestPayable test) public returns (bool) {</pre>



<p>The <code>test</code> parameter receives an argument, i.e., a destination contract address. Then, a call to the non-existing function is deliberately made.</p>



<p>We use different hard-coded values in all three calls to distinguish when a <code>receive()</code> function is executed (hard-coded value <code>test.x = 2</code>) instead of the <code>fallback()</code> function (hard-coded value <code>test.x = 1</code>).</p>



<p>Our <code>receive()</code> and <code>fallback()</code> functions both receive Ether and write to storage (<code>x</code> and <code>y</code> variables). As writing to storage requires more than 2300 gas, we wouldn&#8217;t be able to do both with <code>send()</code> function but instead had to use the low-level <code>call()</code> function.</p>



<p>The next function call is also with calldata, so a <code>fallback()</code> function is executed; <code>test.x</code> becomes <code>= 1</code> (hard coded), and <code>test.y</code> becomes <code>= 0</code> (a default value, since no value is sent). </p>



<p>A tuple is returned: the first part of the result is stored in the success variable, while the rest is discarded. The <code>fallback()</code> function will execute and the function call will complete with the success variable set to true.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">        (bool success,) = address(test).call(abi.encodeWithSignature("nonExistingFunction()"));
        require(success);
</pre>



<p>The next function call is with <code>calldata</code>, but also with a value, so a fallback function is executed; <code>test.x</code> becomes <code>= 1</code> (hardcoded assignment in the fallback function) and <code>test.y</code> becomes <code>= 1</code> (parametrized assignment).</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">(success,) = address(test).call{value: 1} (abi.encodeWithSignature("nonExistingFunction()"));
require(success);</pre>



<p>The next call is without <code>calldata</code>, so the receive function is executed; <code>test.x</code> becomes <code>= 2</code> (hard-coded assignment in the receive function) and <code>test.y</code> becomes <code>2000000000000000000</code> (a parametrized assignment in the amount of Wei units equal to 2 Ether sent as a value).</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">        (success,) = address(test).call{value: 2 ether}("");
        require(success);
        // results in test.x becoming == 2 and test.y becoming 2 ether.

       return true;

    }
}
</pre>



<h2 class="wp-block-heading">Conclusion</h2>



<p>In this article, we learned about a fallback function, i.e., what it is, how, and when it&#8217;s used.</p>



<p>First, we made an overview of the fallback function.</p>



<p>Second, we learned about how a fallback function is implemented and what its limitations are.</p>



<p>Third, we listed the source code for easier navigation.</p>



<p>Fourth, we viewed a simple fallback function example.</p>



<p>Fifth, we examined a more thorough, complex example combining both a fallback and a receive function.</p>



<h2 class="wp-block-heading">What&#8217;s Next?</h2>



<p>This tutorial is part of our extended Solidity documentation with videos and more accessible examples and explanations. You can navigate the series here (all links open in a new tab):</p>



<div class="wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex">
<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://blog.finxter.com/solidity-receive-ether-function/" target="_blank" rel="noreferrer noopener"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f448.png" alt="👈" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Prev Tutorial</a></div>



<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://blog.finxter.com/solidity-deep-dive-syllabus-video-tutorial-resources/" target="_blank" rel="noreferrer noopener"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/261d.png" alt="☝" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Syllabus</a></div>



<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://blog.finxter.com/solidity-function-overloading/" target="_blank" rel="noreferrer noopener"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Next Tutorial</a></div>
</div>
<p>The post <a href="https://blog.finxter.com/soliditys-fallback-function-a-simple-guide/">Solidity&#8217;s Fallback Function &#8211; A Simple Guide</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Solidity Receive Ether Function</title>
		<link>https://blog.finxter.com/solidity-receive-ether-function/</link>
		
		<dc:creator><![CDATA[Matija Horvat]]></dc:creator>
		<pubDate>Tue, 04 Apr 2023 09:34:05 +0000</pubDate>
				<category><![CDATA[dApp]]></category>
		<category><![CDATA[Ethereum]]></category>
		<category><![CDATA[Smart Contracts]]></category>
		<category><![CDATA[Solidity]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1266480</guid>

					<description><![CDATA[<p>In this article, we will focus on an important topic, the receive Ether function in Solidity. This function allows us to receive the currency and is the first of the two possible approaches for receiving currency. The other approach is the fallback function, and we&#8217;ll briefly introduce it here to become aware of the wider ... <a title="Solidity Receive Ether Function" class="read-more" href="https://blog.finxter.com/solidity-receive-ether-function/" aria-label="Read more about Solidity Receive Ether Function">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/solidity-receive-ether-function/">Solidity Receive Ether Function</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In this article, we will focus on an important topic, the <strong>receive Ether function</strong> in Solidity. This function allows us to receive the currency and is the first of the two possible approaches for receiving currency. The other approach is the fallback function, and we&#8217;ll briefly introduce it here to become aware of the wider picture. We&#8217;ll also cover the fallback function in the following article in more detail.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Solidity Receive Ether Function" width="937" height="703" src="https://www.youtube.com/embed/ltldHdr3HEs?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>It&#8217;s part of our long-standing tradition to make this (and other) articles a faithful companion, or a supplement to the official Solidity <a rel="noreferrer noopener" href="https://docs.soliditylang.org/en/v0.8.15/contracts.html#receive-ether-function" data-type="URL" data-id="https://docs.soliditylang.org/en/v0.8.15/contracts.html#receive-ether-function" target="_blank">documentation</a>.</p>



<h2 class="wp-block-heading">Overview</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="564" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-26-1024x564.png" alt="" class="wp-image-1266511" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-26-1024x564.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/04/image-26-300x165.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-26-768x423.png 768w, https://blog.finxter.com/wp-content/uploads/2023/04/image-26-1536x846.png 1536w, https://blog.finxter.com/wp-content/uploads/2023/04/image-26.png 1990w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>When our contract receives a transaction without a matching function, a special function called <code>receive()</code> is automatically executed. </p>



<p>Of course, we imply that our contract contains such a function. The contract can receive incoming Ether using this function and execute operations like putting the received amount in a balance or invoking other contract procedures. </p>



<p>We should differentiate the <code>receive()</code> function, which is a callback function, from a fallback function (a point for the upcoming section).</p>



<h2 class="wp-block-heading">Implementation</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="571" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-27-1024x571.png" alt="" class="wp-image-1266514" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-27-1024x571.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/04/image-27-300x167.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-27-768x428.png 768w, https://blog.finxter.com/wp-content/uploads/2023/04/image-27.png 1202w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>A contract may have only one receive Ether function. The function is declared as:</p>



<p><code>receive() external payable { ... }</code> </p>



<p><em>Note how we omitted the keyword <code>function</code>. </em></p>



<p>There are several peculiarities regarding the receive function: it cannot have any arguments, doesn&#8217;t return anything, and must have external visibility and <code><a href="https://blog.finxter.com/what-is-payable-in-solidity/" data-type="post" data-id="37282" target="_blank" rel="noreferrer noopener">payable</a></code> state mutability. </p>



<p>Besides that, the receive function can be virtual, it can override its base function and also have modifiers.</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Note</strong>: <br><br><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> A function (also called a <em>base</em> function) that allows an inheriting contract to override its behavior will be marked with a keyword <code>virtual</code>. (<a rel="noreferrer noopener" href="https://medium.com/upstate-interactive/solidity-override-vs-virtual-functions-c0a5dfb83aaf" data-type="URL" data-id="https://medium.com/upstate-interactive/solidity-override-vs-virtual-functions-c0a5dfb83aaf" target="_blank">source</a>) <br><br><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> A function that overrides that base function should be marked with the keyword <code>override</code>. (<a href="https://medium.com/upstate-interactive/solidity-override-vs-virtual-functions-c0a5dfb83aaf">source</a>)</p>



<h2 class="wp-block-heading">Receive Function Properties</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="574" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-28-1024x574.png" alt="" class="wp-image-1266518" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-28-1024x574.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/04/image-28-300x168.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-28-768x431.png 768w, https://blog.finxter.com/wp-content/uploads/2023/04/image-28.png 1197w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>The <code>receive</code> function gets executed when a call with empty <code>calldata</code> arguments is made on a contract. </p>



<p>For instance, the <code>receive</code> function is executed on simple, plain Ether transfers, such as the ones made via <code>.send()</code> or <code>.transfer()</code> functions. However, if we didn&#8217;t introduce a receive function, but do have a payable fallback function (in more detail in the following article), the fallback function will be activated on a plain Ether transfer.</p>



<p>We can already notice that a fallback function is an alternative to having a receive function. A few paragraphs later, we&#8217;ll see if they&#8217;re almost equivalent and why. Finally, if we don&#8217;t have a receive function or a fallback function, our contract won&#8217;t be able to receive Ether via regular transactions and will throw an exception.</p>



<p>There&#8217;s a possible confusion between the terms fallback function and callback function, so let&#8217;s first get that out of the way:</p>



<ul class="wp-block-list">
<li>A <strong>fallback function</strong> is executed if (1) none of the other functions match the function identifier, or (2) no data (arguments) was provided with the function call. (<a href="https://www.geeksforgeeks.org/solidity-fall-back-function/">source</a>) A fallback function shouldn&#8217;t be confused with a callback function.</li>



<li>A <strong>callback function</strong> is a function passed as an argument to a called function. After the called function is executed successfully, the callback function gets called. In practice, a callback function construct is commonly used for asynchronous behavior, where we want an activity to take place after the previous event completes. (<a href="https://stackoverflow.com/questions/824234/what-is-a-callback-function">source</a>)</li>
</ul>



<p>Operations consuming more than 2300 gas are:</p>



<ul class="wp-block-list">
<li>writing to storage,</li>



<li>creating a contract,</li>



<li>calling an external function that consumes a large amount of gas, and</li>



<li>sending Ether.</li>
</ul>



<p>They can only execute if the receive function is called by the low-level .call function.</p>



<h3 class="wp-block-heading"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26a1.png" alt="⚡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Warnings <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26a1.png" alt="⚡" class="wp-smiley" style="height: 1em; max-height: 1em;" /></h3>



<p>Although available, payable fallback methods aren&#8217;t recommended for receiving Ether. It&#8217;s much better to have a separate receive function for receiving Ether and a fallback function to cover all other cases. This approach will make our debugging easier and enable healthy separation of functionality.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>There are two special cases where our contract will be able to receive Ether without a receive function. </p>



<p>It will do so as a recipient of a coinbase transaction, also known as a <em>miner block reward</em>, and as a destination of a keyword <code>selfdestruct</code>. </p>



<p>A contract is not able to react to Ether transfers of this kind and therefore cannot decline them. This is an inherent property stemming from the EVM design choice that Solidity cannot bypass.</p>



<p>The consequence of such implementation may be an unexpected value of <code>address(this).balance</code>, possibly higher than the amount accounted for by the contract logic.</p>



<h2 class="wp-block-heading">Receive Function Example</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="574" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-29-1024x574.png" alt="" class="wp-image-1266519" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-29-1024x574.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/04/image-29-300x168.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-29-768x431.png 768w, https://blog.finxter.com/wp-content/uploads/2023/04/image-29.png 1202w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>In the following example, we&#8217;ll see what a contract&#8217;s receive function looks like in its simplest form.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 &lt;0.9.0;

contract Sink {
</pre>



<p>Here we define an event that will be emitted when the receive function is executed.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    event Received(address, uint);</pre>



<p>This is the receive function declaration which usually contains more complex logic. In this example, it just emits the event (signal) letting us know that the receive function finished its execution.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    receive() external payable {
        emit Received(msg.sender, msg.value);
    }
}
</pre>



<h2 class="wp-block-heading"><a></a>Conclusion</h2>



<p>In this article, we went through the details of <code>receive</code> function in Solidity. We also mentioned its alternative, the fallback function. We learned that the receive function allows us to receive the currency and is the first and the preferred one of the two possible choices for receiving currency.</p>



<p>First, we briefly overview the purpose behind the receive function in Solidity.</p>



<p>Second, we discussed the function implementation, i.e., what syntax we should use.</p>



<p>Third, we took a closer look at the function properties, learned how it works, and got familiar with a few use specifics in the form of warnings.</p>



<p>Fourth, we made a simple example showing how a receive function looks in action.</p>



<h2 class="wp-block-heading">What&#8217;s Next?</h2>



<p>This tutorial is part of our extended Solidity documentation with videos and more accessible examples and explanations. You can navigate the series here (all links open in a new tab):</p>



<div class="wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex">
<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://blog.finxter.com/solidity-function-visibility-made-easy/" target="_blank" rel="noreferrer noopener"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f448.png" alt="👈" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Prev Tutorial</a></div>



<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://blog.finxter.com/solidity-deep-dive-syllabus-video-tutorial-resources/" target="_blank" rel="noreferrer noopener"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/261d.png" alt="☝" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Syllabus</a></div>



<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://blog.finxter.com/soliditys-fallback-function-a-simple-guide/" target="_blank" rel="noreferrer noopener"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Next Tutorial</a></div>
</div>
<p>The post <a href="https://blog.finxter.com/solidity-receive-ether-function/">Solidity Receive Ether Function</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Solidity Function Visibility Made Easy</title>
		<link>https://blog.finxter.com/solidity-function-visibility-made-easy/</link>
		
		<dc:creator><![CDATA[Matija Horvat]]></dc:creator>
		<pubDate>Tue, 04 Apr 2023 09:13:25 +0000</pubDate>
				<category><![CDATA[dApp]]></category>
		<category><![CDATA[Ethereum]]></category>
		<category><![CDATA[Smart Contracts]]></category>
		<category><![CDATA[Solidity]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1266426</guid>

					<description><![CDATA[<p>Solidity has many useful features that enable us, smart contract developers, to make safe, secure, and functional smart contracts. We have discussed other interesting Solidity features, and this time, we&#8217;ll focus on one very important feature of Solidity called function visibility. It determines who can call a function and who can access its variables. In ... <a title="Solidity Function Visibility Made Easy" class="read-more" href="https://blog.finxter.com/solidity-function-visibility-made-easy/" aria-label="Read more about Solidity Function Visibility Made Easy">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/solidity-function-visibility-made-easy/">Solidity Function Visibility Made Easy</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Solidity has many useful features that enable us, smart contract developers, to make safe, secure, and functional smart contracts. We have discussed other interesting <a href="https://blog.finxter.com/solidity-deep-dive-syllabus-video-tutorial-resources/" data-type="post" data-id="777532" target="_blank" rel="noreferrer noopener">Solidity features</a>, and this time, we&#8217;ll focus on one very important feature of Solidity called <em>function visibility</em>. It determines who can call a function and who can access its variables.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Solidity Function Visibility Made Easy" width="937" height="703" src="https://www.youtube.com/embed/rZD6paNd6Ww?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>In this article, we will explore the different types of function visibility in Solidity and how the types are used. It&#8217;s part of our long-standing tradition to make this (and other) articles a faithful companion, or a supplement to the official Solidity <a rel="noreferrer noopener" href="https://docs.soliditylang.org/en/v0.8.15/contracts.html#function-modifiers" target="_blank">docs</a> for this article&#8217;s topic.</p>



<h2 class="wp-block-heading">Overview</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-21.png" alt="" class="wp-image-1266455" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-21.png 960w, https://blog.finxter.com/wp-content/uploads/2023/04/image-21-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-21-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>
</div>


<p>There are four types of function visibility in Solidity: </p>



<ul class="wp-block-list">
<li>public, </li>



<li>external, </li>



<li>internal, and</li>



<li>private.</li>
</ul>



<p><strong>Public functions</strong> are the most permissive, as they can be called by anyone, including other contracts and external users. We declare them using the <code>public</code> keyword, which is the default visibility type if we leave out the visibility specifier keyword. We can imagine public functions as being internal and external at the same time.</p>



<p><strong>External functions</strong> are similar to public functions, but they are intended to be called by other contracts rather than external users. They are declared using the <code>external</code> keyword and are useful for defining a contract&#8217;s interface, which is the set of functions that other contracts can use to interact with it.</p>



<p><strong>Internal functions</strong> are similar to public functions, but they can only be called from within the contract in which they are defined and from the derived contracts. We declare them using the <code>internal</code> keyword and they are useful for separating out functionality only needed within the contract.</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f52a.png" alt="🔪" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Warning</strong>: The default function visibility type is public and must not be confused with the default state variable visibility type, which is internal.</p>



<p><strong>Private functions</strong> are the most restrictive, as they can only be called from within the contract in which they are defined. They are declared using the <code>private</code> keyword and are useful for hiding implementation details that are not relevant to external users. In contrast to internal functions, private functions cannot be called by the derived contracts, but only within the base contract.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f469-200d-1f4bb.png" alt="👩‍💻" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>One-Paragraph Summary</strong>: <em>We should carefully consider function visibility when designing a contract, as it can significantly affect security and usability. Public functions can be called by anyone, so they should be used sparingly and only for functions that need to be exposed to both external and internal calls. External functions should be used to define the contract&#8217;s interface and make it easier for other contracts to interact with it. Internal and private functions can be used to hide implementation details and reduce the attack surface of the contract.</em></p>



<h2 class="wp-block-heading">Public Functions</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-22.png" alt="" class="wp-image-1266456" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-22.png 960w, https://blog.finxter.com/wp-content/uploads/2023/04/image-22-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-22-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>
</div>


<p>Public functions are part of the contract interface, which enables us to call these functions either internally, i.e. <code>f()</code> or via message calls, i.e., <code>this.f()</code>. </p>



<p>We&#8217;d commonly declare a function as public to make it callable by other contracts or externally by users, such as us, when calling a function in e.g., Remix.</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f469-200d-1f4bb.png" alt="👩‍💻" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/solidity-remix-ide-quickstart/" data-type="URL" data-id="https://blog.finxter.com/solidity-remix-ide-quickstart/" target="_blank" rel="noreferrer noopener">Solidity Remix IDE Quickstart</a></p>



<p>A very simple example of a public function is given below:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;

contract SimpleFunction {

   function addNumbers(uint a, uint b) 
   external 
   pure 
   returns (uint) {
       return a + b;
   }

   function callAddNumbers(uint a, uint b) 
   public
   pure
   returns (uint) {
      // This would work.
      return addNumbers(a, b);

      // This would work, but the mutability keyword must be 
      // at least 'view' because it calls the function addNumbers(...) 
      // from its environment.
      return this.addNumbers(a, b);
   }
}
</pre>



<p>Public functions provide us with the most freedom in terms of the simplest proof-of-concept approach for quickly testing new ideas, without concerning ourselves with potential design issues or security.</p>



<p>In such cases, however, we should remain aware that an &#8220;all-public&#8221; approach should be later replaced with stricter implementation, guided by best practices in terms of design and security.</p>



<h2 class="wp-block-heading"><a></a>External Functions</h2>



<p class="has-global-color-8-background-color has-background">External functions are also part of the contract interface, which enables us to call them from other contracts and via transactions. However, there&#8217;s a restriction: we cannot call an external function <code>f</code> internally.&nbsp;That&#8217;s why an <code>f()</code> call does not work due to internal reference, however, <code>this.f()</code> does work because the keyword <code>this</code> refers to the contract externally.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-23.png" alt="" class="wp-image-1266457" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-23.png 960w, https://blog.finxter.com/wp-content/uploads/2023/04/image-23-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-23-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>
</div>


<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f469-200d-1f4bb.png" alt="👩‍💻" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/solidity-internal-function-calls/" data-type="post" data-id="911324" target="_blank" rel="noreferrer noopener">Solidity Function Calls – Internal and External</a></p>



<p>Let&#8217;s take a look at the following example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;

contract SimpleFunction {

   function addNumbers(uint a, uint b) 
   external 
   pure 
   returns (uint) {
       return a + b;
   }

   function callAddNumbers(uint a, uint b) 
   public
   // Mutability keyword must be at least 'view', because it calls 
   // the function addNumbers(...) from its environment. 
   // It's not the case with internal function call.
   view
   returns (uint) {
       // This wouldn't work. An error would show up saying: 
       // "DeclarationError: Undeclared identifier. "addNumbers" is not 
       // (or not yet) visible at this point."
       return addNumbers(a, b);

       // This will work.
       return this.addNumbers(a, b);
   }
}
</pre>



<p>In the example above, we notice an error caused by trying to call the function <code>callAddNumbers(...)</code> declared as external. On the other hand, if we tried calling an external function via a message call by adding the keyword this, i.e., <code>this.addNumbers(a, b)</code>, it would work just fine.</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Note</strong>: A caller function calling another function via a <a rel="noreferrer noopener" href="https://blog.finxter.com/ethereum-virtual-machine-evm-message-calls-solidity-smart-contracts/" data-type="post" data-id="592250" target="_blank">message call</a> should be declared at least as view (read-only), because it reads from its environment and pure is too restrictive.</p>



<p>The public visibility type can be considered external type and internal type simultaneously.</p>



<h2 class="wp-block-heading"><a></a>Internal Functions</h2>



<p>We can access internal functions only from within the base (current) contract or contracts deriving (inheriting) from the base contract. This means internal functions are unavailable for external access because they are not exposed through the contract’s <a href="https://blog.finxter.com/solidity-checked-and-unchecked-expressions/" data-type="post" data-id="1257666" target="_blank" rel="noreferrer noopener">ABI</a>. Because of that, internal functions can take parameters of internal types, like mappings or storage references.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-24.png" alt="" class="wp-image-1266459" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-24.png 960w, https://blog.finxter.com/wp-content/uploads/2023/04/image-24-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-24-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>
</div>


<p>Let&#8217;s revisit the modified example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;

contract SimpleFunction {

   function addNumbers(uint a, uint b) 
   internal
   pure 
   returns (uint) {
      return a + b;
   }

   function callAddNumbers(uint a, uint b) 
   public
   // Mutability keyword may be 'pure', since it calls 
   // the function addNumbers(...) internally.
   pure
   returns (uint) {

      // This will work.
      return addNumbers(a, b);

      // This wouldn't work. An error would show up saying: 
      // TypeError: Member "addNumbers" not found or not visible after
      // argument-dependent lookup in contract SimpleFunction.
      return this.addNumbers(a, b);
   }
}
</pre>



<p>The situation with internal functions is quite the opposite with regard to external functions: calling an internal function via a message call is not possible, i.e., <code>this.addNumbers(a, b)</code> won&#8217;t work. However, an internal call to an internal function will work just fine: <code>addNumbers(a, b)</code>.</p>



<h2 class="wp-block-heading"><a></a>Private Functions</h2>



<p>We&#8217;d declare a function as private function is used when the function is only intended to be called by functions within the same contract and is not accessible to external contracts or users.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-25.png" alt="" class="wp-image-1266461" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-25.png 960w, https://blog.finxter.com/wp-content/uploads/2023/04/image-25-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-25-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>
</div>


<p>The example below will show us how to make a function invisible to the outside world, but still an integral part of a contract.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;

contract SimpleFunction {

   function addNumbers(uint a, uint b) 
   private
   pure 
   returns (uint) {
      return a + b;
   }

   function callAddNumbers(uint a, uint b) 
   public
   // Mutability keyword may be 'pure', since it calls 
   // the function addNumbers(...) internally.
   pure
   returns (uint) {

      // This will work.
      return addNumbers(a, b);
   }
}
</pre>



<h2 class="wp-block-heading"><a></a>Conclusion</h2>



<p>In this article, we learned about function visibility types in Solidity. Function visibility is an important concept in Solidity that determines who can call a function and access its variables. By carefully considering function visibility, we, as smart contract developers, can create secure, maintainable, and easy-to-use contracts.</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f469-200d-1f4bb.png" alt="👩‍💻" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/solidity-developer-income-and-opportunity/" data-type="post" data-id="211072" target="_blank" rel="noreferrer noopener">Blockchain Developers &#8211; Income and Opportunity</a></p>



<p>First, we introduced public functions and saw how they work and behave.</p>



<p>Second, we explained what external functions are and what their role is in the notion of public functions.</p>



<p>Third, we learned about internal functions and showed how they can be perceived as a second half of public functions.</p>



<p>Fourth, we rounded the story on function visibility with the introduction of private functions as the most restrictive form of function visibility type.</p>



<h2 class="wp-block-heading">What&#8217;s Next?</h2>



<p>This tutorial is part of our extended Solidity documentation with videos and more accessible examples and explanations. You can navigate the series here (all links open in a new tab):</p>



<div class="wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex">
<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://blog.finxter.com/solidity-error-handling-with-assert-require-and-revert-functions/" target="_blank" rel="noreferrer noopener"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f448.png" alt="👈" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Prev Tutorial</a></div>



<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://blog.finxter.com/solidity-deep-dive-syllabus-video-tutorial-resources/" target="_blank" rel="noreferrer noopener"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/261d.png" alt="☝" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Syllabus</a></div>



<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://blog.finxter.com/solidity-receive-ether-function/" target="_blank" rel="noreferrer noopener"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Next Tutorial</a></div>
</div>
<p>The post <a href="https://blog.finxter.com/solidity-function-visibility-made-easy/">Solidity Function Visibility Made Easy</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Solidity Error Handling with Assert, Require, and Revert Functions</title>
		<link>https://blog.finxter.com/solidity-error-handling-with-assert-require-and-revert-functions/</link>
		
		<dc:creator><![CDATA[Matija Horvat]]></dc:creator>
		<pubDate>Fri, 31 Mar 2023 19:49:31 +0000</pubDate>
				<category><![CDATA[dApp]]></category>
		<category><![CDATA[Ethereum]]></category>
		<category><![CDATA[Smart Contracts]]></category>
		<category><![CDATA[Solidity]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1257859</guid>

					<description><![CDATA[<p>In this article, we&#8217;ll get a closer look at four main mechanisms for error handling in Solidity: functions assert, require, revert, and another approach based on exceptions. These mechanisms will help us tremendously in achieving stable and secure smart contracts, so this is the right moment to introduce them and lay the ground for a ... <a title="Solidity Error Handling with Assert, Require, and Revert Functions" class="read-more" href="https://blog.finxter.com/solidity-error-handling-with-assert-require-and-revert-functions/" aria-label="Read more about Solidity Error Handling with Assert, Require, and Revert Functions">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/solidity-error-handling-with-assert-require-and-revert-functions/">Solidity Error Handling with Assert, Require, and Revert Functions</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In this article, we&#8217;ll get a closer look at four main mechanisms for error handling in Solidity: functions <code>assert</code>, <code>require</code>, <code>revert</code>, and another approach based on exceptions. </p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-479.png" alt="" class="wp-image-1257889" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-479.png 960w, https://blog.finxter.com/wp-content/uploads/2023/03/image-479-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-479-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>
</div>


<p>These mechanisms will help us tremendously in achieving stable and secure smart contracts, so this is the right moment to introduce them and lay the ground for a more thorough analysis.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Solidity Error Handling with Assert, Require, and Revert Functions" width="937" height="703" src="https://www.youtube.com/embed/PaC2N0ATtAA?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>It&#8217;s part of our long-standing tradition to make this (and other) articles a faithful companion, or a supplement to the <a rel="noreferrer noopener" href="https://docs.soliditylang.org/en/v0.8.17/control-structures.html#error-handling-assert-require-revert-and-exceptions" data-type="URL" data-id="https://docs.soliditylang.org/en/v0.8.17/control-structures.html#error-handling-assert-require-revert-and-exceptions" target="_blank">official Solidity documentation</a>.</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-480.png" alt="" class="wp-image-1257890" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-480.png 960w, https://blog.finxter.com/wp-content/uploads/2023/03/image-480-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-480-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>



<h2 class="wp-block-heading">assert()</h2>



<p class="has-global-color-8-background-color has-background">We&#8217;d commonly use the <code>assert(...)</code> function to test if a certain expression evaluates to an expected value. The function takes a boolean expression as an argument, and if the expression evaluates to false, the transaction will throw an exception and revert all changes made in the transaction.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-481.png" alt="" class="wp-image-1257893" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-481.png 960w, https://blog.finxter.com/wp-content/uploads/2023/03/image-481-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-481-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>
</div>


<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Note</strong>: We should refrain from using the <code>assert(...)</code> function in the production source code; it&#8217;s meant to be used mainly for testing and debugging.</p>



<p>Let&#8217;s take a look at a simple and familiar example of using the <code>assert(...)</code> function:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0 &lt;0.9.0;

contract Divider {
    function divide(uint numerator, uint denominator) 
    public 
    pure
    returns (uint) {
        assert(denominator != 0);
        uint result = numerator / denominator;
        return result;
    }
}</pre>



<p>In the example above, the <code>assert(...)</code> function is used to check that the denominator is not 0 before performing the division. If the denominator is 0, the transaction will throw an exception and revert any changes made by the transaction. This way, our <a href="https://blog.finxter.com/i-created-a-counter-smart-contract-with-ether-js-heres-how/" data-type="post" data-id="1002304" target="_blank" rel="noreferrer noopener">smart contract</a> is safe in terms of keeping the transaction in a consistent state.</p>



<h2 class="wp-block-heading">require()</h2>



<p class="has-global-color-8-background-color has-background">The <code>require(...)</code> function is similar to the <code>assert(...)</code> function, but contrary to the <code>assert(...)</code> function, it&#8217;s recommended for use in production code. Just like the <code>assert(...)</code> function, it takes a <a href="https://blog.finxter.com/breaking-down-solidity-expression-trees-and-tuple-assignments/" data-type="post" data-id="979213" target="_blank" rel="noreferrer noopener">boolean expression</a> as an argument and reverts the transaction if the expression evaluates to false.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-482.png" alt="" class="wp-image-1257894" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-482.png 960w, https://blog.finxter.com/wp-content/uploads/2023/03/image-482-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-482-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>
</div>


<p>Let&#8217;s take a look at an example of using <code>require(...)</code> function:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0 &lt;0.9.0;

contract RequireExample {
    mapping(address => uint) balanceOf;
    
    function transfer(address _to, uint _value) public {
        // Ensures that the caller has sufficient funds.
        require(balanceOf[msg.sender] >= _value);
        // Transfers the funds.
        balanceOf[msg.sender] -= _value;
        balanceOf[_to] += _value;
    }
}
</pre>



<p>In this example, we use the <code>require(...)</code> function to ensure that the caller of the <code>transfer(...)</code> function has sufficient funds before transferring the specified amount. If the caller does not have sufficient funds, the transaction will throw an exception and revert any changes made by the transaction.</p>



<h2 class="wp-block-heading">revert()</h2>



<p class="has-global-color-8-background-color has-background">We&#8217;d use the <code>revert(...)</code> function to explicitly revert the changes made by a transaction and throw an exception. It is often used in conjunction with the <code>require(...)</code> function to revert the changes made by a transaction if a certain condition is not met.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-483.png" alt="" class="wp-image-1257895" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-483.png 960w, https://blog.finxter.com/wp-content/uploads/2023/03/image-483-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-483-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>
</div>


<p>Let&#8217;s take a look at an example of using <code>revert(...)</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0 &lt;0.9.0;
// This will report a warning
contract RevertExample{
   address private owner;

   function setOwner(address _newOwner) public {
       // Ensures that the caller is the current owner.
       require(msg.sender == owner);
       // Sets the new owner
       owner = _newOwner;
   }</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-484.png" alt="" class="wp-image-1257896" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-484.png 960w, https://blog.finxter.com/wp-content/uploads/2023/03/image-484-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-484-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>
</div>


<h2 class="wp-block-heading">Exceptions</h2>



<p>Exceptions are a great mechanism available to us for error handling with external function calls and contract creation calls. They are similar to exceptions in other programming languages, but they work a bit differently in the context of a blockchain. </p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-485.png" alt="" class="wp-image-1257897" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-485.png 960w, https://blog.finxter.com/wp-content/uploads/2023/03/image-485-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-485-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>
</div>


<p>In Solidity, exceptions are thrown using the <code>throw</code> keyword, and they can be caught using the <code>try/catch</code> statements.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/solidity-control-structures/" data-type="post" data-id="911321" target="_blank" rel="noreferrer noopener">Solidity Control Structures</a></p>



<p>Exceptions in many programming languages have the property of ‘bubbling up’ automatically until they are caught in a <code>try/catch</code> statement. The exceptions to this rule are the <code>send(...)</code> function and the low-level functions <code>call(...)</code>, <code>delegatecall(...)</code> and <code>staticcall(...)</code>. These functions just return <code>false</code> as their first return value in case of an exception, instead of ‘bubbling up’.</p>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26a1.png" alt="⚡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Warning</strong>: The low-level functions <code>call(...)</code>, <code>delegatecall(...)</code> and <code>staticcall(...)</code> return <code>true</code> as their first return value if the account called is non-existent. We have discussed this behavior in earlier articles since it is a part of the design of the EVM. To circumvent it, we must check for the account&#8217;s existence before using the low-level functions.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/delegatecall-or-storage-collision-attack-on-smart-contracts/" data-type="post" data-id="385265" target="_blank" rel="noreferrer noopener">DelegateCall or Storage Collision Attack on Smart Contracts</a></p>



<p>Here is an example of using exceptions in a smart contract:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0 &lt;0.9.0;

contract Divider {
    function divide(uint numerator, uint denominator) 
    public 
    pure
    returns (uint) {
        uint result = numerator / denominator;
        return result;
    }
}

contract Operation {

    Divider divider = new Divider();
    event Log(string message);

    function callOperation(uint numerator, uint denominator) 
    public 
    returns (uint result) {
        try divider.divide(numerator, denominator) returns (uint r) {
            return r;
        } catch {
            emit Log("External call threw an error.");
        }
    }
}
</pre>



<p></p>



<p>In this example, the <code>divide(...)</code> function throws an exception if the denominator is 0. The <code>callOperation(...)</code> function calls the <code>divide(...)</code> function and catches any exceptions that may be thrown. An exception is handled in the catch block by emitting the error message.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-486.png" alt="" class="wp-image-1257899" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-486.png 960w, https://blog.finxter.com/wp-content/uploads/2023/03/image-486-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-486-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>
</div>


<p>It is important to note that exceptions are expensive to use in Solidity because they require the use of gas to throw and catch the exception. </p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/introduction-to-ethereums-gas-in-solidity-development/" data-type="post" data-id="37644" target="_blank" rel="noreferrer noopener">Ethereum Gas &#8211; How It Works</a></p>



<p>With that in mind, we should use them sparingly and only when absolutely necessary.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>In this article, we learned about four different mechanisms for handling errors in Solidity.</p>



<p>First, we got introduced to the <code>assert(...)</code> function and explained which are its use cases, as well as which are not.</p>



<p>Second, we went through the <code>require(...)</code> function and learned about its use cases.</p>



<p>Third, we got acquainted with the <code>revert(...)</code> function and showed how it can be used to handle errors.</p>



<p>Fourth, we got familiar with exception handling and learned how they&#8217;re used for error handling with external function calls and contract creation calls.</p>



<h2 class="wp-block-heading">What&#8217;s Next?</h2>



<p>This tutorial is part of our extended Solidity documentation with videos and more accessible examples and explanations. You can navigate the series here (all links open in a new tab):</p>



<div class="wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex">
<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://blog.finxter.com/solidity-checked-and-unchecked-expressions/" target="_blank" rel="noreferrer noopener"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f448.png" alt="👈" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Prev Tutorial</a></div>



<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://blog.finxter.com/solidity-deep-dive-syllabus-video-tutorial-resources/" target="_blank" rel="noreferrer noopener"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/261d.png" alt="☝" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Syllabus</a></div>



<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://blog.finxter.com/solidity-function-visibility-made-easy/" target="_blank" rel="noreferrer noopener"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Next Tutorial</a></div>
</div>
<p>The post <a href="https://blog.finxter.com/solidity-error-handling-with-assert-require-and-revert-functions/">Solidity Error Handling with Assert, Require, and Revert Functions</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Solidity Checked and Unchecked Expressions</title>
		<link>https://blog.finxter.com/solidity-checked-and-unchecked-expressions/</link>
		
		<dc:creator><![CDATA[Matija Horvat]]></dc:creator>
		<pubDate>Fri, 31 Mar 2023 18:31:04 +0000</pubDate>
				<category><![CDATA[dApp]]></category>
		<category><![CDATA[Ethereum]]></category>
		<category><![CDATA[Smart Contracts]]></category>
		<category><![CDATA[Solidity]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1257666</guid>

					<description><![CDATA[<p>In this article, we&#8217;ll learn about checked and unchecked expressions and when to use each of them. It&#8217;s part of our long-standing tradition to make this (and other) articles a faithful companion or a supplement to the official Solidity documentation for this article&#8217;s topic. We should consider whether an expression should be checked or unchecked ... <a title="Solidity Checked and Unchecked Expressions" class="read-more" href="https://blog.finxter.com/solidity-checked-and-unchecked-expressions/" aria-label="Read more about Solidity Checked and Unchecked Expressions">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/solidity-checked-and-unchecked-expressions/">Solidity Checked and Unchecked Expressions</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In this article, we&#8217;ll learn about <strong>checked and unchecked expressions</strong> and when to use each of them. </p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Solidity Checked and Unchecked Expressions" width="937" height="703" src="https://www.youtube.com/embed/T0MewaR8Amk?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>It&#8217;s part of our long-standing tradition to make this (and other) articles a faithful companion or a supplement to the official <a rel="noreferrer noopener" href="https://docs.soliditylang.org/en/v0.8.15/control-structures.html#checked-or-unchecked-arithmetic" data-type="URL" data-id="https://docs.soliditylang.org/en/v0.8.15/control-structures.html#checked-or-unchecked-arithmetic" target="_blank">Solidity documentation</a> for this article&#8217;s topic.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-471.png" alt="" class="wp-image-1257791" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-471.png 960w, https://blog.finxter.com/wp-content/uploads/2023/03/image-471-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-471-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>
</div>


<p>We should consider whether an expression should be checked or unchecked in the Solidity programming language. Checked expressions will throw an exception and halt the program if a certain condition is not met, while unchecked expressions do not have this behavior. We should be aware of this distinction because unchecked expressions can lead to performance increases at the cost of possible <a href="https://blog.finxter.com/top-8-scary-smart-contract-hacks-that-exploit-your-dapp-video/" data-type="post" data-id="437387" target="_blank" rel="noreferrer noopener">vulnerabilities in our smart contracts</a>, while checked expressions assist us in ensuring the correctness and security of our code.</p>



<h2 class="wp-block-heading">Checked Expressions</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-472.png" alt="" class="wp-image-1257792" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-472.png 960w, https://blog.finxter.com/wp-content/uploads/2023/03/image-472-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-472-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>
</div>


<p>Checked expressions will throw an exception and halt the program if conditions of interest are unmet, or continue execution if they are satisfied. </p>



<p>For example, if we want to ensure that a certain variable contains a valid result before performing an operation, we can use a checked expression to throw an exception if the variable has an unwanted value.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-473.png" alt="" class="wp-image-1257793" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-473.png 960w, https://blog.finxter.com/wp-content/uploads/2023/03/image-473-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-473-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>
</div>


<h3 class="wp-block-heading">require Function</h3>



<p>There are several ways we can use checked expressions in Solidity. The most common way is to use the <code>require(...)</code> function, which will throw an exception if the condition passed to it is not met. </p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-474.png" alt="" class="wp-image-1257795" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-474.png 960w, https://blog.finxter.com/wp-content/uploads/2023/03/image-474-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-474-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>



<p>The following example shows how we can do it:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">function divide(uint numerator, uint denominator) public {
    // Throws an exception if the denominator is zero.
    require(denominator != 0, "Division by zero");

    // Performs the division operation.
    uint result = numerator / denominator;
}</pre>



<p>The <code>require(...)</code> function throws an exception if the denominator is zero. This helps us in ensuring that the division operation will not be performed if the denominator is zero, which would result in an error.</p>



<h3 class="wp-block-heading">assert Function</h3>



<p>Another way to use checked expressions is to use the <code>assert(...)</code> function, which is similar to <code>require(...)</code>. The main difference between <code>assert(...)</code> and <code>require(...)</code> is that <code>assert(...)</code> is recommended for internal consistency checks, while <code>require(...)</code> is better suited for input validation.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-475.png" alt="" class="wp-image-1257796" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-475.png 960w, https://blog.finxter.com/wp-content/uploads/2023/03/image-475-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-475-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>
</div>


<p>In addition to the <code>require(...)</code> and <code>assert(...)</code> functions, there are several other ways we can take to check expressions in Solidity. For example, we can use the <code>revert(...)</code> function to throw an exception and revert the current transaction, or we can use the <code>abort(...)</code> function to throw an exception and halt the program completely.</p>



<p>We should remember that checked expressions are an important tool for ensuring the correctness and security of our Solidity source code. By using checked expressions, we can ensure that we&#8217;re meeting specific conditions before operations are performed, which aids in preventing errors and vulnerabilities in our smart contract.</p>



<h2 class="wp-block-heading">Unchecked Expressions</h2>



<p>On the other hand, unchecked expressions do not throw an exception or terminate the program if a specific condition is not met. This behavior can be useful in situations where we want to allow for a certain level of flexibility in our source code, but we should be aware it can also lead to vulnerabilities if not used carefully. </p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-476.png" alt="" class="wp-image-1257797" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-476.png 960w, https://blog.finxter.com/wp-content/uploads/2023/03/image-476-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-476-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>
</div>


<p>For example, if we have an unchecked expression that does not check the length of an array before performing an operation, it could potentially lead to an out-of-bounds exception.</p>



<p>Another way to use unchecked expressions is to use the <code>call(...)</code> function that allows us to call another contract function without checking for errors.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Reminder</strong>: The <code>call(...)</code> function is a low-level call function used for interaction with other contracts. It represents the recommended way for <a href="https://blog.finxter.com/ether-and-time-units-and-globally-available-variables-in-solidity/" data-type="post" data-id="895145" target="_blank" rel="noreferrer noopener">sending Ether</a> via a call to the fallback function.</p>



<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26a1.png" alt="⚡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Warning</strong>: Although available, the <code>call(...)</code> function is not recommended for calling functions, because reverts are not forwarded up the call stack, type checks are bypassed, and function existence checks are omitted.</p>



<p>Let&#8217;s take a look at the following example of using the <code>call(...)</code> function:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">function sendTransaction(address destContractAddress, uint amount) public {
    // Calls the 'receiveTransaction' function of the 
   // 'destContractAddress' contract without checking for errors
    (bool success, bytes memory data) = destContractAddress.call{value: amount}("receiveTransaction");
}</pre>



<p>The <code>.call(...)</code> function is used for calling the <code>receiveTransaction(...)</code> function of the <code>destContractAddress</code> contract without checking for errors. This can be useful in situations where we want to allow some flexibility in our code, but it can also potentially lead to vulnerabilities if not used carefully.</p>



<h2 class="wp-block-heading">Checked and Unchecked Arithmetic</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="960" height="540" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-477.png" alt="" class="wp-image-1257798" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-477.png 960w, https://blog.finxter.com/wp-content/uploads/2023/03/image-477-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-477-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>
</div>


<p>Checked and unchecked expressions are a natural way of dealing with two distinct situations during arithmetic operations, overflow, and underflow. These two operations occur when an arithmetic operation is expected on an unrestricted integer, that falls outside the range of the resulting type.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Info</strong>: Before Solidity v0.8.0, arithmetic operations weren&#8217;t checked, so external libraries were needed to introduce additional checks. With Solidity v0.8.0, all arithmetic operations revert by default when overflow and underflow situations occur, introducing the needed behavior and eliminating the requirement for external libraries.</p>



<p>However, regardless of the checked behavior being the default one, we can still invoke the unchecked behavior by using an unchecked block, e.g.:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
contract C {
    function f(uint a, uint b) pure public returns (uint) {
        // This subtraction will wrap on underflow.
        unchecked { return a - b; }
    }
    function g(uint a, uint b) pure public returns (uint) {
        // This subtraction will revert on underflow.
        return a - b;
    }
}</pre>



<p>In this example, the <code>f(...)</code> function takes two <code>uint</code> arguments (only whole positive, unsigned numbers). By calling it as <code>f(2, 3)</code>, the result will be <code>2**256-1</code>, or in other words, the result will wrap around, starting on the left and coming on the far right side.</p>



<p>The same arithmetic operation, but with a checked variant, won&#8217;t make a wrap but instead cause a failing assertion.</p>



<p>We can use the unchecked block inside a block, but not as a standalone block or a replacement for a block.</p>



<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26a1.png" alt="⚡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Warning:</strong> An unchecked block cannot be nested. Also, the unchecked block effect applies only to the statements that are syntactically in the same block. Any function called from inside the block is not affected by the unchecked effect.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/top-8-scary-smart-contract-hacks-that-exploit-your-dapp-video/" data-type="post" data-id="437387" target="_blank" rel="noreferrer noopener">Top 8 Scary Smart Contract Hacks They Use to Exploit Your DApp [+Video]</a></p>



<h2 class="wp-block-heading">Checked and Unchecked Expressions in Solidity</h2>



<p>To avoid ambiguity, we cannot use the <code>_;</code> symbol inside an unchecked block. <code>_;</code> is a special symbol that marks the insertion point in a modifier&#8217;s body. A modified function&#8217;s code will be inserted and executed at this specific point (<a href="https://docs.soliditylang.org/en/v0.8.15/contracts.html#function-modifiers" target="_blank" rel="noreferrer noopener">docs</a>).</p>



<p>These operators will cause a failing assertion on overflow or underflow situations; they will also wrap without an error if they&#8217;re used inside an unchecked block: <code>++</code>, <code>--</code>, <code>+</code>, binary <code>-</code>, unary <code>-</code>, <code>*</code>, <code>/</code>, <code>%</code>, <code>**</code>, <code>+=</code>, <code>-=</code>, <code>*=</code>, <code>/=</code>, and <code>%=</code>.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26a1.png" alt="⚡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Warning</strong>: We cannot disable the check for division by zero or modulo by zero using the unchecked block.</p>



<p>Integer division and multiplication operations by a power of 2 can be substituted by equivalent bitwise shift operators. However, bitwise shift operators do not check for overflow or underflow situations. Specifically, <code>type(uint256).max &lt;&lt; 3</code> does not revert even though <code>type(uint256).max * 8</code> does.</p>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Note</strong>: If we do an edge-of-the-interval operation, such as in <code>int x = type(int).min; -x;</code> it will result in an overflow because the negative range always holds one more value than the positive range, e.g. as in an imaginary range <code>[-5, ..., 0, 4]</code>, where <code>-5</code> cannot be converted to <code>5</code>.</p>



<p>If we do an <a href="https://blog.finxter.com/solidity-conversions-elementary-types/" data-type="post" data-id="895022" target="_blank" rel="noreferrer noopener">explicit type conversion</a>, it will always truncate without a failing assertion, except when an integer is converted to an <a href="https://blog.finxter.com/solidity-string-literals-and-types-unicode-literals-hexadecimal-literals-and-enums/" data-type="post" data-id="776714" target="_blank" rel="noreferrer noopener">enum type</a>.</p>



<p>Unchecked expressions can be useful in certain situations, but it&#8217;s important to use them carefully and consider the potential risks and vulnerabilities they may introduce. By using unchecked expressions wisely, we can achieve a balance between flexibility, performance, and security that is right for our particular use case.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>In this article, we learned that checked and unchecked expressions are important concepts in Solidity programming. Checked expressions can enforce the correctness and security of our code, while unchecked expressions can improve the performance, but potentially lead to vulnerabilities if they&#8217;re used carelessly.</p>



<p>First, we got introduced to checked expressions in general. Then we learned about <code>require(...)</code> and <code>assert(...)</code> functions, and also mentioned the <code>revert(...)</code> and <code>abort(...)</code> functions.<br></p>



<p>Second, we explained the difference between the checked and unchecked expressions and showed how the <code>call(...)</code> function represents an unchecked expression.<br></p>



<p>Third, we went into detail on checked and unchecked arithmetic, explained when checked arithmetic became a default, and showed how to override the default behavior and perform the unchecked arithmetic.</p>



<h2 class="wp-block-heading">What&#8217;s Next?</h2>



<p>This tutorial is part of our extended Solidity documentation with videos and more accessible examples and explanations. You can navigate the series here (all links open in a new tab):</p>



<div class="wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex">
<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://blog.finxter.com/solidity-scoping/" target="_blank" rel="noreferrer noopener"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f448.png" alt="👈" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Prev Tutorial</a></div>



<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://blog.finxter.com/solidity-deep-dive-syllabus-video-tutorial-resources/" target="_blank" rel="noreferrer noopener"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/261d.png" alt="☝" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Syllabus</a></div>



<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://blog.finxter.com/solidity-error-handling-with-assert-require-and-revert-functions/" target="_blank" rel="noreferrer noopener"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Next Tutorial</a></div>
</div>
<p>The post <a href="https://blog.finxter.com/solidity-checked-and-unchecked-expressions/">Solidity Checked and Unchecked Expressions</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>What is a zkEVM Rollup? A Simplified Guide to Ethereum&#8217;s Most Promising Scaling Solution</title>
		<link>https://blog.finxter.com/what-is-a-zkevm-rollup-a-simplified-guide-to-ethereums-most-promising-scaling-solution/</link>
		
		<dc:creator><![CDATA[Emily Rosemary Collins]]></dc:creator>
		<pubDate>Tue, 28 Mar 2023 08:57:27 +0000</pubDate>
				<category><![CDATA[Ethereum]]></category>
		<category><![CDATA[Smart Contracts]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1249502</guid>

					<description><![CDATA[<p>The exponential adoption of blockchain technology and smart contracts forces us to find new solutions to emerging scalability and efficiency challenges. One solution that has attracted attention in the Ethereum ecosystem is the zkEVM Rollup, a zero-knowledge (ZK) rollup designed to enhance the performance and security of smart contracts. Zero-knowledge rollup, or ZK-Rollup, is a ... <a title="What is a zkEVM Rollup? A Simplified Guide to Ethereum&#8217;s Most Promising Scaling Solution" class="read-more" href="https://blog.finxter.com/what-is-a-zkevm-rollup-a-simplified-guide-to-ethereums-most-promising-scaling-solution/" aria-label="Read more about What is a zkEVM Rollup? A Simplified Guide to Ethereum&#8217;s Most Promising Scaling Solution">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/what-is-a-zkevm-rollup-a-simplified-guide-to-ethereums-most-promising-scaling-solution/">What is a zkEVM Rollup? A Simplified Guide to Ethereum&#8217;s Most Promising Scaling Solution</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>The exponential adoption of <a rel="noreferrer noopener" href="https://blog.finxter.com/introduction-to-smart-contracts-and-solidity-part-3-blockchain-basics/" data-type="post" data-id="537705" target="_blank">blockchain technology</a> and <a rel="noreferrer noopener" href="https://blog.finxter.com/i-created-a-counter-smart-contract-with-ether-js-heres-how/" data-type="post" data-id="1002304" target="_blank">smart contracts</a> forces us to find new solutions to emerging scalability and efficiency challenges. One solution that has attracted attention in the <a rel="noreferrer noopener" href="https://blog.finxter.com/smart-contracts-and-evm/" data-type="post" data-id="92507" target="_blank">Ethereum ecosystem</a> is the <strong>zkEVM Rollup</strong>, a zero-knowledge (ZK) rollup designed to enhance the performance and security of smart contracts.</p>



<p>Zero-knowledge rollup, or <a href="https://blog.chain.link/zkevm/" data-type="URL" data-id="https://blog.chain.link/zkevm/" target="_blank" rel="noreferrer noopener">ZK-Rollup</a>, is a second-layer scaling solution that uses zero-knowledge proofs to bundle multiple transactions into a single proof that can be verified on the main Ethereum network. This technique significantly reduces the amount of data stored on the blockchain, thus improving its scalability and boosting transaction throughput. </p>



<p class="has-global-color-8-background-color has-background"><strong>A zkEVM Rollup is an attempt to build an <a href="https://blog.finxter.com/mastering-the-ethereum-virtual-machine-evm-for-solidity-smart-contracts/" data-type="post" data-id="572801" target="_blank" rel="noreferrer noopener">Ethereum Virtual Machine (EVM)</a>-compatible Rollup with zk-proofs while preserving the EVM codes and the knowledge derived from it. </strong><a href="https://chainstack.com/zkevm-and-zkrollups-explained/">(source)</a></p>



<p>By leveraging zkEVM Rollups, Ethereum can benefit from increased transaction capacity, reduced gas fees, and improved security. As the Ethereum community and developers continue to explore and implement zkEVM Rollups, this technology has the potential to play a pivotal role in the broader adoption of blockchain and smart contracts.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="ROLLUPS - The Ultimate Ethereum Scaling Strategy? Arbitrum &amp; Optimism Explained" width="937" height="527" src="https://www.youtube.com/embed/7pWxCklcNsU?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>Next, I&#8217;ll gradually build your knowledge of zkEVMs. Let&#8217;s start with the first profound question: <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h2 class="wp-block-heading">What is the Ethereum Virtual Machine (EVM)?</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="713" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-379-1024x713.png" alt="" class="wp-image-1249526" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-379-1024x713.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/03/image-379-300x209.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-379-768x535.png 768w, https://blog.finxter.com/wp-content/uploads/2023/03/image-379.png 1388w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption"><a href="https://takenobu-hs.github.io/downloads/ethereum_evm_illustrated.pdf" data-type="URL" data-id="https://takenobu-hs.github.io/downloads/ethereum_evm_illustrated.pdf" target="_blank" rel="noreferrer noopener">Source</a></figcaption></figure>
</div>


<p>The Ethereum Virtual Machine (EVM) is like a giant computer brain <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f9e0.png" alt="🧠" class="wp-smiley" style="height: 1em; max-height: 1em;" /> that lives on the Ethereum blockchain. It&#8217;s responsible for keeping track of all the accounts and balances on the network, as well as executing smart contracts and other code. Think of it like a big, decentralized computer that processes all the transactions on the Ethereum blockchain <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4c8.png" alt="📈" class="wp-smiley" style="height: 1em; max-height: 1em;" />.</p>



<p>But what&#8217;s really cool about the EVM is that it&#8217;s designed to be totally transparent and open to everyone. Anyone can write code that runs on the EVM, and the rules for how that code interacts with the rest of the blockchain are all publicly available. This means that developers can build all sorts of amazing decentralized applications (dApps) on top of Ethereum <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" />.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="798" height="532" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-381.png" alt="" class="wp-image-1249577" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-381.png 798w, https://blog.finxter.com/wp-content/uploads/2023/03/image-381-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-381-768x512.png 768w" sizes="auto, (max-width: 798px) 100vw, 798px" /></figure>
</div>


<p>Of course, like any computer system, the EVM has to be secure and reliable, too. That&#8217;s why it&#8217;s designed to be totally decentralized and trustless. Instead of relying on a single central authority to keep everything running smoothly, the EVM is run by a network of nodes all around the world <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f30e.png" alt="🌎" class="wp-smiley" style="height: 1em; max-height: 1em;" />. These nodes work together to validate transactions and execute code, ensuring that everything is working as it should be.</p>



<p>So, in short, the Ethereum Virtual Machine is the heart and soul of the Ethereum blockchain <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1fac0.png" alt="🫀" class="wp-smiley" style="height: 1em; max-height: 1em;" />. It&#8217;s what makes everything possible, from sending Ether (ETH) to building complex decentralized applications. And it&#8217;s all powered by a global network of nodes working together to keep the system running smoothly <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f91d.png" alt="🤝" class="wp-smiley" style="height: 1em; max-height: 1em;" />.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/mastering-the-ethereum-virtual-machine-evm-for-solidity-smart-contracts/" data-type="post" data-id="572801" target="_blank" rel="noreferrer noopener">What is the Ethereum Virtual Machine (EVM)?</a></p>



<h2 class="wp-block-heading">What is a Rollup (L2) in Ethereum?</h2>



<p>A <strong>rollup</strong> is a Layer 2 (L2) scaling solution in Ethereum that aggregates multiple transactions off-chain and submits them to the Ethereum blockchain as a single transaction, reducing congestion and increasing efficiency (source: <a href="https://academy.shrimpy.io/post/what-is-layer-2-scaling-for-ethereum-the-best-layer-2-protocols-explained">Shrimpy</a>, <a href="https://www.coindesk.com/tech/2020/10/13/ethereums-top-dapps-are-increasingly-turning-to-rollups-heres-why/">CoinDesk</a>).</p>



<p>Rollups can be implemented as <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f510.png" alt="🔐" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Zero-Knowledge rollups (ZK-rollups)</strong> or <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f607.png" alt="😇" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Optimistic rollups</strong>, and both types use smart contracts to ensure the integrity of the transactions (source: <a rel="noreferrer noopener" href="https://ethereum.org/en/developers/docs/scaling/zk-rollups/" target="_blank">Ethereum.org</a>).</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="798" height="532" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-382.png" alt="" class="wp-image-1249581" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-382.png 798w, https://blog.finxter.com/wp-content/uploads/2023/03/image-382-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-382-768x512.png 768w" sizes="auto, (max-width: 798px) 100vw, 798px" /></figure>
</div>


<p>Here&#8217;s a short story explaining rollups as a series of emoijs:</p>



<p class="has-base-background-color has-background">Ethereum Rollup = <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f504.png" alt="🔄" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f9e9.png" alt="🧩" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4be.png" alt="💾" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4b0.png" alt="💰" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p>Here&#8217;s my interpretation of the emojis:</p>



<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" /> &#8211; Rollups help Ethereum scale and process more transactions faster.</p>



<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f504.png" alt="🔄" class="wp-smiley" style="height: 1em; max-height: 1em;" /> &#8211; Rollups aggregate multiple transactions off-chain and submit them to the Ethereum blockchain as a single transaction.</p>



<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f9e9.png" alt="🧩" class="wp-smiley" style="height: 1em; max-height: 1em;" /> &#8211; Rollups use smart contracts to ensure the integrity of the transactions.</p>



<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4be.png" alt="💾" class="wp-smiley" style="height: 1em; max-height: 1em;" /> &#8211; Rollups store the aggregated transactions off-chain, reducing congestion on the Ethereum blockchain.</p>



<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4b0.png" alt="💰" class="wp-smiley" style="height: 1em; max-height: 1em;" /> &#8211; Rollups can help reduce transaction fees and make Ethereum more accessible to everyone.</p>



<h2 class="wp-block-heading">What Is a zkEVM Rollup?</h2>



<p>A zkEVM rollup is a <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" /> zero-knowledge Ethereum Virtual Machine, which aims to replicate the Ethereum environment as a <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> rollup, allowing developers to build on it just like they would on Ethereum <a href="https://coinmarketcap.com/community/articles/38132/" target="_blank" rel="noreferrer noopener">(source)</a>. The primary function of this innovative technology is to combine the advantages of <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f310.png" alt="🌐" class="wp-smiley" style="height: 1em; max-height: 1em;" /> EVM compatibility and zero-knowledge rollups, offering a scalable and seamless developer experience <a href="https://blog.jarrodwatts.com/zkevms-and-the-race-to-scale-ethereum" target="_blank" rel="noreferrer noopener">(source)</a>.</p>



<p>With zkEVM rollups, Ethereum layer 2 scaling solutions become more efficient <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4c8.png" alt="📈" class="wp-smiley" style="height: 1em; max-height: 1em;" /> by transferring computation and state storage off-chain while processing thousands of transactions in a batch and submitting only minimal summary data with <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f512.png" alt="🔒" class="wp-smiley" style="height: 1em; max-height: 1em;" /> zero-knowledge proofs to the Ethereum Mainnet <a href="https://ethereum.org/en/developers/docs/scaling/zk-rollups/">(source)</a>. </p>



<p>This technique can potentially solve the <strong>scalability trilemma</strong>, making it a powerful tool for developers <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4aa.png" alt="💪" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <a href="https://blog.jarrodwatts.com/zkevms-and-the-race-to-scale-ethereum">(source)</a>.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="585" height="458" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-384.png" alt="" class="wp-image-1249595" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-384.png 585w, https://blog.finxter.com/wp-content/uploads/2023/03/image-384-300x235.png 300w" sizes="auto, (max-width: 585px) 100vw, 585px" /><figcaption class="wp-element-caption"><em><strong>Source</strong>: <a href="https://vitalik.ca/general/2021/04/07/sharding.html" data-type="URL" data-id="https://vitalik.ca/general/2021/04/07/sharding.html" target="_blank" rel="noreferrer noopener">Vitalik</a></em></figcaption></figure>
</div>


<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Explanation</strong>: The scalability trilemma is a concept in blockchain technology that posits that it is impossible to achieve all three of the following properties simultaneously: scalability, security, and decentralization. This means that a blockchain system can only optimize for two of these properties at the expense of the third. For example, if a blockchain system prioritizes scalability and security, it may sacrifice decentralization by relying on a smaller number of nodes to process transactions. Similarly, if a blockchain system prioritizes decentralization and security, it may sacrifice scalability by limiting the number of transactions that can be processed at any given time.</p>



<p>Due to their compatibility with Ethereum&#8217;s EVM, zkEVM rollups make it easy for developers to port existing <a href="https://blog.finxter.com/solidity-structure-of-a-smart-contract-basic-elements/" data-type="post" data-id="723680" target="_blank" rel="noreferrer noopener">Ethereum dApps</a> and tokens to this new environment, maximizing the benefits of Layer-2 blockchains <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f31f.png" alt="🌟" class="wp-smiley" style="height: 1em; max-height: 1em;" /> without losing the advantages of rollups <a href="https://blog.chain.link/zkevm/">(source)</a>.</p>



<p>So, in a nutshell, zkEVM rollups are the key <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f511.png" alt="🔑" class="wp-smiley" style="height: 1em; max-height: 1em;" /> to unlocking greater scalability, better throughput, and smooth developer experience on the Ethereum network. Ethereum scaling <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" />!</p>



<h2 class="wp-block-heading">How zkEVM Rollups Work</h2>



<p>In this section, we will explore the inner workings of zkEVM rollups, focusing on four key sub-sections: Zero-Knowledge Proofs, Batching Transactions, Data Availability, and Validation. Dive in and take a delightful journey through the world of zkEVM rollups. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2728.png" alt="✨" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h3 class="wp-block-heading">Zero-Knowledge Proofs</h3>



<p>At the heart of zkEVM rollups are zero-knowledge proofs (ZKP). <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> These cryptographic techniques allow one party to prove the validity of a statement without revealing any information about the statement itself. </p>



<p>In other words, <strong>Zero Knowledge Proofs (ZKPs)</strong> are a way for someone to prove that they know something (like a password or a secret) without actually revealing what that thing is. It&#8217;s like a secret handshake <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f91d.png" alt="🤝" class="wp-smiley" style="height: 1em; max-height: 1em;" />, but with math!</p>



<p>ZKPs are really useful for privacy and security. They allow people to prove that they have access to sensitive information without actually revealing that information to anyone else. For example, you could use a ZKP to prove that you&#8217;re over 18 without revealing your exact age.</p>



<p>In the context of blockchain, ZKPs are used to keep transactions private and secure. They allow people to prove that they have the right to make a transaction without revealing any other information about themselves or the transaction. This can help protect against fraud and hacking, and keep the blockchain more secure.</p>



<p>In the context of zkEVMs, ZKP verifies the legitimacy of off-chain transaction batches while maintaining privacy and data security. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f6e1.png" alt="🛡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> For a deeper understanding of Zero-Knowledge Proofs, check out <a rel="noreferrer noopener" href="https://www.alchemy.com/overviews/zkevm" target="_blank">Alchemy</a>.</p>



<h3 class="wp-block-heading">Batching Transactions</h3>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="798" height="532" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-385.png" alt="" class="wp-image-1249605" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-385.png 798w, https://blog.finxter.com/wp-content/uploads/2023/03/image-385-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-385-768x512.png 768w" sizes="auto, (max-width: 798px) 100vw, 798px" /></figure>
</div>


<p>Next up, batching transactions! </p>



<p>In zkEVM rollups, multiple transactions are grouped together into a single batch off-chain. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4e6.png" alt="📦" class="wp-smiley" style="height: 1em; max-height: 1em;" /> This efficient process significantly reduces the amount of on-chain data, which in turn lowers gas fees and increases throughput. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </p>



<p>To learn more about how batching transactions contribute to the scalability of Ethereum, refer to <a href="https://chainstack.com/zkevm-and-zkrollups-explained/" target="_blank" rel="noreferrer noopener">Chainstack Blog</a>.</p>



<h3 class="wp-block-heading">Data Availability</h3>



<p>Ensuring data availability is a crucial aspect of zkEVM rollups. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f310.png" alt="🌐" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Although transaction data is computed off-chain, it is imperative to maintain the data&#8217;s availability to all network participants. In zkEVMs, this is achieved through <strong>data availability proofs</strong>, which guarantee that off-chain computed data can always be accessed and reconstructed if needed. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f3d7.png" alt="🏗" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h3 class="wp-block-heading">Validation</h3>



<p>Last but not least, let&#8217;s talk about validation. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4bc.png" alt="💼" class="wp-smiley" style="height: 1em; max-height: 1em;" /> To maintain Ethereum&#8217;s security and prevent double-spending attacks, all transactions need to be verified. With zkEVM rollups, off-chain computation is combined with on-chain data availability and ZKP. This enables the Ethereum network to validate transactions without performing the full computation itself. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f393.png" alt="🎓" class="wp-smiley" style="height: 1em; max-height: 1em;" /> The result? A secure and efficient scaling solution. For a detailed look at zkEVM validation, check out <a href="https://ethereum.org/en/developers/docs/scaling/zk-rollups/">ethereum.org</a>.</p>



<h2 class="wp-block-heading">zkEVMs in the Wild &#8211; Polygon, ZKSync, Scroll</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="876" height="645" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-383.png" alt="" class="wp-image-1249584" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-383.png 876w, https://blog.finxter.com/wp-content/uploads/2023/03/image-383-300x221.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-383-768x565.png 768w" sizes="auto, (max-width: 876px) 100vw, 876px" /><figcaption class="wp-element-caption"><em><strong>Source</strong>: <a href="https://vitalik.ca/general/2022/08/04/zkevm.html" data-type="URL" data-id="https://vitalik.ca/general/2022/08/04/zkevm.html" target="_blank" rel="noreferrer noopener">Vitalik</a></em></figcaption></figure>
</div>


<p>As zkEVM rollups gain popularity, several projects have emerged that adopt this technology, such as <a href="https://blog.bingx.com/new-launch-analysis/what-is-zkevm-evm-types-of-zkevms-polygon-zkevm-zksync-and-scroll/">Polygon, ZKSync, and Scroll</a>. Let&#8217;s dive into these implementations and see how they are contributing to the wider Ethereum ecosystem. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f60e.png" alt="😎" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p><strong>Polygon zkEVM</strong> is a scaling solution designed to improve the throughput and reduce transaction costs on the Ethereum network. With its rollup-based architecture, it enables faster confirmations and enhanced security. Polygon&#8217;s vision is to create a mesh network of L2 solutions for Ethereum, and zkEVM plays a crucial role in realizing this ambition. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p><strong>ZKSync</strong> is another project leveraging zkEVM technology to achieve a powerful layer-2 scaling solution. It guarantees the security of smart contracts by using zero-knowledge proofs and aims to process thousands of transactions per second. <a href="https://docs.zksync.io/zkevm/" target="_blank" rel="noreferrer noopener">ZKSync</a> promises to significantly improve the user experience for both developers and end-users, making decentralized applications more accessible to a broader audience. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26a1.png" alt="⚡" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p>Lastly, <strong>Scroll</strong> is an innovative project that combines zkEVM rollups with a privacy-focused approach. It seeks to provide scalable, trustless, and private computation using zero-knowledge proof technology. While not much information about Scroll is available at the moment, it is definitely a project worth keeping an eye on as privacy becomes increasingly important in the blockchain space. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f575-fe0f-200d-2640-fe0f.png" alt="🕵️‍♀️" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p class="has-global-color-8-background-color has-background"><strong>zkEVM rollups like Polygon, ZKSync, and Scroll are paving the way for a more scalable, secure, and user-friendly Ethereum ecosystem.</strong> As these projects continue to develop and innovate, the potential for zkEVM technology to revolutionize the way we interact with decentralized applications becomes even more apparent. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f389.png" alt="🎉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h2 class="wp-block-heading">Benefits of zkEVM Rollups</h2>



<p></p>



<p>In this section, you&#8217;ll explore the advantages of using zkEVM rollups for off-chain computation and scaling while still maintaining compatibility with the Ethereum ecosystem. The primary benefits include improved scalability, security, and privacy.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="798" height="576" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-386.png" alt="" class="wp-image-1249608" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-386.png 798w, https://blog.finxter.com/wp-content/uploads/2023/03/image-386-300x217.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-386-768x554.png 768w" sizes="auto, (max-width: 798px) 100vw, 798px" /></figure>
</div>


<h3 class="wp-block-heading">Scalability</h3>



<p>zkEVM rollups boost the throughput of the Ethereum network by aggregating multiple transactions into a single proof, known as a Layer 2 protocol. The power of this technique lies in the ability to &#8220;roll up&#8221; a large batch of transactions and then use a zero-knowledge proof to verify them before submitting them back to the mainnet. This process significantly reduces transaction costs and increases transaction capacity <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f60e.png" alt="😎" class="wp-smiley" style="height: 1em; max-height: 1em;" />, making the Ethereum network more efficient and accommodating for users and developers.</p>



<h3 class="wp-block-heading">Security</h3>



<p>zkEVM rollups gain the advantage of the Ethereum network&#8217;s inherent security measures, making them an ideal solution for decentralized applications where trustless and secure environments are crucial <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f512.png" alt="🔒" class="wp-smiley" style="height: 1em; max-height: 1em;" />. By executing transactions off-chain through a zero-knowledge proof mechanism, the security of the main Ethereum network remains uncompromised even as throughput increases.</p>



<h3 class="wp-block-heading">Privacy</h3>



<p>With zkEVM rollups, privacy is enhanced through the utilization of zero-knowledge proofs. This process enables obfuscation and selective disclosure of transaction data, minimizing the risk of sensitive information being exposed <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f575-fe0f-200d-2642-fe0f.png" alt="🕵️‍♂️" class="wp-smiley" style="height: 1em; max-height: 1em;" />. This added layer of privacy makes zkEVM rollups an attractive option for applications where user anonymity and data protection are vital.</p>



<p class="has-global-color-8-background-color has-background"><strong>zkEVM rollups not only address the limitations of the Ethereum network, but also bring about essential improvements such as scalability, security, and privacy that cater to the dynamic demands of the burgeoning blockchain ecosystem <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a5.png" alt="💥" class="wp-smiley" style="height: 1em; max-height: 1em;" />.</strong> This makes them a fun yet powerful solution for a wide array of use cases and industries (see below). <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h2 class="wp-block-heading">Comparing zkEVM Rollups and Other Layer 2 Solutions</h2>



<p>As Ethereum strives for better scalability and faster transaction speeds, several Layer 2 solutions have emerged as potential options. This section will compare zkEVM Rollups with Optimistic Rollups, Plasma, and State Channels.</p>



<h3 class="wp-block-heading">Optimistic Rollups <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f603.png" alt="😃" class="wp-smiley" style="height: 1em; max-height: 1em;" /></h3>



<p>Optimistic Rollups offer an alternative scaling solution that allows developers to build and deploy contracts on Layer 2 while maintaining compatibility with Ethereum. These rollups are &#8220;optimistic&#8221; because they assume transactions are valid, and any disputes are resolved on-chain. But they have a longer confirmation time and higher gas fees than zkEVM Rollups, which utilize zero-knowledge proofs for quick, secure transactions <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" />.<a href="https://www.coindesk.com/tech/2022/07/27/ethereums-rollup-race-what-is-a-true-zkevm/">(source)</a></p>



<h3 class="wp-block-heading">Plasma <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f525.png" alt="🔥" class="wp-smiley" style="height: 1em; max-height: 1em;" /></h3>



<p>Plasma is a Layer 2 scaling solution that enables the creation of child chains off the main Ethereum blockchain. These child chains can process transactions independently and anchor their final states back to the Ethereum main chain. However, they are more suited to specific use cases, like token transfers and exchanges, than to general-purpose smart contracts. zkEVM Rollups aim to enable a broader range of applications by bringing the full Ethereum experience to Layer 2.<a href="https://blog.pantherprotocol.io/what-is-a-zkevm-heres-everything-you-need-to-know/">(source)</a></p>



<h3 class="wp-block-heading">State Channels <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26d3.png" alt="⛓" class="wp-smiley" style="height: 1em; max-height: 1em;" /></h3>



<p>State Channels allow off-chain transactions between participants without compromising security. These channels can be opened, closed, or updated by participants, with only the final state of the channel being submitted to the Ethereum blockchain. State Channels offer faster transactions with negligible fees, but their applicability is limited to specific scenarios, such as micropayments, and they don&#8217;t generalize well to complex smart contracts. zkEVM Rollups have an edge in providing the familiar Ethereum-like environment while scaling the network <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f31f.png" alt="🌟" class="wp-smiley" style="height: 1em; max-height: 1em;" />. <a href="https://scroll.io/blog/zkEVM">(source)</a></p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://vitalik.ca/general/2021/01/05/rollup.html" data-type="URL" data-id="https://vitalik.ca/general/2021/01/05/rollup.html" target="_blank" rel="noreferrer noopener">Vitalik&#8217;s Incomplete Guide to Rollups</a></p>



<h2 class="wp-block-heading">Use Cases and Applications</h2>



<p>As one of the most promising layer 2 scaling solutions for Ethereum, zkEVM rollups have a broad range of use cases and applications. Let&#8217;s dive into a few examples that will put the capabilities of zkEVM rollups into perspective<img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" />:</p>



<p>First, <strong>payments and swaps</strong> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4b8.png" alt="💸" class="wp-smiley" style="height: 1em; max-height: 1em;" /> are natural fits for zkEVM rollups. By bundling many transactions into a single proof, zkEVM rollups can reduce gas fees and improve transaction throughput. Platforms like <a href="https://loopring.org/">Loopring</a> are already leveraging zkEVM technology to offer efficient payment processing and token exchanges.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="798" height="553" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-387.png" alt="" class="wp-image-1249618" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-387.png 798w, https://blog.finxter.com/wp-content/uploads/2023/03/image-387-300x208.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-387-768x532.png 768w" sizes="auto, (max-width: 798px) 100vw, 798px" /></figure>
</div>


<p>Next, we have the booming world of <strong>Non-Fungible Tokens (NFTs)</strong> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f3a8.png" alt="🎨" class="wp-smiley" style="height: 1em; max-height: 1em;" />. Projects like <a href="https://immutable.com/">Immutable</a> are building on zkEVM rollups to facilitate minting and trading NFTs with reduced costs and increased speed. This makes it more accessible for artists and collectors to participate in the NFT marketplace, while also supporting gaming applications.</p>



<p>When it comes to <strong>decentralized finance (DeFi)</strong> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4b9.png" alt="💹" class="wp-smiley" style="height: 1em; max-height: 1em;" />, zkEVM rollups can provide enhanced scalability and privacy for lending, borrowing, and yield farming operations. DeFi platforms can leverage zkEVM rollups for optimized processing and cryptographic proofs, creating a more seamless experience for users.</p>



<p>These are just a few of the potential use cases for zkEVM rollups, and as the technology continues to mature, we can expect to see even more exciting and innovative applications across the Ethereum ecosystem. So, hold on to your hats, and let&#8217;s embrace the future of blockchain technology together! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f310.png" alt="🌐" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f31f.png" alt="🌟" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h2 class="wp-block-heading">&#8220;Rolling This Up&#8221; <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f363.png" alt="🍣" class="wp-smiley" style="height: 1em; max-height: 1em;" /></h2>



<p class="has-global-color-8-background-color has-background">In summary, a <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f9e9.png" alt="🧩" class="wp-smiley" style="height: 1em; max-height: 1em;" /> zkEVM (Zero-Knowledge Ethereum Virtual Machine) is a solution that aims to replicate the Ethereum environment using zero-knowledge proofs as rollups. This technology enhances Ethereum&#8217;s scalability and reduces costs while maintaining compatibility with its native programming environment.</p>



<p>Combining the power of <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4aa.png" alt="💪" class="wp-smiley" style="height: 1em; max-height: 1em;" /> zkRollups and the familiarity of the EVM, developers can utilize their existing knowledge and tools to build decentralized applications on layer 2 systems. The marriage of these concepts offers a more sustainable and efficient future for the Ethereum ecosystem.</p>



<p>As the blockchain space evolves and grows, we can expect further innovations fueled by the zkEVM concept <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" />. So, buckle up and get ready for an exciting ride in the world of decentralized applications! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f604.png" alt="😄" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f3a2.png" alt="🎢" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/email-academy/" data-type="page" data-id="12278" target="_blank" rel="noreferrer noopener">Join our free email academy</a> on exponential technologies such as AI, Blockchain development, and programming.</p>
<p>The post <a href="https://blog.finxter.com/what-is-a-zkevm-rollup-a-simplified-guide-to-ethereums-most-promising-scaling-solution/">What is a zkEVM Rollup? A Simplified Guide to Ethereum&#8217;s Most Promising Scaling Solution</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Solidity Scoping &#8211; A Helpful Guide with Video</title>
		<link>https://blog.finxter.com/solidity-scoping/</link>
		
		<dc:creator><![CDATA[Matija Horvat]]></dc:creator>
		<pubDate>Wed, 08 Mar 2023 16:11:29 +0000</pubDate>
				<category><![CDATA[dApp]]></category>
		<category><![CDATA[Ethereum]]></category>
		<category><![CDATA[Smart Contracts]]></category>
		<category><![CDATA[Solidity]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1191575</guid>

					<description><![CDATA[<p>As promised in the previous article, we&#8217;ll get more closely familiar with the concept of scoping next. We&#8217;ll explain what scoping is, why it exists, and how it helps us in programming. It&#8217;s part of our long-standing tradition to make this (and other) articles a faithful companion, or a supplement to the official Solidity documentation. ... <a title="Solidity Scoping &#8211; A Helpful Guide with Video" class="read-more" href="https://blog.finxter.com/solidity-scoping/" aria-label="Read more about Solidity Scoping &#8211; A Helpful Guide with Video">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/solidity-scoping/">Solidity Scoping &#8211; A Helpful Guide with Video</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>As promised in the <a rel="noreferrer noopener" href="https://blog.finxter.com/solidity-declarations-a-helpful-guide-with-video/" data-type="post" data-id="1191512" target="_blank">previous article</a>, we&#8217;ll get more closely familiar with the concept of scoping next. We&#8217;ll explain what scoping is, why it exists, and how it helps us in programming.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Solidity Scoping - A Helpful Guide" width="937" height="527" src="https://www.youtube.com/embed/JmEVpzi6OFQ?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="572" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-98-1024x572.png" alt="" class="wp-image-1191636" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-98-1024x572.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/03/image-98-300x168.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-98-768x429.png 768w, https://blog.finxter.com/wp-content/uploads/2023/03/image-98.png 1060w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>It&#8217;s part of our long-standing tradition to make this (and other) articles a faithful companion, or a supplement to the <a rel="noreferrer noopener" href="https://docs.soliditylang.org/en/v0.8.17/control-structures.html#scoping-and-declarations" data-type="URL" data-id="https://docs.soliditylang.org/en/v0.8.17/control-structures.html#scoping-and-declarations" target="_blank">official Solidity documentation</a>.</p>



<h2 class="wp-block-heading">Scopes Overview</h2>



<p>Scope refers to the context in which we can access a defined variable or a function. There are three main types of scope specific to Solidity: </p>



<ul class="wp-block-list">
<li><code>global</code>, </li>



<li><code>contract</code>, and </li>



<li><code>function</code> scope.</li>
</ul>



<p>In the <strong>global scope</strong>, variables, and functions are defined at the global level, i.e., outside of any contract or function, and we can access them from any place in the source code.</p>



<p>In the <strong>contract scope</strong>, variables and functions are defined within a contract, but outside of any function, so we can access them from anywhere within the specific contract. However, these variables and functions are inaccessible from outside the contract scope.</p>



<p>In the <strong>function scope</strong>, variables and functions are defined within a function and we can access them exclusively from inside that function.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="570" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-99-1024x570.png" alt="" class="wp-image-1191639" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-99-1024x570.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/03/image-99-300x167.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-99-768x428.png 768w, https://blog.finxter.com/wp-content/uploads/2023/03/image-99.png 1068w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Note</strong>: <br><br>The concept of scopes in Solidity is similar and based on the concept of scopes in the C99 programming language. In both languages, a &#8220;scope&#8221; refers to the context in which a variable or function is defined and can be accessed.<br><br>In C99 (a C language standard from 1999), variables and functions can be defined at either the global level (i.e., outside of any function) or within a function. There is no &#8220;contract&#8221; scope in C99.</p>



<h2 class="wp-block-heading">Global Scope</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="574" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-100-1024x574.png" alt="" class="wp-image-1191642" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-100-1024x574.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/03/image-100-300x168.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-100-768x430.png 768w, https://blog.finxter.com/wp-content/uploads/2023/03/image-100.png 1064w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Let&#8217;s take a look at a simple example of the global scope:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pragma solidity ^0.6.12;

uint public globalCounter;

function incrementGlobalCounter() public {
    globalCounter++;
}
</pre>



<p>In this example, the <code>globalCounter</code> variable is defined at the global level and is, therefore, in the global scope. We can access it from anywhere in the code, including from within the <code>incrementGlobalCounter(...)</code> function.</p>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Reminder</strong>: Global variables and functions can be accessed and modified by any contract or function that has access to them. We can find this behavior useful for sharing data across contracts or functions, but it can also present security risks if the global variables or functions are not properly protected.</p>



<h2 class="wp-block-heading">Contract Scope</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="571" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-101-1024x571.png" alt="" class="wp-image-1191643" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-101-1024x571.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/03/image-101-300x167.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-101-768x428.png 768w, https://blog.finxter.com/wp-content/uploads/2023/03/image-101.png 1066w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>As explained above, variables and functions defined within a contract (but outside of any function) are in contract scope, and we can access them from anywhere within the contract. </p>



<p>Contract-level variables and functions are useful for storing and manipulating data that is specific to a particular contract and is not meant to be shared with other contracts or functions.</p>



<p>Let&#8217;s take a look at a simple example of the contract scope:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pragma solidity ^0.6.12;

contract Counter {
    uint public contractCounter;

    function incrementContractCounter() public {
        contractCounter++;
    }
}
</pre>



<p>In this example, the <code>contractCounter</code> variable is defined within the <code>Counter</code> contract and is, therefore, in contract scope. It is available for access from anywhere within the <code>Counter</code> contract, including from within the <code>incrementContractCounter()</code> function.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26a1.png" alt="⚡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Warning</strong>: We should be aware that contract-level variables and functions are only accessible from within the contract in which they are defined. They cannot be accessed from other contracts or from external accounts.</p>



<h2 class="wp-block-heading">Function Scope</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="572" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-102-1024x572.png" alt="" class="wp-image-1191645" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-102-1024x572.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/03/image-102-300x167.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-102-768x429.png 768w, https://blog.finxter.com/wp-content/uploads/2023/03/image-102.png 1064w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Variables and functions that are defined within a function are in the function scope and can only be accessed from within that function. </p>



<p>Function-level variables and functions are useful for storing and manipulating data that is specific to a particular function and is not meant to be shared with other functions or with the contract as a whole.</p>



<p>Let&#8217;s take a look at the following example of the function scope:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pragma solidity ^0.6.12;

contract Counter {
    function incrementCounter(uint incrementAmount) public {
        uint functionCounter = 0;
        functionCounter += incrementAmount;
    }
}
</pre>



<p>In this example, the <code>functionCounter</code> variable is defined within the <code>incrementCounter(...)</code> function and is, therefore, in the function scope. It can only be accessed from within the <code>incrementCounter</code> function and is not accessible from other functions or from outside the contract.</p>



<h2 class="wp-block-heading">C99 Scoping Rules</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="574" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-103-1024x574.png" alt="" class="wp-image-1191646" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-103-1024x574.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/03/image-103-300x168.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-103-768x430.png 768w, https://blog.finxter.com/wp-content/uploads/2023/03/image-103.png 1064w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Now, let&#8217;s take a look at an interesting example showing minimal scoping by using curly braces:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0 &lt;0.9.0;
contract C {
    function minimalScoping() pure public {
        {
            uint same;
            same = 1;
        }

        {
            uint same;
            same = 3;
        }
    }
}
</pre>



<p>Each of the curly braces pair forms a distinct scope, containing a declaration and initialization of the variable same. </p>



<p>This example will compile without warnings or errors because each of the variable&#8217;s lifecycles is contained in its own disjoint scope, and there is no overlap between the two scopes.</p>



<h2 class="wp-block-heading">Shadowing</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="572" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-104-1024x572.png" alt="" class="wp-image-1191648" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-104-1024x572.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/03/image-104-300x167.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-104-768x429.png 768w, https://blog.finxter.com/wp-content/uploads/2023/03/image-104.png 1066w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>In some special cases, such as this one demonstrating C99 scoping rules below, we&#8217;d come across a phenomenon called shadowing. </p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Shadowing</strong> means that two or more variables share their name and have intersected scopes, with the first one as the outer scope and the second one as the inner scope. </p>



<p>Let&#8217;s take a closer look to get a better idea of what&#8217;s all about:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0 &lt;0.9.0;
// This will report a warning
contract C {
    function f() pure public returns (uint) {
        uint x = 1;
        {
            x = 2; // this will assign to the outer variable
            uint x;
        }
        return x; // x has value 2
    }
}
</pre>



<p>There are two variables called <code>x</code>; the first one is in the outer scope, and the second one is in the inner scope. </p>



<p>The inner scope is contained in or surrounded by the outer scope. </p>



<p>Therefore, the first and the second assignment assign the value 1, and then value 2 to the outer variable <code>x</code>, and only then will the declaration of the second variable <code>x</code> take place. </p>



<p>In this specific case, we&#8217;d get a warning from the <a href="https://blog.finxter.com/how-to-install-the-solidity-compiler-overview-videos/" data-type="post" data-id="716526" target="_blank" rel="noreferrer noopener">compiler</a>, because the first (outer) variable <code>x</code> is being shadowed by the second variable <code>x</code>.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26a1.png" alt="⚡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Warning</strong>: in versions prior to 0.5.0, Solidity used the same scoping rules as JavaScript: a variable declared at any location within the function would be visible through the entire function&#8217;s scope. That&#8217;s why the example below could&#8217;ve been compiled in Solidity versions before 0.5.0:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0 &lt;0.9.0;
// This will not compile
contract C {
    function f() pure public returns (uint) {
        x = 2;
        uint x;
        return x;
    }
}
</pre>



<p>The code above couldn&#8217;t compile in today&#8217;s versions of Solidity because an assignment to variable <code>x</code> is attempted before the variable itself is declared. In other words, the inner variable <code>x</code>&#8216;s scope starts with the line of its declaration.</p>



<h2 class="wp-block-heading"><a></a>Conclusion</h2>



<p>In this article, we learned about variable and function scopes.</p>



<ul class="wp-block-list">
<li>First, we made a scope overview, introducing ourselves to three different scopes in Solidity.</li>



<li>Second, we investigated the global scope by studying an appropriate example.</li>



<li>Third, we looked at the contract scope through an appropriate example.</li>



<li>Third, learned about the function scope on an appropriate example.</li>



<li>Fourth, we glanced at C99 scoping rules based on C99 &#8211; a C language standard.</li>



<li>Fifth, we also learned about shadowing and got an idea of why we should be careful about it.</li>
</ul>



<h2 class="wp-block-heading">What&#8217;s Next?</h2>



<p>This tutorial is part of our extended Solidity documentation with videos and more accessible examples and explanations. You can navigate the series here (all links open in a new tab):</p>



<div class="wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex">
<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://blog.finxter.com/solidity-declarations-a-helpful-guide-with-video/" target="_blank" rel="noreferrer noopener"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f448.png" alt="👈" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Prev Tutorial</a></div>



<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://blog.finxter.com/solidity-deep-dive-syllabus-video-tutorial-resources/" target="_blank" rel="noreferrer noopener"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/261d.png" alt="☝" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Syllabus</a></div>



<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://blog.finxter.com/solidity-checked-and-unchecked-expressions/" target="_blank" rel="noreferrer noopener"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Next Tutorial</a></div>
</div>
<p>The post <a href="https://blog.finxter.com/solidity-scoping/">Solidity Scoping &#8211; A Helpful Guide with Video</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 
Minified using Disk

Served from: blog.finxter.com @ 2026-06-06 09:21:15 by W3 Total Cache
-->