<?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>Solidity Archives - Be on the Right Side of Change</title>
	<atom:link href="https://blog.finxter.com/category/solidity/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.finxter.com/category/solidity/</link>
	<description></description>
	<lastBuildDate>Tue, 04 Apr 2023 15:10:06 +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>Solidity Archives - Be on the Right Side of Change</title>
	<link>https://blog.finxter.com/category/solidity/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<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 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 fetchpriority="high" 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="(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 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="(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>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>
		<item>
		<title>Solidity Declarations &#8211; A Helpful Guide with Video</title>
		<link>https://blog.finxter.com/solidity-declarations-a-helpful-guide-with-video/</link>
		
		<dc:creator><![CDATA[Matija Horvat]]></dc:creator>
		<pubDate>Wed, 08 Mar 2023 15:49:24 +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=1191512</guid>

					<description><![CDATA[<p>In this article, we&#8217;ll learn more about variable declarations in Solidity and further explain some of their specific behavior. To keep the article more succinct, we&#8217;ll focus on the next subject, scoping, in the next article. It&#8217;s part of our long-standing tradition to make this (and other) articles a faithful companion or a supplement to ... <a title="Solidity Declarations &#8211; A Helpful Guide with Video" class="read-more" href="https://blog.finxter.com/solidity-declarations-a-helpful-guide-with-video/" aria-label="Read more about Solidity Declarations &#8211; A Helpful Guide with Video">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/solidity-declarations-a-helpful-guide-with-video/">Solidity Declarations &#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>In this article, we&#8217;ll learn more about variable declarations in Solidity and further explain some of their specific behavior. To keep the article more succinct, we&#8217;ll focus on the next subject, scoping, in the next article.</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 Declarations - A Helpful Guide" width="937" height="527" src="https://www.youtube.com/embed/UeVMJzAUjJ0?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#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>


<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-94-1024x571.png" alt="" class="wp-image-1191620" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-94-1024x571.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/03/image-94-300x167.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-94-768x428.png 768w, https://blog.finxter.com/wp-content/uploads/2023/03/image-94.png 1066w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<h2 class="wp-block-heading">Variable Declaration and Initialization</h2>



<p>Before we step into the topic of declarations, let&#8217;s make a brief note of the difference between declaration and initialization. I find making this distinction useful because I noticed the two being interchanged quite often, although they mean entirely different things.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="567" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-95-1024x567.png" alt="" class="wp-image-1191622" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-95-1024x567.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/03/image-95-300x166.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-95-768x425.png 768w, https://blog.finxter.com/wp-content/uploads/2023/03/image-95.png 1068w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<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><em><strong>Variable declaration</strong></em> means we&#8217;re just declaring there&#8217;s a variable of a certain type (hence the term), but we&#8217;re not necessarily saying anything about the variable value. <br><br><em><strong>Variable initialization</strong></em> means we&#8217;re taking an existing variable and giving it some initial, also known as <em>default </em>value (hence the term). It&#8217;s quite common to do both at once, i.e., declare and initialize the variable.</p>



<p>Once a variable is only declared but not explicitly initialized, it will get an initial value. </p>



<p>This value varies from type to type, but the general underlying principle is the same: <strong><em>the initial value of any variable is the one whose byte representation is set to all zeros. </em></strong></p>



<p>This means that if we take a variable and look at it at a very low level, where individual bytes are visible, we&#8217;d see only zeros. This is not necessarily the same if we look at the same variable at a higher level. This state of &#8220;all zeros&#8221; is sometimes also called the &#8220;zero-state&#8221; of a 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>Note</strong>: A variable initialization can be <strong>implicit</strong> or <strong>explicit</strong>. <br><br>An <strong><em>implicit initialization</em></strong> is made by the Solidity compiler, according to the underlying type of the variable. <br><br>An <strong><em>explicit initialization</em></strong> is made by the programmer, i.e., in the code, setting the variable to a desired initial value, again, according to the variable type.</p>



<h2 class="wp-block-heading">Implicit Initializations of Variable Types</h2>



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



<p>Let&#8217;s take a brief overview of the simple, primitive variables and their initial default values, starting with the simpler types and going to the more complex types.</p>



<p>A <code>bool</code> variable has a default value of false because it corresponds to its zero state. An integer value in a signed variant <code>int</code> or unsigned variant <code>uint</code> has a default value of 0.</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>Recommended Read</strong>: <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">Understanding the Boolean Data Type in Solidity</a></p>



<p>Going over to the more complex types, statically-sized arrays and types <code>bytes1</code> to <code>bytes32</code>, each of their elements will also be set to a zero-state, i.e., their equivalent of zero. </p>



<ul class="wp-block-list">
<li>For dynamically-sized arrays and types of bytes and strings, their default value is an empty array or an empty string, respectively. </li>



<li>For even more complex, custom data types/structures, default values consist of (a set of) default values according to their underlying simpler types, since each complex type can be perceived as a set of simple(r) types.</li>
</ul>



<p>The effects of the implicit approach are two-fold; they make our coding more safe and enjoyable but can also make it ambiguous. Let&#8217;s take a look at both of these cases.</p>



<h2 class="wp-block-heading">Implicit Initialization and Value Ambiguity</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="566" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-97-1024x566.png" alt="" class="wp-image-1191631" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-97-1024x566.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/03/image-97-300x166.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-97-768x424.png 768w, https://blog.finxter.com/wp-content/uploads/2023/03/image-97.png 1061w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>In the first case, it prevents us from having uninitialized variables, which is a cause for many bugs in professional development. </p>



<p>For instance, in <a href="https://blog.finxter.com/best-programming-languages-to-start-freelancing-in-2020/" data-type="post" data-id="14208" target="_blank" rel="noreferrer noopener">languages</a> like Java, C, and C++, the default initialization value for some types of objects is null (we don&#8217;t have null or equivalent in Solidity). </p>



<p>Let&#8217;s see how implicit initialization aids us in our programming projects:</p>



<ul class="wp-block-list">
<li>In a simpler scenario, when a programmer just forgets to initialize his variables and objects to specific, non-null values but continues working with them as if he did initialize them. This type of bug is easy to notice and correct.</li>



<li>Another, more complex scenario is where, due to the logic of the program, the initialization is left for a later stage of the code, possibly in a branch that is conditionally (un)reachable. If the source code is poorly organized and extensive, such bugs are hard to catch because they occur only occasionally.</li>
</ul>



<p>Solidity takes care of both of these problems for us by not allowing a null value, therefore our programs will never experience bugs due to uninitialized variables.</p>



<p>However, there&#8217;s a catch in the second case, and let&#8217;s take a look at it more closely. Since Solidity implicitly initializes our variables if we don&#8217;t initialize them explicitly, the default value of a (primitive) variable is 0. </p>



<p>However, the result of our calculation may also be 0, and in that case, it&#8217;s impossible to differentiate whether the 0 came from implicit initialization without executing our calculation or is a result of our calculation. </p>



<p>A common approach to resolving such ambiguity is by introducing a variable, commonly called a <code>flag</code>, and conditionally setting it to some non-zero value during the calculation execution. That way, we can always tell if result 0 originated from the calculation, or the implicit initialization, just by looking at the flag.</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>: A flag is a common-purpose variable with a special (imaginary) role of tracking a certain program state. Flags are used to indicate a state of a calculation, function execution, readiness of a result, etc. We can think of a flag as a signaling light on a control panel. It&#8217;s entirely up to us to define a role for it and treat it that way.</p>



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



<p>In this article, we learned about the difference between variable declaration and initialization.</p>



<p>First, we learned about what variable declaration and initialization are. We also hinted there are two kinds of variable initializations: implicit and explicit.</p>



<p>Second, we went over implicit variable initializations for different variable types and also introduced the notion of zero-state value.</p>



<p>Third, we analyzed a very specific ambiguity regarding implicit initialization. This allowed us to introduce another interesting and very common tool in programming: a flag variable.</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-complications-with-arrays-and-structs-and-order-of-evaluation/" 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-scoping/" 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-declarations-a-helpful-guide-with-video/">Solidity Declarations &#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>
		<item>
		<title>$821,000 Ethereum Value per Solidity Developer</title>
		<link>https://blog.finxter.com/821000-ethereum-value-per-solidity-developer/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Tue, 31 Jan 2023 14:29:26 +0000</pubDate>
				<category><![CDATA[Career]]></category>
		<category><![CDATA[Ethereum]]></category>
		<category><![CDATA[Productivity]]></category>
		<category><![CDATA[Smart Contracts]]></category>
		<category><![CDATA[Solidity]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1099725</guid>

					<description><![CDATA[<p>Ethereum&#8217;s Total Value Locked (TVL) is $28,000,000,000 USD and Ethereum&#8217;s market cap is $193,000,000,000 USD. Based on my estimations below, there are at most 269,000 monthly active Solidity developers. Therefore, the Ethereum TVL per Solidity developer is more than $104,000, and the Ethereum market cap per Solidity developer is more than $717,000. So for all ... <a title="$821,000 Ethereum Value per Solidity Developer" class="read-more" href="https://blog.finxter.com/821000-ethereum-value-per-solidity-developer/" aria-label="Read more about $821,000 Ethereum Value per Solidity Developer">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/821000-ethereum-value-per-solidity-developer/">$821,000 Ethereum Value per Solidity Developer</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Ethereum&#8217;s Total Value Locked (TVL) is <a rel="noreferrer noopener" href="https://defillama.com/chain/Ethereum" data-type="URL" data-id="https://defillama.com/chain/Ethereum" target="_blank">$28,000,000,000 USD</a> and Ethereum&#8217;s market cap is <a rel="noreferrer noopener" href="https://coinmarketcap.com/currencies/ethereum/" data-type="URL" data-id="https://coinmarketcap.com/currencies/ethereum/" target="_blank">$193,000,000,000 USD</a>. Based on my estimations below, there are at most 269,000 monthly active Solidity developers. </p>



<p class="has-global-color-8-background-color has-background">Therefore, the Ethereum TVL per Solidity developer is more than <strong>$104,000</strong>, and the Ethereum market cap per Solidity developer is more than <strong>$717,000</strong>. So for all practical purposes, you can assume that the total value locked per Solidity developer is at least <strong>$821,000</strong>.*</p>



<p><em>*I used very conservative assumptions; the real numbers will be much higher (see below). Also, I&#8217;m aware that not all Ethereum developers use Solidity, but most (see below). At the time of writing, we&#8217;re amid a bear market in 2023, with the TVL of both Ethereum and its Solidity smart contracts down roughly 70%. As the number of developers doesn&#8217;t grow proportionally to the price in a bull market, this number can be seen as a historic &#8220;worst-case&#8221; estimation.</em></p>



<h2 class="wp-block-heading">How Many Monthly Active Solidity Developers Are There?</h2>



<p class="has-global-color-8-background-color has-background">My basic assumption is that a monthly active Solidity developer checks the Solidity docs at least once per month. Currently, the Solidity docs have 580,000 visits per month and 2.15 pages per visit, so our estimate is 269,000 active Solidity developers per month. </p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="884" height="567" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-369.png" alt="" class="wp-image-1099764" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-369.png 884w, https://blog.finxter.com/wp-content/uploads/2023/01/image-369-300x192.png 300w, https://blog.finxter.com/wp-content/uploads/2023/01/image-369-768x493.png 768w" sizes="auto, (max-width: 884px) 100vw, 884px" /><figcaption class="wp-element-caption"><a href="https://www.similarweb.com/website/soliditylang.org/#ranking" data-type="URL" data-id="https://www.similarweb.com/website/soliditylang.org/#ranking" target="_blank" rel="noreferrer noopener">Source</a></figcaption></figure>
</div>


<p><strong>Reasons there are more Solidity developers:</strong> Some active Solidity developers may not check out the docs during development. However, I think this won&#8217;t change the number by more than a factor of 2-3x. </p>



<p><strong>Reasons there are fewer Solidity developers:</strong> On the other hand, this may be a significant overestimation of the number of Solidity devs because the number of sessions may be much larger than the number of active users. Many Solidity developers will check out the docs multiple times per month! </p>



<p>So, the 269,000 Solidity developers per month number is likely to be a significant overestimation and can be seen as an upper bound. Consequently, the TVL per Solidity developer will be much larger than our $821,000 number, even considering that not all ETH dApp developers use Solidity (only most).</p>



<p>If you&#8217;re interested in learning to create your own dApps and participate in this highly profitable growth market, check out our new Finxter Academy course:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://academy.finxter.com/university/blockchain-development-creating-a-decentralized-app-to-sell-ebooks/" target="_blank" rel="noreferrer noopener"><img loading="lazy" decoding="async" width="909" height="272" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-371.png" alt="" class="wp-image-1099821" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-371.png 909w, https://blog.finxter.com/wp-content/uploads/2023/01/image-371-300x90.png 300w, https://blog.finxter.com/wp-content/uploads/2023/01/image-371-768x230.png 768w" sizes="auto, (max-width: 909px) 100vw, 909px" /></a></figure>
</div><p>The post <a href="https://blog.finxter.com/821000-ethereum-value-per-solidity-developer/">$821,000 Ethereum Value per Solidity Developer</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-04-06 20:10:34 by W3 Total Cache
-->