{"id":7430,"date":"2024-03-21T08:03:50","date_gmt":"2024-03-21T08:03:50","guid":{"rendered":"https:\/\/metaschool.so\/articles\/?p=7430"},"modified":"2024-03-21T08:03:54","modified_gmt":"2024-03-21T08:03:54","slug":"function-modifiers-view-pure-payable-and-fallback-functions-in-solidity","status":"publish","type":"post","link":"https:\/\/metaschool.so\/articles\/function-modifiers-view-pure-payable-and-fallback-functions-in-solidity\/","title":{"rendered":"Function Modifiers (view, pure, payable) and Fallback Functions in Solidity"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_56_1 ez-toc-wrap-left counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title \" >Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/metaschool.so\/articles\/function-modifiers-view-pure-payable-and-fallback-functions-in-solidity\/#Function_modifiers\" title=\"Function modifiers\">Function modifiers<\/a><ul class='ez-toc-list-level-3'><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/metaschool.so\/articles\/function-modifiers-view-pure-payable-and-fallback-functions-in-solidity\/#1_view_modifier\" title=\"1. view modifier\">1. view modifier<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/metaschool.so\/articles\/function-modifiers-view-pure-payable-and-fallback-functions-in-solidity\/#2_pure_modifier\" title=\"2. pure modifier\">2. pure modifier<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/metaschool.so\/articles\/function-modifiers-view-pure-payable-and-fallback-functions-in-solidity\/#3_payable_modifier\" title=\"3. payable modifier\">3. payable modifier<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/metaschool.so\/articles\/function-modifiers-view-pure-payable-and-fallback-functions-in-solidity\/#Fallback_functions\" title=\"Fallback functions\">Fallback functions<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/metaschool.so\/articles\/function-modifiers-view-pure-payable-and-fallback-functions-in-solidity\/#Use_Cases_and_Best_Practices\" title=\"Use Cases and Best Practices\">Use Cases and Best Practices<\/a><ul class='ez-toc-list-level-3'><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/metaschool.so\/articles\/function-modifiers-view-pure-payable-and-fallback-functions-in-solidity\/#1_Security_Checks\" title=\"1. Security Checks\">1. Security Checks<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/metaschool.so\/articles\/function-modifiers-view-pure-payable-and-fallback-functions-in-solidity\/#2_Gas_optimization\" title=\"2. Gas optimization\">2. Gas optimization<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/metaschool.so\/articles\/function-modifiers-view-pure-payable-and-fallback-functions-in-solidity\/#3_Handling_Ether\" title=\"3. Handling Ether\">3. Handling Ether<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/metaschool.so\/articles\/function-modifiers-view-pure-payable-and-fallback-functions-in-solidity\/#Conclusion\" title=\"Conclusion\">Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n\n<h2 class=\"wp-block-heading\" id=\"function-modifiers\"><span class=\"ez-toc-section\" id=\"Function_modifiers\"><\/span>Function modifiers<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Function modifiers in Solidity are powerful tools for adding common functionality to multiple functions within a contract. They allow developers to enforce security checks, optimize gas usage, and handle special cases like Ether transactions. Solidity provides three main built-in modifiers: <code>view<\/code>, <code>pure<\/code>, and <code>payable<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"1-view-modifier\"><span class=\"ez-toc-section\" id=\"1_view_modifier\"><\/span>1. <code>view<\/code> modifier<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The <code>view<\/code> modifier indicates that the function will not modify the state of the contract. It&#8217;s akin to a read-only operation, allowing functions to fetch data from the blockchain without altering any values. By marking a function with <code>view<\/code>, Solidity ensures that it cannot change any state variables within the contract.<\/p>\n\n\n\n<pre class=\"wp-block-code has-nv-site-bg-background-color has-background\" style=\"font-size:18px\"><code>\/\/ SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ncontract MyContract {\n    uint256 public myNumber = 10;\n\n    function getNumber() public view returns (uint256) {\n        return myNumber;\n    }\n}<\/code><\/pre>\n\n\n\n<p>In this example, the <code>getNumber<\/code> function is marked with the <code>view<\/code> modifier because it only reads the value of <code>myNumber<\/code> without making any modifications to it. This is useful for querying contract states without incurring gas costs.<\/p>\n\n\n\n<p><strong>\ud83d\udd25 Check this course out:<\/strong>\u00a0<a href=\"https:\/\/metaschool.so\/courses\/create-your-own-ethereum-token-in-just-30-mins\" target=\"_blank\" rel=\"noreferrer noopener\">Create Your Own Ethereum Token in Just 30 Mins<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"2-pure-modifier\"><span class=\"ez-toc-section\" id=\"2_pure_modifier\"><\/span>2. <code>pure<\/code> modifier<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The <code>pure<\/code> modifier goes a step further than <code>view<\/code> by ensuring that the function does not even read the contract&#8217;s state. It&#8217;s reserved for functions that perform computations and return results solely based on their inputs, without interacting with the blockchain state.<\/p>\n\n\n\n<pre class=\"wp-block-code has-nv-site-bg-background-color has-background\" style=\"font-size:18px\"><code>\/\/ SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ncontract MathOperations {\n    function square(uint x) public pure returns (uint) {\n        return x * x;\n    }\n}<\/code><\/pre>\n\n\n\n<p>In the <code>MathOperations<\/code> contract, the <code>square<\/code> function is marked with <code>pure<\/code> because it only relies on its input <code>x<\/code> to compute and return the square, without accessing any state variables. This allows for efficient and predictable behavior, particularly in mathematical calculations.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"3-payable-modifier\"><span class=\"ez-toc-section\" id=\"3_payable_modifier\"><\/span>3. <code>payable<\/code> modifier<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The <code>payable<\/code> modifier is crucial for functions that can receive Ether along with the function call. Without this modifier, a function cannot accept Ether transfers, and sending Ether to such a function would result in an exception. This modifier is essential for implementing financial transactions in Solidity contracts.<\/p>\n\n\n\n<pre class=\"wp-block-code has-nv-site-bg-background-color has-background\" style=\"font-size:18px\"><code>\/\/ SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ncontract PayableContract {\n    function receivePayment() public payable {\n        \/\/ Code to handle received Ether\n    }\n}<\/code><\/pre>\n\n\n\n<p>In the <code>PayableContract<\/code> example, the <code>receivePayment<\/code> function is marked as <code>payable<\/code>, allowing it to receive Ether transfers along with the function call. This is commonly used for functions involved in crowdfunding, payments, or token purchases within smart contracts.<\/p>\n\n\n\n<p><strong>\ud83d\udd25 Check this course out:<\/strong>\u00a0<a href=\"https:\/\/metaschool.so\/courses\/one-piece-personality-dapp-solidity\" target=\"_blank\" rel=\"noreferrer noopener\">Build a One Piece Personality dApp With Solidity<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"fallback-functions\"><span class=\"ez-toc-section\" id=\"Fallback_functions\"><\/span>Fallback functions<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Fallback functions in Solidity are special functions that are executed if a contract is called and no other function matches the given function signature, or if Ether is sent directly to a contract without specifying a function to call. Fallback functions have no name and cannot accept arguments or return values.<\/p>\n\n\n\n<pre class=\"wp-block-code has-nv-site-bg-background-color has-background\" style=\"font-size:18px\"><code>\/\/ SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ncontract FallbackExample {\n    event Received(address sender, uint amount);\n\n    fallback() external payable {\n        emit Received(msg.sender, msg.value);\n    }\n}<\/code><\/pre>\n\n\n\n<p>In this example, the <code>fallback<\/code> function is triggered when someone sends Ether to the contract without specifying a function to call. It emits an event to log the sender&#8217;s address and the amount of Ether sent. Fallback functions are useful for handling unexpected interactions with contracts and managing Ether transfers.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"use-cases-and-best-practices\"><span class=\"ez-toc-section\" id=\"Use_Cases_and_Best_Practices\"><\/span>Use Cases and Best Practices<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Now that we understand function modifiers and fallback functions, let&#8217;s explore some common use cases and best practices for their usage.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"1-security-checks\"><span class=\"ez-toc-section\" id=\"1_Security_Checks\"><\/span>1. Security Checks<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Modifiers are often used to enforce security checks before executing a function. For example, you might have a modifier to restrict access to certain functions only to the contract owner or authorized users.<\/p>\n\n\n\n<pre class=\"wp-block-code has-nv-site-bg-background-color has-background\" style=\"font-size:18px\"><code>\/\/ SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ncontract AccessControl {\n    address public owner;\n\n    modifier onlyOwner() {\n        require(msg.sender == owner, \"Only contract owner can call this function\");\n        _;\n    }\n\n    constructor() {\n        owner = msg.sender;\n    }\n\n    function changeOwner(address newOwner) public onlyOwner {\n        owner = newOwner;\n    }\n}<\/code><\/pre>\n\n\n\n<p>In this <code>AccessControl<\/code> contract, the <code>onlyOwner<\/code> modifier ensures that only the contract owner can call functions restricted by this modifier. This helps prevent unauthorized access and protects sensitive operations within the contract.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"2-gas-optimization\"><span class=\"ez-toc-section\" id=\"2_Gas_optimization\"><\/span>2. Gas optimization<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Using <code>view<\/code> and <code>pure<\/code> modifiers can help optimize gas costs since they don&#8217;t involve state changes. This is especially important when interacting with contracts on the Ethereum blockchain, where gas fees can be significant. By marking functions appropriately, developers can reduce unnecessary gas consumption and make their contracts more efficient.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"3-handling-ether\"><span class=\"ez-toc-section\" id=\"3_Handling_Ether\"><\/span>3. Handling Ether<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>When dealing with Ether transactions, always use the <code>payable<\/code> modifier for functions that need to receive Ether. Additionally, make sure to implement a fallback function to handle unexpected Ether transfers. This ensures that contracts can gracefully handle Ether payments and prevent funds from being locked or lost.<\/p>\n\n\n\n<p><strong>\ud83d\udd25 Check this course out:<\/strong>\u00a0<a href=\"https:\/\/metaschool.so\/courses\/build-marketplace-erc404-tokens\" target=\"_blank\" rel=\"noreferrer noopener\">Build a Semi-Fungible ERC404 Tokens&#8217; Marketplace<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"conclusion\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In Solidity, function modifiers, and fallback functions are essential tools for defining the behavior and security of smart contracts. Modifiers allow for code reuse and enforce constraints, while fallback functions provide a fallback mechanism for handling unexpected calls and Ether transfers. Understanding and correctly utilizing these features is crucial for writing efficient and secure smart contracts on the Ethereum blockchain. By applying best practices and considering the use cases outlined above, developers can create robust and reliable contracts that meet the needs of their applications.<\/p>\n\n\n\n<p><strong>Try it out, ask us questions, and tell us how it went by tagging Metaschool on Social Media.<\/strong><\/p>\n\n\n\n<p><strong>Follow us on<\/strong>&nbsp;\u2013<\/p>\n\n\n\n<p>\ud83d\udd2eTwitter \u2013\u00a0<a href=\"https:\/\/twitter.com\/0xmetaschool\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/twitter.com\/0xmetaschool<\/a><\/p>\n\n\n\n<p>\ud83d\udd17LinkedIn \u2013\u00a0<a href=\"https:\/\/www.linkedin.com\/company\/0xmetaschool\/\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/www.linkedin.com\/company\/0xmetaschool\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":15,"featured_media":7433,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"neve_meta_sidebar":"","neve_meta_container":"","neve_meta_enable_content_width":"","neve_meta_content_width":0,"neve_meta_title_alignment":"","neve_meta_author_avatar":"","neve_post_elements_order":"","neve_meta_disable_header":"","neve_meta_disable_footer":"","neve_meta_disable_title":"","footnotes":""},"categories":[292],"tags":[51,31,46,29],"class_list":["post-7430","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-answers","tag-blockchain","tag-ethereum-blockchain","tag-solidity","tag-web3"],"_links":{"self":[{"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/posts\/7430","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/users\/15"}],"replies":[{"embeddable":true,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/comments?post=7430"}],"version-history":[{"count":3,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/posts\/7430\/revisions"}],"predecessor-version":[{"id":7434,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/posts\/7430\/revisions\/7434"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/media\/7433"}],"wp:attachment":[{"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/media?parent=7430"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/categories?post=7430"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/tags?post=7430"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}