{"id":2248,"date":"2018-12-22T20:06:32","date_gmt":"2018-12-22T20:06:32","guid":{"rendered":"http:\/\/www.talkcrypto.org\/blog\/?p=2248"},"modified":"2020-06-03T12:44:42","modified_gmt":"2020-06-03T00:44:42","slug":"understanding-basic-functions-in-solidity","status":"publish","type":"post","link":"https:\/\/www.talkcrypto.org\/blog\/2018\/12\/22\/understanding-basic-functions-in-solidity\/","title":{"rendered":"Understanding basic functions in solidity"},"content":{"rendered":"<p>Smart contracts are comprised mainly of functions so it is important to understand how to construct one and all the various options available.<\/p>\n<p>From the <a href=\"https:\/\/solidity.readthedocs.io\/en\/v0.4.21\/types.html#function-types\" target=\"_blank\" rel=\"noopener\">solidity documentation<\/a>, the syntax of a function is as follows:<\/p>\n<p>function\u00a0FunctionName([parameters]) {public|private|internal|external} [pure|constant|view|payable] [modifiers] [returns\u00a0(&lt;return types&gt;)]\n<p>What this means is that when creating a function, here are the required steps.<\/p>\n<ol>\n<li>Use the <strong>function<\/strong> keyword<\/li>\n<li>Provide a function name<\/li>\n<li>Provide parameters if required<\/li>\n<li>Set the function&#8217;s visibility. There&#8217;s 4 options to choose from.\u00a0<strong class=\"markup--strong markup--p-strong\"><em class=\"markup--em markup--p-em\">public, private, internal, or external<\/em><\/strong>:<\/li>\n<li>Set the behaviour of the function. Choose from\u00a0<strong>view,\u00a0<\/strong><strong>pure, or payable<\/strong>.<\/li>\n<li>Add any applicable modifiers<\/li>\n<li>Add any applicable return types\/parameters<\/li>\n<\/ol>\n<p>Here is a brief explanation of the different visibilities.<\/p>\n<p><strong>Public:<\/strong>\u00a0All (contracts can a call the function)<br \/>\n<strong>Private: <\/strong>Only this contract<br \/>\n<strong>Internal<\/strong> &#8211; only this contract and contracts deriving from it<br \/>\n<strong>External<\/strong> &#8211; Cannot be accessed internally, only externally.<\/p>\n<p>Private is a subset of internal and external is a subset of public. For a more detailed and intriguing analysis of the difference between public and external check <a href=\"https:\/\/ethereum.stackexchange.com\/questions\/19380\/external-vs-public-best-practices\" target=\"_blank\" rel=\"noopener\">this<\/a>. (TLDR: public uses more gas because it uses memory instead of calldata). (Check the <a href=\"https:\/\/solidity.readthedocs.io\/en\/v0.5.0\/contracts.html#visibility-and-getters\" target=\"_blank\" rel=\"noopener\">docs<\/a>\u00a0for more details).<\/p>\n<p>The behaviours are defined as:<\/p>\n<p><strong>View<\/strong>: Can read the state but will not modify storage state in any way.<br \/>\n<strong>Pure<\/strong>: More restrictive than view and does not read or write to the storage state<br \/>\n<strong>Payable<\/strong>: Accepts incoming payments<\/p>\n<p>As noted in the <a href=\"https:\/\/solidity.readthedocs.io\/en\/v0.5.0\/contracts.html#view-functions\" target=\"_blank\" rel=\"noopener\">docs<\/a>, statements that are considered modifying state include:<\/p>\n<ol class=\"arabic simple\">\n<li>Writing to state variables.<\/li>\n<li><span class=\"std std-ref\">Emitting events<\/span>.<\/li>\n<li><span class=\"std std-ref\">Creating other contracts<\/span>.<\/li>\n<li>Using\u00a0<code class=\"docutils literal notranslate\"><span class=\"pre\">selfdestruct<\/span><\/code>.<\/li>\n<li>Sending Ether via calls.<\/li>\n<li>Calling any function not marked\u00a0<code class=\"docutils literal notranslate\"><span class=\"pre\">view<\/span><\/code>\u00a0or\u00a0<code class=\"docutils literal notranslate\"><span class=\"pre\">pure<\/span><\/code>.<\/li>\n<li>Using low-level calls.<\/li>\n<li>Using inline assembly that contains certain opcodes.<\/li>\n<\/ol>\n<p>View and pure replaces the &#8220;constant&#8221; keyword and\u00a0indicates to the compiler that storage data\u00a0would not be written\u00a0as a result of the\u00a0function call. Therefore \u00a0<strong>network verification is not required<\/strong>. This means no transaction\u00a0to mine, resulting in no gas needed to be spent.\u00a0These functions were essentially look-ups for data held in or derived from a contract&#8217;s state.<\/p>\n<p><a href=\"https:\/\/medium.com\/javascript-scene\/master-the-javascript-interview-what-is-a-pure-function-d1c076bec976\" target=\"_blank\" rel=\"noopener\">Pure functions<\/a> are completely independent of outside state,\u00a0are the simplest reusable building blocks of code in a program, and are recommended to be used. For further reading, check this out:\u00a0https:\/\/www.youfoundron.com\/blog\/solidity-constant-vs-view-vs-pure\/<\/p>\n<p>Let&#8217;s ignore modifiers for now. For return type, if the function returns something this is required. Let&#8217;s look at some examples.<\/p>\n<pre>function getMessage() public view returns (string memory) {\n   return message;\n}<\/pre>\n<p>Here is a simple function. Let&#8217;s use our checklist.<\/p>\n<ol>\n<li>Use the function keyword. <strong>YES<\/strong><\/li>\n<li>Provide a function name. <strong>getMessage<\/strong><\/li>\n<li>Provide parameters if required. <strong>No parameters here.\u00a0<\/strong><\/li>\n<li>Set the function&#8217;s visibility. <strong>Public<\/strong><\/li>\n<li>Set the behaviour of the function. <strong>View<\/strong><\/li>\n<li>Add any applicable modifiers. <strong>No modifiers<\/strong><\/li>\n<li>Add any applicable return types\/parameters. <strong>Returns 1 parameter of type string located in memory. NB: in v5.0+ data location needs to be specified.\u00a0<\/strong><\/li>\n<\/ol>\n<h3>Payable functions<\/h3>\n<p>A payable function is one where ether can be sent to it. This is how ether can be sent to a smart contract. Examples include:<\/p>\n<pre>function deposit() payable {};\n\nfunction payme() payable{\n  amount += msg.value;\n}<\/pre>\n<p>NB: It is not possible to have payable as a function name as it is a reserved keyword.<\/p>\n<p>Here is a full contract to try:<\/p>\n<pre>pragma solidity ^0.5.1;\n\ncontract HelloWorld {\n  string message = \"Welcome\";\n\n  function getMessage() public view returns (string memory) {\n    return message;\n  }\n\n  function getBalance() public view returns (uint256){\n    return address(this).balance;\n  }\n\n  function acceptPayment() public payable{ }\n}<\/pre>\n<h3>Fallback function<\/h3>\n<p>There is a special feature in a solidity smart contract where it can have precisely one unnamed function which cannot have any arguments or return anything back. This is called a fallback function. This fall back function gets executed when a\u00a0contract is called and\u00a0no\u00a0other\u00a0function\u00a0matches, or if\u00a0no\u00a0data\u00a0is supplied.<\/p>\n<pre>pragma solidity 0.5.1;\n\ncontract fallingback {\n    \n    function () external {\n        \n    }\n}<\/pre>\n<p>Note that in v0.5 and above, fallback functions need to be defined as external. This fallback function doesn&#8217;t do anything useful. The following is more useful.<\/p>\n<pre>pragma solidity 0.5.1;\n\ncontract fallingback {\n    \n    \/\/ fall back function\n    function () external payable {\n    }\n    \n    \/\/ getter function\n    function getBalance() public payable returns (uint256) {\n        return address(this).balance;\n    }\n}<\/pre>\n<p>Deploy this in Remix and run the fallback function and don&#8217;t forget to include a value of say 1 ether. Then call the getBalance function.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Smart contracts are comprised mainly of functions so it is<\/p>\n","protected":false},"author":1,"featured_media":2262,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4,2],"tags":[],"class_list":["post-2248","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-ethereum","category-smart-contracts"],"featured_image_urls":{"full":["https:\/\/www.talkcrypto.org\/blog\/wp-content\/uploads\/2018\/12\/functions.jpg",300,177,false],"thumbnail":["https:\/\/www.talkcrypto.org\/blog\/wp-content\/uploads\/2018\/12\/functions-150x150.jpg",150,150,true],"medium":["https:\/\/www.talkcrypto.org\/blog\/wp-content\/uploads\/2018\/12\/functions-300x177.jpg",300,177,true],"medium_large":["https:\/\/www.talkcrypto.org\/blog\/wp-content\/uploads\/2018\/12\/functions.jpg",300,177,false],"large":["https:\/\/www.talkcrypto.org\/blog\/wp-content\/uploads\/2018\/12\/functions.jpg",300,177,false],"1536x1536":["https:\/\/www.talkcrypto.org\/blog\/wp-content\/uploads\/2018\/12\/functions.jpg",300,177,false],"2048x2048":["https:\/\/www.talkcrypto.org\/blog\/wp-content\/uploads\/2018\/12\/functions.jpg",300,177,false],"chromenews-featured":["https:\/\/www.talkcrypto.org\/blog\/wp-content\/uploads\/2018\/12\/functions.jpg",300,177,false],"chromenews-large":["https:\/\/www.talkcrypto.org\/blog\/wp-content\/uploads\/2018\/12\/functions.jpg",300,177,false],"chromenews-medium":["https:\/\/www.talkcrypto.org\/blog\/wp-content\/uploads\/2018\/12\/functions.jpg",300,177,false]},"author_info":{"info":["seandotau"]},"category_info":"<a href=\"https:\/\/www.talkcrypto.org\/blog\/category\/ethereum\/\" rel=\"category tag\">Ethereum<\/a> <a href=\"https:\/\/www.talkcrypto.org\/blog\/category\/smart-contracts\/\" rel=\"category tag\">Smart Contracts<\/a>","tag_info":"Smart Contracts","comment_count":"1","_links":{"self":[{"href":"https:\/\/www.talkcrypto.org\/blog\/wp-json\/wp\/v2\/posts\/2248","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.talkcrypto.org\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.talkcrypto.org\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.talkcrypto.org\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.talkcrypto.org\/blog\/wp-json\/wp\/v2\/comments?post=2248"}],"version-history":[{"count":4,"href":"https:\/\/www.talkcrypto.org\/blog\/wp-json\/wp\/v2\/posts\/2248\/revisions"}],"predecessor-version":[{"id":2883,"href":"https:\/\/www.talkcrypto.org\/blog\/wp-json\/wp\/v2\/posts\/2248\/revisions\/2883"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.talkcrypto.org\/blog\/wp-json\/wp\/v2\/media\/2262"}],"wp:attachment":[{"href":"https:\/\/www.talkcrypto.org\/blog\/wp-json\/wp\/v2\/media?parent=2248"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.talkcrypto.org\/blog\/wp-json\/wp\/v2\/categories?post=2248"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.talkcrypto.org\/blog\/wp-json\/wp\/v2\/tags?post=2248"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}