<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Oluwatosin Serah on Medium]]></title>
        <description><![CDATA[Stories by Oluwatosin Serah on Medium]]></description>
        <link>https://medium.com/@ajaotosinserah?source=rss-3012defd7eba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5UMxp-O6EPNrOJbvQVfPGA.jpeg</url>
            <title>Stories by Oluwatosin Serah on Medium</title>
            <link>https://medium.com/@ajaotosinserah?source=rss-3012defd7eba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 06:55:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ajaotosinserah/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A Practical Guide for Developers to Deploying Their First Smart Contract on Ethereum]]></title>
            <link>https://medium.com/@ajaotosinserah/a-practical-guide-for-developers-to-deploying-their-first-smart-contract-on-ethereum-3378f190600d?source=rss-3012defd7eba------2</link>
            <guid isPermaLink="false">https://medium.com/p/3378f190600d</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[remix]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[ethereum-blockchain]]></category>
            <dc:creator><![CDATA[Oluwatosin Serah]]></dc:creator>
            <pubDate>Mon, 26 Jun 2023 07:23:03 GMT</pubDate>
            <atom:updated>2023-06-26T07:23:03.163Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dofxt-rWnFd2kyPkoTOXPw.png" /></figure><p>Smart contracts have gained significant attention and popularity in the world of blockchain and cryptocurrency. Ethereum, with its robust blockchain infrastructure, has emerged as a leading platform for deploying dApps and executing smart contracts. While Web2 developers may be accustomed to building centralized applications, transitioning to Web3 development on Ethereum opens up a world of decentralized possibilities.</p><p>This tutorial aims to offer a comprehensive guide specifically tailored for Web2 developers who are interested in deploying their first smart contract on the Ethereum blockchain. By following this tutorial, you will gain a basic understanding of the process involved in building and deploying your own decentralized applications on the Ethereum blockchain.</p><h4>Prerequisites</h4><p>Before diving into the process of deploying a smart contract on Ethereum, it is essential to have a basic understanding of the following concepts and meet the requirements:</p><ul><li>Familiarity with the fundamentals of blockchain technology (distributed ledger, consensus mechanisms, immutability).</li><li>Key differences between centralized and decentralized applications (decentralized consensus, peer-to-peer networks, significance of smart contracts).</li><li>Knowledge of <a href="https://docs.soliditylang.org/en/v0.8.20/">Solidity</a>, the programming language used to write smart contracts on the Ethereum Blockchain.</li><li>Familiarity with blockchain terminologies (wallets, gas, block explorers, e.t.c.).</li><li>Ensure that you have <a href="https://www.youtube.com/watch?v=Af_lQ1zUnoM&amp;t=399s">Metamask</a> set up on your PC. If you haven’t done so already, you can add the Metamask browser extension using this <a href="https://chrome.google.com/webstore/detail/metamask/nkbihfbeogaeaoehlefnkodbefgpgknn">link</a> to your preferred web browser.</li><li>Get the Sepolia testnet faucet <a href="https://sepoliafaucet.com/">here </a>to enable you to cover the gas fees for deploying your smart contract on the Ethereum testnet.</li><li>A text editor: For this tutorial, we will make use of <a href="https://remix.ethereum.org/">REMIX</a>, a development environment that allows you to write and test smart contracts. It provides a user-friendly interface and a range of features to facilitate the development and deployment of smart contracts.</li></ul><h4>Decentralized applications (DApps)</h4><p>A DApp is an application that operates in a decentralized manner. It utilizes smart contracts to store the application’s business logic and state, replacing the traditional server-side component. However, it’s important to note that DApps encompass more than just smart contracts. At the minimum, a DApp consists of:</p><ul><li>Smart contracts on a blockchain, and</li><li>A web user interface.</li></ul><p>In a broader sense, a DApp is a web application that leverages open, decentralized, peer-to-peer infrastructure services.</p><h3>Tutorial</h3><h4>Step 1: Writing a simple store contract</h4><p>To create a basic store smart contract on Remix, you can proceed as follows:</p><ul><li>Go to the Remix website at <a href="https://remix.ethereum.org/">remix.ethereum.org</a> using a compatible web browser.</li><li>Locate the top left corner of the Remix UI and click on “Create a new file.”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yq6uH9HZJxYJo4l3w88DtA.png" /></figure><ul><li>Provide a name for the file, such as “SimpleStore.sol”. The extention “.sol” makes Remix know that the file is a solidity file.</li><li>Within the Remix editor, write the Solidity code for the simple store contract.</li></ul><p>Here’s an example of a basic store contract:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99f21ef8005c5a18e55c22365b912d68/href">https://medium.com/media/99f21ef8005c5a18e55c22365b912d68/href</a></iframe><p>The contract above provides a simple storage mechanism where an external caller or a user can store a message by calling the storeMessage function and retrieve the stored message by calling the retrieveMessage function. The message is stored in the contract&#39;s private message variable. Let’s break the code down:</p><p><strong>SPDX-License-Identifier</strong>:<strong> MIT</strong>: This is a standard SPDX license identifier, indicating that the contract is licensed under the MIT license. SPDX stands for Software Package Data Exchange. SPDX provides a consistent way to communicate and document software licenses, copyrights, and other relevant information associated with a software package. The SPDX specification includes standardized license identifiers, file-level information, copyright statements, and other metadata related to software packages.</p><p><strong>Pragma Directive</strong>:pragma solidity ^0.8.13; This specifies the version of the Solidity compiler that should be used. In this case, it indicates that the contract is compatible with Solidity version 0.8.13 or higher.</p><p><strong>Contract Declaration</strong>:contract SimpleStore { ... } Solidity, being an object-oriented programming language, encapsulates all code within curly brackets. The “SimpleStore” contract, which includes a private string variable and two functions, follows this convention.</p><p><strong>Private Variable</strong>:string private message; This line declares a private string variable called &quot;message.&quot; Theprivate keyword restricts access to this variable to only be within the contract itself.</p><p><strong>storeMessage Function:</strong></p><p>function storeMessage(string memory _msg) external { ... }This function is used to store a message. It takes a string input parameter _msg and does not return anything. You can choose to input a string of any length and then store it in the smart contract.</p><p>message = _msg;This line assigns the value of _msg to themessage variable, effectively storing the message within the contract.</p><p><strong>retrieveMessage Function</strong>:</p><p>function retrieveMessage() external view returns(string memory) { ... }This function is used to retrieve the stored message from the state of the contract. It does not take any input parameters and returns a string value.</p><p>return message;This line returns the value of themessage variable, allowing external callers to retrieve the stored message.</p><h4>Step 2: Compile your smart contract</h4><p>Once you have written your smart contract, you need to compile it into bytecode. In the Remix UI, navigate to the “Solidity Compiler” tab located on the left side. Select the appropriate Solidity compiler version (e.g., 0.8.13). Click on the “Compile SimpleStore.sol” button to compile the contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AXlgufuMBZxhGnRFU_Ftjw.png" /></figure><p>When the green check mark appears, it indicates that the contract has been compiled successfully.</p><h4>Step 3: Deploy your smart contract</h4><p>Moving on to the primary goal of our tutorial, which is deploying your smart contract, This is where you will actually send your smart contract to the Ethereum blockchain.</p><p>Navigate to the “Deploy &amp; Run Transactions” tab and select the desired environment, such as a JavaScript VM for local testing. However, for the purpose of this tutorial, we will be deploying directly on the Ethereum testnet, the Sepolia network. Click on Environment and choose “Injected Provider—Metamask” to connect to your metamask wallet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eOr2Z6xFBB9nfXx6soG4Ag.png" /></figure><p>Ensure your wallet is on the Sepolia network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i1BvRSmb9Am4o4CS1oDClA.png" /></figure><p>To deploy the contract, simply click on the “Deploy” button. This will trigger a pop-up from Metamask, asking you to confirm and sign the deployment transaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*3JfKPNQjVHEKcvtaf95B-w.png" /><figcaption>Confirm Deployment</figcaption></figure><h4>Step 6: Interact with the Deployed Contract</h4><p>Once the contract is deployed, you can interact with it using the user interface provided by Remix. For example, you can call thestoreMessage function to store a message and then use theretrieveMessage function to retrieve the stored message from the Ethereum blockchain, like in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Vq66cQsCMS-jnpaDHcKgA.png" /><figcaption>Contract Interaction</figcaption></figure><p>After storing the message “My first smart contract,” I retrieved the stored message using the retrieveMessage function. If you wish to view the contract address on the block explorer, you can do so by clicking <a href="https://sepolia.etherscan.io/address/0x51425b6b3A7617C2f2FCC245Ef8276b55Dc9698D">here</a>.</p><h4>Conclusion</h4><p>That’s it! You have successfully written and deployed your first smart contract on the Ethereum Blockchain using Remix. You can experiment further by modifying the contract code, deploying it on different networks, and interacting with it using Remix’s user interface. Here are some additional tips for Web2 developers who are new to Ethereum development:</p><ul><li>Start with a simple decentralized application (dApp). Begin with smaller projects to gain familiarity with Ethereum development before diving into more complex areas.</li><li>Avoid the urge to build the next big thing right away. It’s advisable to gradually progress and gain experience with Ethereum development by starting with smaller-scale projects.</li><li>Leverage a development environment like Remix. Tools like Remix can greatly simplify the process of developing and deploying Ethereum dApps, providing a user-friendly interface and a range of useful features.</li><li>Don’t hesitate to seek assistance. The Ethereum community is vast and active, with many experienced developers willing to offer guidance and support to newcomers. Don’t be afraid to ask questions or seek help when needed.</li></ul><p>By following these tips and continuing to explore Ethereum development, you can further enhance your skills and contribute to the thriving Ethereum ecosystem. I wish your codes bug-free!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3378f190600d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Addresses In Ethereum]]></title>
            <link>https://medium.com/@ajaotosinserah/mastering-addresses-in-ethereum-5411ba6c3b0f?source=rss-3012defd7eba------2</link>
            <guid isPermaLink="false">https://medium.com/p/5411ba6c3b0f</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[ethereum-blockchain]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[address]]></category>
            <dc:creator><![CDATA[Oluwatosin Serah]]></dc:creator>
            <pubDate>Thu, 01 Jun 2023 09:26:24 GMT</pubDate>
            <atom:updated>2023-06-01T09:26:24.277Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2_EWLFKl7P5kGEl3JazCbw.png" /></figure><p>Welcome 👋 to another article series on mastering Ethereum addresses. In this article, we will explore the fundamental aspects of Ethereum addresses and their crucial role within the Ethereum ecosystem. We will simplify complex concepts, provide practical examples, and share best practices to help you understand and utilize Ethereum addresses effectively.</p><p>By the end of this article, you will have a comprehensive understanding of Ethereum addresses, enabling you to confidently handle transactions, interact with smart contracts, and secure your assets within the Ethereum ecosystem. Let’s dive in and master addresses in Ethereum!</p><h3>What is an Ethereum address?</h3><p>Just like our traditional bank account used for making transactions. An Ethereum address is a 20-byte hexadecimal number that is used to identify an account on the Ethereum blockchain. They are unique identifiers used to send, receive, and store Ether (ETH), tokens, and access decentralized applications on the Ethereum blockchain. They serve as a digital representation of a participant or entity within the Ethereum ecosystem. Each Ethereum address is composed of a string of alphanumeric characters and typically starts with “0x” to indicate its hexadecimal format.</p><h4>Types of Accounts in Ethereum</h4><p>There are two types of Ethereum accounts each with its address:</p><ul><li><strong>Externally owned accounts (EOAs)</strong> are accounts that are controlled by users. EOAs can hold and manage Ether (ETH) and other tokens on the Ethereum blockchain. They are primarily used for initiating transactions, such as sending ether or tokens to other addresses. EOAs can be created by generating a new Ethereum account using wallet software like <a href="https://metamask.io/download/">MetaMask</a>.</li><li><strong>Contract accounts </strong>are owned by smart contracts and can be used to interact with the Ethereum blockchain. Contract addresses are unique addresses that are associated with smart contracts deployed on the Ethereum blockchain.</li></ul><blockquote>A smart contract is a self-executing program that runs on the Ethereum Virtual Machine (EVM) and performs predefined functions when triggered by certain conditions.</blockquote><p>When a smart contract is deployed, it is assigned a contract address, which serves as its identifier on the Ethereum network. Contract addresses are used to interact with smart contracts by sending transactions to invoke their functions,access their data, modify the contract’s state, or produce specific outputs.</p><p>So basically we have Externally Owned Addresses, and Contract Addresses.</p><h4>Difference Between EOAs and Contract Account</h4><ul><li>Creation: EOAs are created by users. In contrast, contract accounts are created by deploying a smart contract to the Ethereum blockchain.</li><li>Key Pair: EOAs have a private-public key pair. The private key is used to sign transactions and provide proof of ownership. Unlike EOAs, there are no public or private keys associated with a contract account.</li><li><strong>Control</strong>: EOAs are controlled by users, meaning that users have control over the private keys associated with their EOAs. In contrast, contract accounts are controlled by the logic of the smart contract code. The code defines the rules and behavior of the contract account.</li><li><strong>Transaction Signing</strong>: Only EOAs can sign transactions because they have a private key. The signature generated using the private key ensures the authenticity and integrity of the transaction. Contract accounts, however, cannot sign transactions since they lack a private key.</li><li><strong>Interactions:</strong> EOAs can interact with the Ethereum blockchain through transactions. They can send ether (ETH) or interact with other smart contracts by invoking their functions, while contract accounts can interact with the Ethereum blockchain through transactions and events, which are logged on the blockchain and can be observed by external parties.</li><li><strong>Actions</strong>: EOAs can perform actions explicitly allowed by the user. They can transfer funds, interact with contracts, and initiate various transactions based on the user’s intentions. On the other hand, contract accounts can perform actions explicitly allowed by the code. The behavior of a contract account is defined in the smart contract code, and it can only execute functions and actions that have been programmed into it.</li></ul><h4>Similarities between EOAs and Contract Accounts</h4><ul><li><strong>They both have addresses</strong>. EOAs and contract addresses are both 20-byte hexadecimal strings that identify the account on the Ethereum blockchain.</li><li><strong>They can both hold Ether and ERC-20 tokens</strong>. EOAs and contract accounts can both hold ether and tokens.</li><li><strong>They can both interact with the Ethereum blockchain</strong>. EOAs and contract accounts can both send and receive ether, and they can both interact with decentralized applications (DApps).</li></ul><h3>How Addresses are generated</h3><p>Ethereum addresses are generated using a process called the Elliptic Curve Digital Signature Algorithm (ECDSA). ECDSA is a cryptographic algorithm that uses a pair of keys, a public key and a private key, to sign and verify digital signatures.</p><blockquote>Digital signatures use cryptographic algorithms to generate a unique digital fingerprint, or hash, of a document or message. The hash is then encrypted using the signer’s private key to create a signature. The recipient can verify the authenticity of the signature by using the signer’s public key to decrypt the hash and comparing it to the hash of the original document or message. If the hashes match, the signature is valid.</blockquote><blockquote>A digital signature can be created to sign any message. For Ethereum transactions, the details of the transaction itself are used as the message. The mathematics of cryptography in this case, elliptic curve cryptography provides a way for the message (i.e., the transaction details) to be combined with the private key to create a code that can only be produced with knowledge of the private key. That code is called the <strong>digital signature.</strong></blockquote><h4>Externally Owned Address Generation</h4><p>The public key is calculated from the private key using elliptic curve multiplication, which is practically irreversible: <em>K</em> = <em>k</em> * <em>G</em>, where <em>k</em> is the private key, <em>G</em> is a constant point called the <em>generator point</em>, <em>K</em> is the resulting public key, and * is the special elliptic curve “multiplication” operator. <br><strong>Note that elliptic curve multiplication is not like normal multiplication.</strong></p><p>Arithmetic on the elliptic curve is different from “regular” integer arithmetic. A point (<em>G</em>) can be multiplied by an integer (<em>k</em>) to produce another point (<em>K</em>). But there is no such thing as <em>division</em>, so it is not possible to simply “divide” the public key <em>K</em> by the point <em>G</em> to calculate the private key <em>k</em>. <strong>This is a one-way mathematical function.</strong></p><p>A private key can be converted into a public key, but a public key cannot be converted back into a private key, because the math only works one way. The private key is used to sign transactions and prove ownership of an address.</p><p>🚨Never share your private key with anyone!!! Sharing your private key can lead to unauthorized access and control over your Ethereum account, including the ability to transfer or manipulate funds.</p><p><strong>Here are some other tips for keeping your Ethereum address and private key safe:</strong></p><ul><li>Store your private key in a secure offline location.</li><li>Use a strong password to protect your wallet.</li><li>Keep your software up to date.</li><li>Be careful of phishing attacks.</li></ul><p>Private keys should never be shared or disclosed with anyone, as they are the primary means of proving ownership and control over Ethereum addresses and the associated assets.</p><p><strong>Externally Owned Address are generated using the following steps:</strong></p><ul><li>Random Private Key: Let’s assume we generate a random private key: 0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef</li><li>Public Key Generation: Using the private key, we generate a corresponding public key using elliptic curve cryptography (specifically, the secp256k1 curve).</li><li>Hash Generation: We generate a hash of the public key using the Keccak-256 hashing algorithm. Public Key Hash: 0x4b6f5a3dfc911e992c3d8f38c6bb9d1563b5e9a526260ee1a83693a8e56f4f48</li><li>Address Derivation: From the Keccak-256 hash of the public key, we take the last 20 bytes (160 bits) to obtain the EOA address. EOA Address: 0x4b6f5a3dfc911e992c3d8f38c6bb9d1563b5e9a5</li><li>Prefixing: Finally, we prefix the 20-byte EOA address with “0x” to signify its hexadecimal format. Prefixed EOA Address: 0x4b6f5a3dfc911e992c3d8f38c6bb9d1563b5e9a5</li></ul><p>This is a simplified example to demonstrate the process of generating an EOA address. In reality, there are additional considerations such as key pair generation algorithms and encoding formats, but the basic concept remains the same.</p><h4><strong>Contract Address Generation</strong></h4><p>Contract addresses are generated using a combination of the deploying account’s address and a nonce value, which represents the number of transactions sent from that account.</p><p>The contract address is derived by RLP encoding the deploying account’s address and the nonce using the Keccak-256 hashing algorithm.</p><p>Contract addresses are deterministic, meaning that the same contract deployed from the same account with the same nonce will always result in the same address.</p><p><strong>Here is a more detailed explanation of the process:</strong></p><ul><li>The deploying account’s address is obtained. Let’s assume the deployer’s account’s address is: 0x0123456789abcdef0123456789abcdef0123456</li><li>The nonce value is obtained. Let’s assume the nonce value is 5</li><li>The deploying account’s address and the nonce value are concatenated. We concatenate the deploying account’s address and the nonce value: 0x0123456789abcdef0123456789abcdef01234565</li><li>The concatenation is then RLP encoded.<br> Keccak-256 Hash: 0x4b6f5a3dfc911e992c3d8f38c6bb9d1563b5e9a526260ee1a83693a8e56f4f48</li><li>The first 20 bytes of the hash are used as the contract address. <br>Following our example, the Contract Address is prefixed with the “0x” character.: 0x4b6f5A3dFc911E992c3D8F38C6bb9D1563B5e9A5</li></ul><p>Note that this is a simplified example for illustration purposes, and in practice, additional steps and considerations might be involved in the deployment process.</p><h4>Features of Ethereum Addresses</h4><ul><li>Ethereum addresses are 20 bytes long or 160 bits.</li><li>Ethereum addresses are represented in hexadecimal format, using base 16 notation. Each character in the address corresponds to 4 bits. An Ethereum address consists of exactly 40 characters, chosen from the range of 0–9 and a-f (a total of 16 possible values per character).</li><li>Ethereum addresses are always prefixed with “0x” to indicate the hexadecimal format. This prefix is necessary for distinguishing Ethereum addresses from other types of data. Hence, the total length of an Ethereum address, including the prefix, is 42 characters.</li></ul><p>By understanding the length, format, and prefix of Ethereum addresses, you can accurately identify and work with them in Solidity and other Ethereum-related applications.</p><blockquote>Solidity is the programming language used in writing Smart Contract on EVM compatible chains</blockquote><p>It is important to note that Ethereum addresses are case-insensitive, meaning that capitalization does not affect their interpretation. All wallets and systems within the Ethereum ecosystem are designed to accept Ethereum addresses expressed in either capital or lowercase characters without any distinction.</p><p>For example, the addresses</p><pre>&quot;0x4b6f5a3dfc911e992c3d8f38c6bb9d1563b5e9a5&quot; and <br>&quot;0x4B6F5A3DFC911E992C3D8F38C6BB9D1563B5E9A5&quot;</pre><p>would be considered the same address and refer to the same Ethereum account.</p><h4>Significance of hexadecimal representation in Ethereum addresses</h4><ul><li><strong>Compactness</strong>: Hexadecimal is a base-16 number system, which means that each digit can represent one of 16 values (0–9 and A-F). This makes hexadecimal addresses much more compact than decimal addresses, which would require 32 digits to represent the same information.</li><li><strong>Uniqueness</strong>: Hexadecimal addresses are unique, which is important for preventing fraud and errors. For example, if a decimal address were to be entered incorrectly, it could easily be mistaken for another address.</li><li><strong>Compatibility</strong>: Hexadecimal addresses are compatible with other blockchains that use hexadecimal addresses, such as Bitcoin and others. This makes it easy to transfer funds between different blockchains.</li></ul><h4>Significance of checksum feature in Ethereum addresses</h4><ul><li><strong>Error prevention</strong>: The checksum feature helps to prevent errors when entering Ethereum addresses. If an error is made, the checksum will not match, and the transaction will fail. This helps protect users from losing funds due to typos or other errors.</li><li><strong>Security</strong>: The checksum feature also adds an extra layer of security to Ethereum addresses. If an attacker were to try to create a fake address, the checksum would not match, and the transaction would fail. This helps protect users from fraud and theft.</li></ul><p>The hexadecimal representation and the checksum feature are both important features of Ethereum addresses. They help to ensure that addresses are compact, unique, compatible, error-proof, and secure. <a href="https://github.com/Ethereum/EIPs/blob/master/EIPS/eip-55.md">Check out EIP55 </a>for more details on checksums.</p><h4>Addresses in Solidity Smart Contract</h4><p>In Solidity, addresses are a primitive type. This means that they can be used in expressions and statements just like other primitive types, such as integers and strings.</p><p>Here are some of the things you can do with addresses in Solidity:</p><p><strong>Declaring an address variable in Solidity<br></strong>You can declare an address variable by using the address keyword. For example:</p><pre>address myAddress;</pre><p><strong>Assigning an address to a variable<br></strong>You can assign an address to a variable by using the = operator. For example:</p><pre>myAddress = 0x2e504C9c22089cE75a600fF113e891d2c2D53d57;</pre><p><strong>Comparing addresses in Solidity<br></strong> You can compare addresses using the == and != operators. For example:</p><pre>if (myAddress == 0x2e504C9c22089cE75a600fF113e891d2c2D53d57) {<br> // Do something<br>}</pre><p><strong>Accessing a smart contract address</strong> <br>You can access a smart contract’s address using the address(this) method. For example:</p><pre>address contractAddr = address(this);</pre><p><strong>Getting the balance of a smart contract address<br></strong>You can get the Ether balance of a smart contract using the address(this).balance method. For example:</p><pre>uint256 balance = address(this).balance;</pre><p><strong>Explicit address conversion in Solidity<br></strong>It is important to note that not all addresses are payable, and if you try to send ethers to a non-payable address, the transaction will fail. The conversion to “address payable” can be done using payable(address(x)). The conversion from address to “address payable” is done to enable sending ether to the address.</p><p>This conversion is used when calling a contract function that has the “payable” modifier, which allows it to receive ether. The “payable” keyword makes the function accept ether and increases the balance of the contract by the amount of ether received. <br><a href="https://medium.com/coinmonks/exploring-the-differences-between-payable-and-non-payable-functions-in-solidity-an-in-depth-d031c6ae577b">Check out my article on Payable and Nonpayable function to learn more.</a></p><pre>//address payable provides the transfer function<br>address payable payableAddress;</pre><p><strong>Sending Ether from a smart contract</strong> <br>You can send Ether from a smart contract using the send , transferor callmethod. For example:</p><pre>contract SendEther {<br>    function sendViaTransfer(address payable _to) public payable {<br>        // This function is no longer recommended for sending Ether.<br>        _to.transfer(msg.value);<br>    }<br><br>    function sendViaSend(address payable _to) public payable {<br>        // Send returns a boolean value indicating success or failure.<br>        // This function is not recommended for sending Ether.<br>        bool sent = _to.send(msg.value);<br>        require(sent, &quot;Failed to send Ether&quot;);<br>    }<br><br>    function sendViaCall(address payable _to) public payable {<br>        // Call returns a boolean value indicating success or failure.<br>        // This is the current recommended method to use.<br>        (bool sent, bytes memory data) = _to.call{value: msg.value}(&quot;&quot;);<br>        require(sent, &quot;Failed to send Ether&quot;);<br>    }<br>}</pre><p><strong>Interacting with a smart contract<br></strong>When it comes to interacting with a smart contract on the Ethereum blockchain, there are various methods available. One common way is to use the function call, delegatecall, or similar functions. For example:</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.17;<br><br>// NOTE: Deploy this contract first<br>contract B {<br>    // NOTE: storage layout must be the same as contract A<br>    uint public num;<br>    address public sender;<br>    uint public value;<br><br>    function setVars(uint _num) public payable {<br>        num = _num;<br>        sender = msg.sender;<br>        value = msg.value;<br>    }<br>}<br><br>contract A {<br>    uint public num;<br>    address public sender;<br>    uint public value;<br><br>    function setVars(address _contract, uint _num) public payable {<br>        // A&#39;s storage is set, B is not modified.<br>        (bool success, bytes memory data) = _contract.delegatecall(<br>            abi.encodeWithSignature(&quot;setVars(uint256)&quot;, _num)<br>        );<br>    }<br>}</pre><blockquote>The contract above consists of two contracts: contract A and contract B.</blockquote><blockquote>Contract B is designed to store three variables: num (an unsigned integer), sender (an address), and value (an unsigned integer). The setVars function in contract B allows these variables to be set with the provided values.</blockquote><blockquote>Contract A also has the same three variables: num, sender, and value. The setVars function in contract A is used to interact with contract B. It takes an address parameter _contract that represents the address of contract B and a uint parameter _num. Inside the setVars function in contract A, a delegatecall is made to contract B, passing the _num value to its setVars function.</blockquote><blockquote>The purpose of this contract is to demonstrate how a delegatecall can be used to interact with another contract and modify its storage. By making a delegatecall to contract B, contract A can modify its own storage variables using the setVars function of contract B. This can be useful in certain scenarios where you want to reuse or extend the functionality of another contract while maintaining the storage layout.</blockquote><p>Check out my article on <a href="https://medium.com/@ajaotosinserah/mastering-delegatecall-in-solidity-a-comprehensive-guide-with-evm-walkthrough-6ddf027175c7">Delegate</a>call to learn more.</p><p><strong>Returning an address type<br></strong>When working with smart contracts on Ethereum, it is common to have methods that return values for the address type. Here are a few examples of how you can handle methods that return an address:</p><ul><li>Mapping Access: If the method returns an address within a mapping, you can access it using the corresponding key. For example:</li></ul><pre>mapping(uint256 =&gt; address) addressesMapping;<br><br>address myAddress = addressesMapping[key];</pre><ul><li>Function Call: You can directly call the method and use the returned address value in subsequent operations. For example:</li></ul><pre>mapping(uint256 =&gt; address) addressesMapping;<br><br>function returnAddress(uint256 _key) external view returns(address){<br>    return addressesMapping[_key];<br>}</pre><ul><li>Array Access: If the method returns an address within an array, you can access it using the index. For example:</li></ul><pre>address myAddress = myArray[index];</pre><p><strong>Zero Address<br></strong>The zero address, also known as the null address or the zero account, refers to the Ethereum address:</p><pre>0x0000000000000000000000000000000000000000</pre><p>It is a special address in the Ethereum ecosystem that is hard-coded to have the value of all zeros. It is a special address that has no balance and cannot be used to send or receive transactions.</p><p>The zero address is used in a few different ways in Ethereum:</p><ul><li>To create new contracts: When a new contract is created, it is assigned the zero address. The contract’s address is then updated once the transaction is mined.</li><li>To burn tokens: When tokens are burned, they are sent to the zero address. This makes them permanently unavailable.</li></ul><p>Here are some of the things you cannot do with the zero address:</p><ul><li>Send Ether to the zero address: Any ether sent to the zero address is permanently lost.</li><li>Create a contract at the zero address: Any transaction that attempts to create a contract at the zero address will fail.</li><li>Interact with a contract at the zero address: Any transaction that attempts to interact with a contract at the zero address will fail.</li></ul><p>The zero address is a special address that should not be used for any purpose other than those listed above. If you send Ether to the zero address or attempt to create a contract or interact with a contract at the zero address, you will lose your funds or your transaction will fail.</p><h4>How Addresses are stored In the EVM</h4><p>Addresses are stored in the EVM’s state trie. The state trie is a data structure that stores all of the state information on the Ethereum blockchain. This includes the balances of all accounts, the code of all contracts, and the data of all storage variables.</p><p>The state trie is a Merkle tree, which is a type of data structure that is very efficient for storing and retrieving data. The state trie is organized by address, with each address having its own branch in the tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*i02oXrMuk-eorLuP-_oTLg.png" /><figcaption>Merkle Patricia Tree</figcaption></figure><p>When an address is stored in the EVM, it is first hashed using the Keccak-256 hashing algorithm. The hash is then used to find the corresponding branch in the state trie. The balance of the address, the code of any contracts at the address, and the data of any storage variables are all stored in this branch.</p><p>Addresses are stored in the EVM in a decentralized manner. This means that no single entity has control over the storage of addresses. This helps to ensure the security and reliability of the Ethereum network.</p><h4>Address obfuscation</h4><p>Address obfuscation is a technique that aims to hide or obfuscate the true ownership or identity associated with an Ethereum address. These techniques can be used to enhance privacy and prevent address-based tracking or analysis. This can be done by using a variety of techniques, such as:</p><ul><li><strong>Hashing</strong>: An Ethereum address can be hashed to create a shorter, more anonymous identifier.</li><li><strong>Nonce</strong>: A nonce is a random number that can be used to obfuscate an Ethereum address.</li><li><strong>Mixing</strong>: Multiple Ethereum addresses can be mixed together to create a single, anonymous address.</li></ul><p><strong>Here are a few commonly employed address obfuscation techniques:</strong></p><ol><li>Address Reuse Avoidance: To avoid address-based tracking, users can generate a new address for each transaction or interaction, ensuring that no two transactions are associated with the same address.</li><li>Coin Mixing: Coin mixing services (also known as coin tumblers or mixers) allow users to pool their funds with other users and then redistribute them to different addresses, making it difficult to trace the flow of funds.</li><li>Hierarchical Deterministic (HD) Wallets: HD wallets generate a hierarchical tree of addresses from a single master seed. By using different child addresses for each transaction, users can obfuscate their transaction history and ownership.</li><li>Stealth Addresses: Stealth addresses enable the recipient to generate a unique one-time address for each transaction. The sender encrypts the payment with the recipient’s stealth address, ensuring that only the intended recipient can decipher it.</li></ol><h4>Zero-knowledge proofs(ZKPs)</h4><p>Zero-knowledge proofs are a cryptographic technique that allows two parties to verify information about each other without revealing any confidential information. This can be used to protect user privacy on the Ethereum blockchain by allowing users to prove that they have certain assets without revealing the specific amounts or addresses.</p><h4>Benefits of using address obfuscation and Zero-knowledge proofs</h4><ul><li><strong>Increased privacy</strong>: Address obfuscation and ZKPs can help protect user privacy by making it difficult to associate an Ethereum address with a real-world identity.</li><li><strong>Reduced risk of fraud</strong>: Address obfuscation and ZKPs can help reduce the risk of fraud by making it more difficult for attackers to track user activity and steal funds.</li><li><strong>Improved user experience</strong>: Address obfuscation and ZKPs can help improve the user experience by making it easier for users to participate in decentralized applications without fear of their privacy being compromised.</li></ul><h4>Some of the drawbacks of using address obfuscation and ZKPs</h4><ul><li><strong>Reduced transparency</strong>: Address obfuscation and ZKPs can reduce transparency by making it more difficult to track the flow of funds on the Ethereum blockchain.</li><li><strong>Potential for abuse</strong>: Address obfuscation and ZKPs can be used to facilitate illegal activity.</li></ul><p>These privacy-focused solutions leverage advanced cryptographic techniques to protect user privacy, enhance transactional anonymity, and provide stronger privacy guarantees within the Ethereum ecosystem. They offer users more control over their personal information and mitigate the risks associated with address-based tracking and analysis.</p><h4>Conclusion</h4><p>Mastering Ethereum addresses is crucial for navigating the Ethereum ecosystem effectively. By mastering Ethereum addresses, you gain confidence in transactions, smart contract interactions, and asset security. Understanding best practices empowers participation in the decentralized revolution. Thank you for taking the time to read this article. I hope you found it informative and helpful in understanding Ethereum addresses. Stay tuned for my next article!</p><h4>References and Tools</h4><p><a href="https://docs.soliditylang.org/en/v0.8.20/types.html#address">Solidity Documentation on Addresses</a><br>M<a href="https://medium.com/@ajaotosinserah/mastering-delegatecall-in-solidity-a-comprehensive-guide-with-evm-walkthrough-6ddf027175c7">astering Delegatecall in Solidity</a><br><a href="https://medium.com/coinmonks/exploring-the-differences-between-payable-and-non-payable-functions-in-solidity-an-in-depth-d031c6ae577b">Mastering Payable and Non payable functions in Solidity</a><br><a href="https://github.com/Ethereum/EIPs/blob/master/EIPS/eip-55.md">EIP55 on Checksum</a><br><a href="https://etherscan.io/">Ethereum Explorer</a><br><a href="https://ethereum.github.io/yellowpaper/paper.pdf">Ethereum Yellowpaper</a><br>Metamask Extension</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5411ba6c3b0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Libraries In Solidity]]></title>
            <link>https://medium.com/@ajaotosinserah/mastering-libraries-in-solidity-36d783409dfc?source=rss-3012defd7eba------2</link>
            <guid isPermaLink="false">https://medium.com/p/36d783409dfc</guid>
            <category><![CDATA[ethereum-blockchain]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Oluwatosin Serah]]></dc:creator>
            <pubDate>Wed, 24 May 2023 23:42:15 GMT</pubDate>
            <atom:updated>2023-05-26T02:51:03.978Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jCB9GbuKknRyUxX2jwmt6g.png" /></figure><p>Welcome back! In this article, we will explore the fascinating world of libraries in Solidity. We’ll uncover the advantages of utilizing libraries, delve into their implementation, and discover more intriguing aspects. Prepare yourself for an enlightening journey as we dive into the realm of Solidity libraries.</p><h4>Prerequisites</h4><p>Before delving into the topic, it is crucial to have a basic understanding of the Solidity programming language. Solidity is used for writing smart contracts on EVM-compatible chains. If you already have experience or familiarity with Solidity and smart contract development, you’re well-prepared to explore the subject further. However, if you are new to Solidity, I recommend referring to the documentation and resources available <a href="https://docs.soliditylang.org/en/v0.8.20/">here</a> to familiarize yourself with the language before proceeding. This foundational knowledge will enhance your understanding of the concepts discussed in this article.</p><h4>What are libraries?</h4><p><strong>SCENARIO 1</strong></p><p>Let’s say you are a skilled chef preparing a delicious feast in a busy kitchen. As you whip up various mouthwatering dishes, you realize that <strong>many recipes</strong> call for a <strong>specific</strong> sauce or spice blend. Instead of repeatedly measuring and mixing the same ingredients for each recipe, you decide to create a “<strong>master blend</strong>” that can be used across multiple dishes. This master blend serves as a <strong>library </strong>of flavors that you can easily sprinkle into different recipes as needed.</p><p>Now, imagine you are building a decentralized application (DApp), like an online marketplace, on the Ethereum blockchain. You encounter various mathematical calculations required by your smart contract. Instead of writing the same arithmetic code over and over again, you can create a <strong>library</strong>. This library acts as your “<strong>master blend</strong>” of mathematical functions that can be used across different parts of your smart contract. By doing so, you save time and effort, just like you would in the kitchen, while maintaining consistency and efficiency throughout your code.</p><p><strong>SCENARIO 2</strong></p><p>Imagine you are working on a large-scale blockchain project that involves multiple smart contracts interacting with each other. One of the requirements of your project is to implement a complex authentication mechanism that involves encryption, decryption, and user authentication, for example.</p><p>To achieve this, you can create a <strong>library </strong>specifically dedicated to handling the authentication logic. This library can contain functions for encrypting and decrypting user data, verifying user credentials, and managing access control. By creating a library for this authentication logic, you ensure that it is consistently applied across all the smart contracts within your project.</p><p>Now, let’s consider a scenario where you have multiple smart contracts that require authentication. For instance, you may have a contract for user registration, a contract for conducting transactions, and a contract for accessing sensitive information. Instead of duplicating the authentication code in each of these contracts, you can simply import and utilize the authentication library.</p><p>By using the library, you achieve code <strong>reusability</strong> as the authentication logic is centralized in one place. Any updates or improvements to the authentication mechanism can be made in the library, and all the smart contracts using the library will automatically benefit from these changes. This approach not only reduces code duplication but also enhances code maintainability and reduces the chances of introducing errors across multiple smart contracts.</p><h4>Definition of a Library</h4><p>According to the scenarios stated above, we can infer libraries in Solidity as a type of smart contract that contain reusable pieces of code. This reusability allows multiple contracts to efficiently leverage the functionality provided by the library without duplicating the code within each contract. They are similar to contracts but differ in how they are deployed and used.</p><h4>Advantages of using Libraries</h4><p>Libraries enable the reuse of common code snippets across multiple smart contracts, reducing redundancy, promoting modular code development, and also:</p><ul><li><strong>Gas Optimization/Efficiency</strong>: By using libraries, you can optimize gas costs and contract size by avoiding code duplication. This results in more efficient and cost-effective smart contracts.</li><li><strong>Code Organization</strong>: Libraries help organize code by separating reusable logic into standalone entities. This improves readability, maintainability, and overall code structure.</li><li><strong>Security and Consistency:</strong> By using libraries, you can ensure that critical functionalities, such as authentication or arithmetic calculations, are implemented consistently and securely across multiple contracts.</li><li><strong>Simplified Development</strong>: Leveraging libraries simplifies the development process by providing pre-built and tested code components that can be easily integrated into smart contracts.</li><li><strong>Collaboration and Standardization</strong>: Libraries foster collaboration and standardization within the developer community by offering a shared collection of functionalities that can be utilized across various projects. A prime example of this is the widespread use of <a href="https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol">OpenZeppelin’s SafeMath library</a>. Developers frequently integrate this library into their projects, including myself, to ensure accurate and secure calculations in smart contracts. By relying on widely adopted libraries like SafeMath, developers can avoid errors and some vulnerabilities in their code while benefiting from the expertise and best practices implemented in these trusted libraries. This promotes consistency, reliability, and efficiency in smart contract development across different projects within the blockchain ecosystem.</li></ul><h4>Restrictions of Libraries</h4><p>Libraries are restricted in the following ways:</p><ul><li>Libraries cannot inherit nor be inherited</li><li>Libraries cannot receive ether, so the receive and fallback functions can’t be in a library.</li><li>Libraries cannot be destroyed</li></ul><blockquote>There is a misconception that libraries cannot have state variables. To further clarify this, check out this <a href="https://dev.to/mudgen/solidity-libraries-can-t-have-state-variables-oh-yes-they-can-3ke9">article</a> by Nick Mudgen.</blockquote><h4>How to define and import libraries in solidity</h4><p>Define a new contract using the library keyword.</p><pre>pragma solidity ^0.8.9;<br><br>library MyLibrary {<br>    // Code and functions here<br>}</pre><p>Implement the desired reusable functions within the library contract like so:</p><pre>library MyLibrary {<br>    function add(uint256 a, uint256 b) internal pure returns (uint256) {<br>        return a + b;<br>    }<br>}</pre><p>Ensure that the library functions are marked as internal to indicate that they can only be accessed by contracts that use the library.</p><p>Save the library contract in a separate .sol file, similar to regular contracts.</p><p>In the contracts that need to use the library, import the library file using the import statement.</p><pre>import &quot;./MyLibrary.sol&quot;;</pre><p>In a case whereby your file contains multiple libraries. You can use curly braces {} in the import statement, specifying which library you would like to import. For example let’s say we have 3 different libraries in a file like this:</p><pre>pragma solidity ^0.8.9;<br><br>library Library1 {<br>    // Code and functions here<br>}<br><br>library Library2 {<br>    // Code and functions here<br>}<br><br>library Library3 {<br>    // Code and functions here<br>}</pre><p>And you want to make use of two of the libraries in your contract code. You simply specify which library you would like to import like so:</p><pre>pragma solidity ^0.8.9;<br><br>import {Library1, Library3} from &quot;./LibraryFolder.sol&quot;;<br><br>contract ThisContract{<br>   //contract code<br>}</pre><h4><strong>Using Libraries in your smart contract</strong></h4><p>In the main contract, declare the library’s usage by using the using or ‘*’ keyword followed by the library name.</p><blockquote>“using LibraryName for Type”</blockquote><p>This directive allows for the attachment of library functions (from the LibraryName library) to a specific type (Type) within the contract which allows accessing the library’s functions and using them within the contract.</p><p><strong>For Example:</strong></p><pre>// Use the library for unsigned integers<br>using MathLib for uint;</pre><pre>// Use the library for any data type<br>using MathLib for *;</pre><p>In both cases mentioned above, all functions from the library are attached to the contract, even if the type of the first parameter does not directly match the object’s type. The type is checked when the function is called, and function overload resolution is performed accordingly.</p><p>By including a library in this manner, its data types and library functions become accessible without the need for additional code. When you call a library function, these functions will receive the object they are called on as their first parameter. Example:</p><pre>// SPDX-License-Identifier: MIT<br><br>pragma solidity ^0.8.0;<br><br><br>library MathLib {<br> <br>    function add(uint256 a, uint256 b) internal pure returns (uint256) {<br>        return a + b;<br>    }<br><br>    <br>    <br><br>}</pre><p>Making use of the MathLibrary in our contract:</p><pre>import {MathLib} from  &#39;./MathLibrary.sol&#39;;<br><br>contract MyContract{<br><br>   using MathLib for uint;<br>     uint a = 10;<br>     uint b= 10;<br><br>     uint c = a.add(b);<br>}</pre><h4>Libraries with Internal Functions and Libraries with External Functions</h4><p>When using Solidity libraries with external functions, they are deployed as separate and independent contracts on the blockchain. Once the library is deployed on the blockchain, it is assigned a specific address. This address then becomes a reference point for other contracts in the Ethereum network to utilize the library’s functionalities. Contracts that use these libraries use DELEGATECALL to call the external functions in these libraries.</p><p>Solidity libraries that exclusively contain internal functions are not deployed as separate, independent contracts on the blockchain. Instead, the internal functions of these libraries are added directly to the contracts that use them. These internal functions become part of the contract that is deployed. Unlike external functions, internal functions are executed using a JUMP instruction rather than the DELEGATECALL mechanism.</p><blockquote>Delegatecall is a low-level function that allows a contract to delegate its call to another contract (borrowing the functionality of another contract) while still preserving its own storage and context. To learn more about delegatecall, read my article<a href="https://medium.com/@ajaotosinserah/mastering-delegatecall-in-solidity-a-comprehensive-guide-with-evm-walkthrough-6ddf027175c7"> here</a>.</blockquote><blockquote>The JUMP opcode plays a crucial role in altering the program counter, thereby enabling the execution to jump to a different point within the deployed code.The JUMP instruction facilitates the efficient navigation and execution of different parts of the code within a smart contract.</blockquote><h4>Example of Solidity Library with Internal function</h4><p>Let’s say that we have ‘MyContract’ that calls the internal function ‘doSomething()’ from the Solidity library ‘Library1’.</p><pre>// Library1.sol<br>library Library1 {<br>    function doSomething() internal pure returns (uint256) {<br>        // Internal function logic<br>        return 42;<br>    }<br>}<br><br>// MyContract.sol<br>pragma solidity ^0.8.9;<br><br>import &quot;./Library1.sol&quot;;<br><br>contract MyContract {<br>    function execute() public pure returns (uint256) {<br>        uint256 result = Library1.doSomething();<br>        return result;<br>    }<br>}</pre><p>In this example above, the Library1 contains an internal function doSomething(). The MyContract contract imports Library1 and calls the doSomething() function. Here is what happens during compilation and deployment:</p><ul><li>The MyContract and Library1 contracts are compiled into separate bytecodes.</li><li>The bytecode of the doSomething() function from Library1 is added to the bytecode of MyContract.</li><li>The combined bytecode, which includes the internal function, is deployed as a single contract, which is MyContract.</li></ul><p>Therefore, only MyContract is deployed to the blockchain, and the doSomething() function becomes part of MyContract bytecode.</p><h4>Example of Solidity Library with External function</h4><p>Let’s consider a scenario where MyContract2 calls an external function stake() from the Solidity library Library2.</p><pre>// Library2.sol<br>pragma solidity ^0.8.9;<br><br>library Library2 {<br>    function stake() external pure returns (uint256) {<br>        // External function logic<br>        return 10;<br>    }<br>}<br><br>// MyContract2.sol<br>pragma solidity ^0.8.9;<br><br>import &quot;./Library2.sol&quot;;<br><br>contract MyContract2 {<br>    address public libraryAddress;<br><br>    constructor(address _libraryAddress) {<br>        libraryAddress = _libraryAddress;<br>    }<br><br>    function executeStake() public view returns (uint256) {<br>        // Make DELEGATECALL to Library2&#39;s stake() function<br>        (bool success, bytes memory result) = libraryAddress.delegatecall(abi.encodeWithSignature(&quot;stake()&quot;));<br>        require(success, &quot;DELEGATECALL to Library2 failed&quot;);<br>        uint256 stakeResult = abi.decode(result, (uint256));<br>        return stakeResult;<br>    }<br>}</pre><p>In this example above, the MyContract2 contract imports Library2 and has a constructor that accepts the address of the deployed Library2 contract. The MyContract2 contract includes a executeStake() function that makes a DELEGATECALL to the stake() function in Library2. Here is what happens during compilation and deployment:</p><ul><li>MyContract2 is compiled into bytecode.</li><li>Library2 is compiled into bytecode.</li><li>Library2 is deployed as its own contract on the blockchain.</li><li>The bytecode of MyContract2 is updated with the Ethereum address of the deployed Library2 contract. This allows MyContract2 to make a DELEGATECALL to the Library2 contract.</li><li>MyContract2 is deployed to the blockchain.</li></ul><p>In this scenario, two contracts are deployed: MyContract2 and Library2. MyContract2 includes the Ethereum address of the deployed Library2 contract in its bytecode, enabling it to make DELEGATECALLs to execute the stake() external function from Library2.</p><h4>Gas Cost when using library with internal function and external function</h4><p>The gas cost of using a Solidity library with internal functions is typically lower compared to using a Solidity library with external functions.</p><p><strong>When using a library with internal functions:</strong></p><ul><li>The internal functions are added to the contract bytecode during compilation and deployment.</li><li>The function calls are executed directly within the contract, similar to regular function calls. This avoids the overhead of DELEGATECALL and the associated gas cost.</li></ul><p><strong>On the other hand, when using a library with external functions:</strong></p><ul><li>The library is deployed as a separate contract on the blockchain.</li><li>The calling contract needs to make DELEGATECALL to invoke the external functions in the library. And DELEGATECALL incurs additional gas cost due to the overhead of message passing and execution in a different context.</li></ul><p>In general, Solidity library with internal functions is generally more efficient than using a library with external functions. However, the actual gas cost can vary depending on the specific implementation and usage patterns.</p><h4><strong>Security: </strong>Implementing SafeMath Library to Prevent Integer Overflow/Underflow</h4><p>The transfer function in the provided contract below lacks protection against potential integer overflow/underflow errors. Specifically, when subtracting the ‘_value’ from ‘balances[msg.sender]’ and adding it to ‘balances[_to]’, there is a risk of encountering underflow, which can have detrimental effects on the contract’s functionality and security.</p><p>Integer overflow occurs when the result of an arithmetic operation exceeds the maximum value that can be stored in the data type, while underflow happens when the result is below the minimum value. These issues can lead to unexpected behavior, and security vulnerabilities within smart contracts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f344e4177db4346761f8395e0720475c/href">https://medium.com/media/f344e4177db4346761f8395e0720475c/href</a></iframe><p>To mitigate these risks, it is crucial to implement preventive measures such as the Openzeppelin SafeMath library. SafeMath provides secure arithmetic operations by performing extensive checks on calculations to prevent overflow/underflow. By incorporating SafeMath or similar libraries into the contract, you can ensure the integrity and reliability of your operations, safeguarding against potential vulnerabilities and enhancing the overall robustness of the smart contract.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e494163f62b1684656fbf3ab3fb9dd21/href">https://medium.com/media/e494163f62b1684656fbf3ab3fb9dd21/href</a></iframe><h4>Popular Libraries</h4><p><a href="http://openzeppelin.com/"><strong>OpenZeppelin</strong></a></p><p><a href="https://github.com/modular-network/ethereum-libraries"><strong>Modular network</strong></a></p><h4>Conclusion</h4><p>Libraries are a powerful tool for developers, enabling them to create modular, reusable code that can significantly streamline the development process and improve code quality. By leveraging libraries effectively, developers can build more efficient, scalable, and maintainable smart contracts on blockchain platforms.</p><h4>Reference</h4><p><a href="https://docs.soliditylang.org/en/v0.8.20/contracts.html#libraries">Solidity Documentation on Libraries</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36d783409dfc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Essential Programming Concepts in Cairo 1]]></title>
            <link>https://medium.com/@ajaotosinserah/exploring-essential-programming-concepts-in-cairo-1-c8426b39d92?source=rss-3012defd7eba------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8426b39d92</guid>
            <category><![CDATA[cairo-lang]]></category>
            <category><![CDATA[cairo]]></category>
            <category><![CDATA[starknet]]></category>
            <dc:creator><![CDATA[Oluwatosin Serah]]></dc:creator>
            <pubDate>Fri, 19 May 2023 06:10:40 GMT</pubDate>
            <atom:updated>2023-05-19T06:20:02.043Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e2gNqHY3v7-K94cYEgDXnQ.png" /><figcaption>Concepts in Cairo1</figcaption></figure><p>Welcome to another exciting adventure as we continue exploring the world of StarkNet and delve deeper into Cairo 1. If you’ve been following along, you might recall our previous article on scalar types in Cairo 1 which you can find <a href="https://medium.com/@ajaotosinserah/mastering-cairo-data-types-for-starknet-contracts-part-1-d5d2485d7fb8">here</a>. If you haven’t had the chance to read it yet, I highly recommend doing so. Now, in this installment, we’re shifting our focus towards essential programming concepts in Cairo 1. We will focus on the Cairo program rather than the starknet contract in this article. Let’s dive right in!</p><h4>Prerequisites</h4><p>Scarb and Cairo-lang are the most efficient frameworks for Cairo 1.0 development. We will be making use of the Scarb framework in this article. In order to install and use these frameworks effectively, you’d need to set up your development environment. You can refer to the installation guides provided below:</p><ul><li><a href="https://docs.google.com/document/d/e/2PACX-1vQO7MSt_JINcGItO4-aIH-FQE9xN_Ssa6zQXC93f0e7W5g7ECny57w3E2M9-fdTdU5Ne1R-Kt9g8_EB/pub">Setting up your development environment</a></li><li><a href="https://github.com/cairo-book/cairo-book.github.io/blob/main/src/ch01-03-hello-scarb.md">Scarb Installation</a></li></ul><h4>Introduction to Functions in Cairo</h4><p>A function is a self-contained block of code that performs a specific task or calculates a result when called or invoked. Functions provide modularity and code reusability by allowing you to define functionality once and use it multiple times throughout your program.</p><p>Functions are extensively used in Cairo code. The mainfunction, serves as the entry point for many programs. To define a function in Cairo, one uses the fnkeyword, followed by the function name and a pair of parentheses. The function body is enclosed within curly brackets, denoting its start and end.</p><pre>fn main(){}</pre><p>In Cairo, we don’t name return values, but we must declare their type after an arrow (-&gt;) . The return value of the function is synonymous with the value of the final expression in the block of the body of a function. You can also return early from a function by using the return keyword and specifying a value, but most functions return the last expression implicitly.</p><p>Also, the conventional style for function and variable names follows the snake case. This entails using all lowercase letters and separating words with underscores. Example:</p><pre>use debug::PrintTrait;<br><br>fn main() -&gt; u8 {<br>    subtract_cd(4, 2)<br>}<br><br>fn subtract_cd(x: u8, y: u8) -&gt; u8 {<br>  x - y<br>}<br></pre><ul><li>The line use debug::PrintTrait; imports the PrintTrait from the debug module, making it accessible within the current scope.</li><li>The main function is the entry point of the program. It is also defined with the fn keyword. It does not take any parameters and is expected to return a value of type u8 based on the -&gt; u8 annotation. Inside the main function, the subtract_cd function is called with arguments 4 and 2. This expression subtract_cd(4, 2) calculates the difference between 4 and 2 using the subtract_cd function.</li><li>The subtract_cd function is defined with the fn keyword. It takes two parameters, x and y, both of type u8 (unsigned 8-bit integer). The -&gt; u8 indicates that the function returns a value of type u8. Inside the function, it subtracts y from x and implicitly returns the result.</li><li>Since the result of the subtraction is an u8, it matches the expected return type of the main function, which is also u8. Therefore, the result of the subtraction is returned from the main function.</li></ul><h4>Statements and Expression</h4><p>A statement is a piece of code that performs an action or an operation. It is a standalone instruction that does not produce a value. Statements are typically used for control flow, variable assignments, function declarations, and other imperative actions in a program.</p><p>An expression is a combination of values, variables, operators, and function calls that evaluates to a single value. It can be thought of as a computation that produces a result. Expressions can be used to calculate values, combine values, and pass arguments to functions. Example:</p><pre>use debug::PrintTrait;<br><br>fn subtract(x: u8, y: u8) -&gt; u8 {<br>    x - y<br>}<br><br>fn main() {<br>    let z: u8 = 3 * subtract(4, 2);<br>    z.print();<br>}</pre><p>In the given example, the statement and expression can be identified as follows:</p><p><strong>Statement:</strong></p><ul><li>let z: u8 = 3 * subtract(4, 2); is a statement. It declares a new variable z of type u8 and assigns it the value obtained by multiplying 3 with the result of the subtract(4, 2) function call. This statement combines variable declaration, assignment, and function invocation.</li></ul><p><strong>Expression:</strong></p><ul><li>x - y inside the subtract function is an expression. It performs the subtraction operation on the variables x and y and evaluates to a value of type u8. This expression represents the result of subtracting y from x.</li><li>3 * subtract(4, 2) is also an expression. It multiplies the value 3 with the result of the subtract(4, 2) function call. This expression evaluates to a value of type u8, which is the result of the multiplication operation.</li><li>z.print() is an expression. It calls the print() method on the variable z. This expression represents the action of printing the value of z to the output.</li></ul><p><strong>Note</strong>: that x — yline doesn’t have a semicolon at the end. That is because expressions do not include ending semicolons. If you add a semicolon to the end of an expression, you turn it into a statement, and it will not return a value.</p><h4>Mutability in Cairo</h4><p>Cairo employs an immutable memory model, which implies that once a memory cell is written to, it cannot be overwritten but only accessed for reading. In line with this immutable memory model, variables in Cairo are immutable by default, meaning their values cannot be changed after the assignment. However, Cairo provides an abstraction that allows you to make variables mutable if needed, giving you the option to modify values during program execution.</p><p>Let’s consider a practical scenario. Suppose you are writing a program that initially prints out ‘Hello, World,’ but later on you decide to modify it to display ‘Hello, there’ with the code below:</p><pre>use debug::PrintTrait;<br><br>fn main() {<br>    let varr = &#39;Hello, World&#39;;<br>    varr.print();<br>    varr = &#39;Hello, there&#39;;<br>    varr.print();<br>}</pre><p>Running the program above will yield the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V_zdwBDAMW7d1gkOxGgAzg.png" /></figure><p>The error message “cannot assign to an immutable variable” is displayed because in Cairo, variables are immutable by default, meaning they cannot be changed once they are assigned a value. Now that Cairo has given us the option to make variables mutable , we can modify the program accordingly.</p><p>To make a variable mutable in Cairo, you can simply add the keyword mutbefore the variable name. This allows you to modify the value assigned to the variable. Here’s an example:</p><pre>use debug::PrintTrait;<br><br>fn main() {<br>    let mut varr = &#39;Hello, World&#39;;<br>    varr.print();<br>    varr = &#39;Hello, there&#39;;<br>    varr.print();<br>}</pre><p>Running the program with the mutkeyword will yield the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ovj5HAbNx7xrWFnHYUl9tQ.png" /></figure><p>Indeed, the program ran successfully without any errors, and it initially printed ‘Hello, World’ as expected. After mutating the variable by assigning a new value to it, the program then printed ‘Hello, there’. This demonstrates that we have successfully modified the variable in Cairo by using the mutkeyword.</p><h4>Constants in Cairo</h4><p>A constant variable is a variable whose value is fixed and cannot be changed after it is assigned. Constant variables are useful when you have a value that remains the same throughout the execution of a program.</p><p>Constants in Cairo are declared using the const keyword, and their values are immutable and cannot be changed after assignment. They are typically used for values that remain constant throughout the program and are declared in the global scope.</p><p>Constants in Cairo are assigned with literal constant expressions, meaning their values are known at compile-time and cannot be computed at runtime. Using constants can help improve code readability, provide meaningful names to hardcoded values, and ensure consistency throughout the program.</p><p>Here’s an example of a constant declaration in Cairo:</p><pre>const MAX_OWNERS: u8 = 20_u8;</pre><p>Let’s say you want to create a MultisigWallet contract that requires multiple owners to approve a transaction before it can be executed. The MAX_OWNERS constant defines the maximum number of owners that can be set for this particular contract. It ensures that the number of owners doesn&#39;t exceed the specified limit.</p><p>In the given example, MAX_OWNERS is defined as a constant with a value of 20.</p><p>By setting a maximum limit on the number of owners, the contract establishes a predefined boundary for the number of individuals or addresses that can participate in the approval process. This limit helps maintain the contract’s security, manageability, and prevents potential abuse by limiting the number of individuals with the authority to approve transactions.</p><h4>Variable Shadowing in Cairo</h4><p>Shadowing in programming languages, including Cairo, refers to the act of declaring a new variable with the same name as an existing variable. This process “shadows” or hides the original variable, causing the compiler to consider the new variable when the name is referenced. The second variable takes precedence over the first, capturing any usage of the variable name until it itself is shadowed or the scope ends.</p><p>In Cairo, variable shadowing can be achieved by reusing the variable name with the let keyword. This creates a new variable within the current scope, potentially with a different value or type compared to the original variable.</p><p>Here’s an example of variable shadowing in Cairo:</p><pre><br>use debug::PrintTrait;<br>fn main() {<br>    let x = 5;<br>    let x = x + 1; //x shadows to give a value of 6<br>    {<br>        let x = x * 2; // 6 * 2 = 12<br>        &#39;Inner scope x value is:&#39;.print();<br>        x.print()<br>    }<br>    &#39;Outer scope x value is:&#39;.print();<br>    x.print(); //6<br>}</pre><p>In the given code snippet, the variable x is initially assigned a value of 5. Then, a new variable x is declared by repeating let x =, which adds 1 to the original value and assigns 6 to x. Within an inner scope defined by curly brackets, another let statement shadows x once again, creating a new variable with a value obtained by multiplying the previous value by 2, resulting in x being 12 within that inner scope. Once the inner scope ends, the shadowing effect ceases, and x returns to having a value of 6. The program then prints the values of x within the inner and outer scopes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lZqu4JMezaHV8QAVc39mOQ.png" /></figure><p><strong>Note: </strong>Shadowing and marking a variable as mutable (mut) are distinct concepts. One difference is that shadowing prevents accidental reassignment without using the let keyword, leading to a compile-time error if attempted. This ensures that the variable remains immutable after performing certain transformations on its value.</p><p>In contrast, when using mut, the variable is explicitly marked as mutable, allowing direct reassignment without requiring the let keyword.</p><p>Also, shadowing with the let keyword creates a new variable with the same name. This enables us to change the type of the value while reusing the name, effectively discarding the previous variable and introducing a fresh one.</p><h4>Typecasting in Cairo</h4><p>Typecasting refers to the process of converting a value from one data type to another. This is typically necessary when you need to use a value in a context where its current data type is not compatible with the expected data type.</p><p>In Cairo, you have the ability to convert values between common scalar types and felt252 using the try_into and into methods provided by the TryInto and Into traits, respectively.</p><p>The try_into method is useful for safe type casting when there is a possibility that the target type may not accommodate the source value. It is important to note that try_into returns an Option&lt;T&gt; type, requiring you to unwrap it to access the new value. Example:</p><pre>use traits::TryInto;<br>use option::OptionTrait;<br><br>fn main() {<br>    let x: felt252 = 56; //x is of type felt252<br>    let y: u64 = x.try_into().unwrap(); //Since a felt252 might not fit in a u64, we need to unwrap the Option&lt;T&gt; type<br>}</pre><p>On the other hand, the into method is suitable for type casting when success is guaranteed, typically in cases where the source type is smaller than the destination type. Example:</p><pre>use debug::PrintTrait;<br>use traits::Into;<br><br>fn main() {<br>    let x = 4_u32;<br>    x.print();<br>    let x: felt252 = x.into(); // converts x to a felt, type annotation is required.<br>    x.print()<br>}</pre><p>It is necessary to explicitly define the type of the new variable, as exemplified in the examples above.</p><h4>Conclusion</h4><p>In this article, we explored functions, mutability, constants, statements and expressions, variable shadowing, and typecasting in Cairo. By understanding these essential programming concepts in Cairo, you are now equipped with the knowledge to write more sophisticated programs and explore further possibilities within the language. I look forward to sharing my next article with you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8426b39d92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Safeguarding Smart Contracts: The Imperative of Access Control]]></title>
            <link>https://medium.com/@ajaotosinserah/safeguarding-smart-contracts-the-imperative-of-access-control-a49dae4f5bf8?source=rss-3012defd7eba------2</link>
            <guid isPermaLink="false">https://medium.com/p/a49dae4f5bf8</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[access-control]]></category>
            <category><![CDATA[smart-contract-security]]></category>
            <dc:creator><![CDATA[Oluwatosin Serah]]></dc:creator>
            <pubDate>Wed, 17 May 2023 04:55:33 GMT</pubDate>
            <atom:updated>2023-05-17T05:57:48.182Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eatbji-FvEVLE66D_33qng.png" /></figure><p>Smart contracts have completely transformed how transactions take place in the Web3 industries, bringing transparency, efficiency, and independence. However, their unchangeable nature creates unique security challenges that we must tackle. In this article, we will explore why access control is so essential in smart contracts, diving into its core principles and emphasizing its indispensable role in securing these innovative digital agreements.</p><h4>Prerequisites</h4><blockquote>Basic Understanding of Solidity: It is important to have a basic understanding of Solidity as it is the main programming language for creating smart contracts on Ethereum. Let’s dive in!</blockquote><p>Access control is a crucial part of developing smart contracts and plays a vital role in reducing vulnerabilities and protecting sensitive functions and data. Understanding the importance of implementing strong access control mechanisms when writing smart contracts is crucial for maintaining their reliability and security.</p><h4>Ensuring Secure Access Control in Smart Contract Functions</h4><p>The use of appropriate access control checks when writing a smart contract is critical to avoiding contract vulnerability. Smart contract functions that execute critical logic should have appropriate access control enforced through address checks (e.g., owner, controller, etc.), which are typically in modifiers.</p><p>Inadequate checks allow attackers to take control of critical logic. The functionality of a contract is typically accessed via its public or external functions. While insecure visibility settings provide attackers with easy access to a contract’s private values or logic, access control bypasses can be more subtle.</p><h4>Code Example</h4><p>Let’s consider the following code example: Below is an illustration of a smart contract that features an initialization function. The intention behind this function was to limit its execution to the contract deployer or owner. The purpose was to grant the owner both a “DEFAULT_ADMIN_ROLE” and a “REVIEWER_ROLE”, allowing the owner to perform specific actions such as assigning roles to different accounts and withdrawing funds from the contract.</p><p>Unfortunately, in the provided code snippet, the initialization function incorrectly designates the caller of the function as the contract’s admin and reviewer. This means that the function can be invoked by anyone, even after it has already been executed. Consequently, anyone who calls the function becomes the administrator of the contract, gains access to its funds, and can assign access roles to any desired account. Also, the logic within the code does not consider the fact that the initialization function has already been called, resulting in a detachment from the contract’s constructor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91c5a8d09eedb39e1f75f720ea4967b3/href">https://medium.com/media/91c5a8d09eedb39e1f75f720ea4967b3/href</a></iframe><h4>Preventive Measures</h4><p>The initialize function should have a modifier that restricts the caller to only the DEFAULT_ADMIN_ROLE, like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe9160eb34b40eaf623682944297cda9/href">https://medium.com/media/fe9160eb34b40eaf623682944297cda9/href</a></iframe><p>The withdraw function should also be protected with a function modifier that restricts the caller to only the REVIEWER_ROLE to avoid theft of funds by attackers.</p><pre>function withdraw() public onlyRole(REVIEWER_ROLE){<br>        payable(msg.sender).transfer(address(this).balance);<br>    }</pre><h4>Code Example 2</h4><p>Let’s consider another example. In the smart contract below, there is a voting system where any address can vote for a candidate without any access control. This lack of access control allows anyone to modify the vote count for any address, e.g., by voting for different candidates or voting for the same candidates numerous times.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86423b9fc13af751d97ee9a240abd6d3/href">https://medium.com/media/86423b9fc13af751d97ee9a240abd6d3/href</a></iframe><h4>Preventive Measure</h4><p>To prevent unauthorized voting and ensure the integrity of the voting system, the following preventive measures can be implemented:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e21d5188c0e8cebd467ad69501f3d494/href">https://medium.com/media/e21d5188c0e8cebd467ad69501f3d494/href</a></iframe><p>In the modified contract, access control is implemented using a modifier onlyAdmin, which restricts certain functions to be executed only by the contract admin. Also, a mapping hasVoted is introduced to track whether an address has already voted or not. This prevents multiple votes from the same address.</p><p>By implementing access control and tracking the voting status of each address, the contract ensures that only authorized individuals can vote and that each address can vote only once, thus maintaining the integrity and fairness of the voting system.</p><p>Implementing access control in smart contracts is essential to prevent unauthorized actions and protect the integrity of the contract’s functions and data. It helps in maintaining transparency, accountability, and security within the decentralized application or system.</p><h4>Conclusion</h4><p>In conclusion, access control is a crucial aspect of smart contract development that ensures only authorized entities can interact with sensitive functions and data. By understanding the significance of access control and following recommended practices, developers can minimize the risk of vulnerabilities and protect the assets and functionality of their smart contracts.</p><p>Failure to implement proper access controls can result in attackers gaining control over critical logic within a smart contract. It is essential to establish controls that restrict unauthorized access and ensure that actions such as withdrawals can only be triggered by authorized parties or in accordance with the predefined rules of the smart contract system.</p><p>Stay tuned for more informative articles to enhance your understanding of blockchain technology and smart contract development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a49dae4f5bf8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Cairo Data Types for StarkNet Contracts: Part 1]]></title>
            <link>https://medium.com/@ajaotosinserah/mastering-cairo-data-types-for-starknet-contracts-part-1-d5d2485d7fb8?source=rss-3012defd7eba------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5d2485d7fb8</guid>
            <category><![CDATA[cairo]]></category>
            <category><![CDATA[layer-2]]></category>
            <category><![CDATA[cairo-lang]]></category>
            <category><![CDATA[starknet]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Oluwatosin Serah]]></dc:creator>
            <pubDate>Mon, 01 May 2023 16:50:41 GMT</pubDate>
            <atom:updated>2023-05-01T17:05:11.506Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*obtDMO5ccxtggdzx_LqeVg.png" /><figcaption>Cairo 1.0 Data type 1</figcaption></figure><blockquote>Welcome to another installment where I share my journey building on StarkNet. In this article, we’ll explore the part 1 of the exciting world of data types used in writing StarkNet contracts. Get ready for an informative and engaging deep dive into this topic. So without further ado, let’s jump right in!</blockquote><p>As we know, smart contracts on StarkNet are written using the programming language Cairo, which is classified as a “statically or strongly typed” language. It shares this trait with another programming language called Rust. This means that when writing your Starknet contracts, you must declare the type of every variable, constant, and function argument you use in your code. By doing so, Cairo enforces strict type checking, which is a process of verifying that the type of data being used is compatible with what is expected. This helps to increase safety and significantly reduces the likelihood of runtime errors, which can occur when data types do not match or are not compatible with each other.</p><h3>Scalar Types</h3><p>A scalar type is a data type that represents a single value. There are three primary scalar types in Cairo: felts, short strings (which are felts under the hood), integers, and booleans. In Cairo, each scalar type works in its own unique way, and understanding how they function is important when writing your contract. Let’s look at them one by one.</p><h4><strong>Felts</strong></h4><p>“Felts” stands for “field elements.” In Cairo, it’s a data type used to represent unsigned integers with up to 76 decimal places. Specifically, the felt252 data type is used to represent a 252-bit integer within a range of 0 ≤ x &lt; P, where P is a prime number. When using felt252, all computations are done modulo P, which ensures the results stay within the 252-bit range.</p><h4>Booleans</h4><p>The<strong> </strong>boolean data type in Cairo is used to store logical values, which can either be “true” or “false.”</p><pre>fn main() {<br>    let initial_state: bool = false;<br>}</pre><p>This code initializes a boolean variable initial_state to false. The bool type is a built-in primitive type in Rust that can hold one of two values: true or false. In this case, the variable initial_state is assigned the value of false, indicating that it represents a state that is initially turned off or inactive.</p><p>Booleans are commonly used in conditional statements and logical operations, where the code execution depends on whether a particular condition is true or false.</p><h4><strong>Short strings</strong></h4><p>In Cairo, full strings are not supported, but you can use short strings, which are strings that have a maximum length of 31 characters. This enables them to be stored in a single field element(felt). Even though short strings may look like regular strings, they are actually encoded as ASCII characters, allowing them to be represented using felt under the hood.</p><p>In order to perform conversions between felt, strings, and hex in Cairo, a Python script is required. This script facilitates conversions between the aforementioned data types, allowing the resulting short strings to be viewed. To perform these conversions, follow the steps outlined below:</p><ul><li>Install Python3 on your computer.</li><li>Create a file named “utils.py”.</li><li>Paste the provided code below into the “utils.py” file.</li></ul><pre>MAX_LEN_FELT = 31<br> <br>def str_to_felt(text):<br>    if len(text) &gt; MAX_LEN_FELT:<br>        raise Exception(&quot;Text length too long to convert to felt.&quot;)<br>    return int.from_bytes(text.encode(), &quot;big&quot;)<br> <br>def felt_to_str(felt):<br>    length = (felt.bit_length() + 7) // 8<br>    return felt.to_bytes(length, byteorder=&quot;big&quot;).decode(&quot;utf-8&quot;)<br> <br>def str_to_felt_array(text):<br>    return [str_to_felt(text[i:i+MAX_LEN_FELT]) for i in range(0, len(text), MAX_LEN_FELT)]<br> <br>def uint256_to_int(uint256):<br>    return uint256[0] + uint256[1]*2**128<br> <br>def uint256(val):<br>    return (val &amp; 2**128-1, (val &amp; (2**256-2**128)) &gt;&gt; 128)<br> <br>def hex_to_felt(val):<br>    return int(val, 16)</pre><ul><li>In your terminal, run:</li></ul><pre>python3 -i utils.py</pre><p>You should see something like this in your terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UDMUzCsNicM116wJg8knFQ.png" /></figure><p>You can then proceed to perform various conversions, such as converting a string to felt and converting felt to a string, using the Python script created earlier. To do so, follow the steps below:</p><pre>str_to_felt(&quot;Hello World&quot;)<br>felt_to_str(87521618088882533792115812)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*uFUpC7817_Jht3g8CzxAhQ.png" /></figure><p>And yay👏, you have successfully made your conversion.</p><h4><strong>Integers</strong></h4><p>We have both unsigned integer types and integer literals.</p><p><strong>Unsigned integers </strong>are a type of integer that only represents non-negative values (i.e., positive numbers and zero) and can’t represent negative values. The size of an integer determines the range of values it can represent. The larger the size, the wider the range of values it can represent. Here are the unsigned integer types and their respective sizes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*Y8y4gnC6QbSH_7ZzwwmpNg.png" /><figcaption>unsigned integer chart</figcaption></figure><p>The “u” in front of the numbers denotes that they are unsigned integers.</p><p>The example below is a simple function that takes in an unsigned 64-bit integer (u64) as input, which is passed in as an argument called value. Inside the function, the input value is multiplied by 2 and the result is stored in a new variable called multiply_value, which is also of type u64. Finally, the function returns the value of multiply_value, which is also of type u64.</p><pre>fn main(value: u64) -&gt; u64 {<br>    let multiply_value: u64 = value * 2;<br>    return multiply_value;<br>}</pre><p>In other words, this function takes a number as input, multiplies it by 2, and returns the result. For example, if the input value is 5, the function would return 10.</p><p><strong>Integer Literal:</strong> In Cairo, you can also assign a type to an integer literal by adding an underscore and the desired integer type after the value, which is similar to how it’s done in the Rust programming language. Integer literals can be specified with an underscore notation to make it easier to work with different integer types without the need for explicit type casting. E.g.:</p><pre>// &quot;num_u8&quot; is an 8-bit unsigned integer initialized with a value of 1.<br>let num_u8 = 1_u8;<br><br>// &quot;num_u32&quot; is a 32-bit unsigned integer initialized with a value of 10.<br>let num_u32 = 10_u32;</pre><p>Using the underscore notation makes it clear to the compiler what the intended type of the integer is and helps avoid type errors and the need for explicit casting. It’s a convenient feature that allows for more efficient and cleaner code. Let’s take a look at the function below:</p><pre>fn main() {<br>     // addition<br>    let sum = 9_u64 + 20_u64;<br><br>    // subtraction<br>    let difference = 84_u64 - 12_u64;<br><br>    // multiplication<br>    let product = 5_u64 * 5_u64;<br><br>    // division<br>    let quotient = 100_u64 / 2_u64; <br>}</pre><p>The main function defines several variables that perform basic arithmetic operations using the unsigned 64-bit integer type u64:</p><p>The + operator adds two numbers, - subtracts the second number from the first, * multiplies two numbers, and / divides the first number by the second, returning the whole number quotient (integer division).</p><p>In this specific case, sum will be assigned the value 29, difference will be assigned the value 72, product will be assigned the value 25, and quotient will be assigned the value 50.</p><h4>Conclusion</h4><p>It is essential to have a good grasp of Cairo data types while developing StarkNet contracts. It is important to comprehend scalar data types to guarantee that the data being utilized aligns with the anticipated type. The piece gives a detailed outline of felts, booleans, integers, and short strings, emphasizing the distinctiveness of each data type. In my upcoming article, I will delve into compound data types that can merge multiple values into one type. I will also create videos that showcase these contracts in practice for your better comprehension🤗. I look forward to sharing my next article with you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5d2485d7fb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CAIRO 1.0: A closer look at the upgrades]]></title>
            <link>https://medium.com/@ajaotosinserah/cairo-1-0-a-closer-look-at-the-upgrades-8cd945c14260?source=rss-3012defd7eba------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cd945c14260</guid>
            <category><![CDATA[layer-2]]></category>
            <category><![CDATA[cairo]]></category>
            <category><![CDATA[cairo-lang]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[starknet]]></category>
            <dc:creator><![CDATA[Oluwatosin Serah]]></dc:creator>
            <pubDate>Fri, 28 Apr 2023 07:46:51 GMT</pubDate>
            <atom:updated>2023-04-28T07:46:51.599Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CuKtFDwjY8xKGXOOeRrz3g.png" /></figure><blockquote>This article will provide an overview of why Cairo 1.0 is a significant advancement for writing contracts on Starknet. It would explore how these upgrades enhance the developer experience and make Cairo more secure and resistant to DOS attacks and censorship.</blockquote><p>Cairo 1.0 came about as a consequence of enhancements made to the earlier iteration of Cairo, which was used in writing starknet contracts. Among the upgrades in Cairo 1.0 are:</p><h4><strong>Introduction to Sierra 🫓</strong></h4><p>Previously, the process for creating a contract involved developers writing it in Cairo and then directly compiling it into CASM (Cairo Assembly). Once compiled, the CASM contract would be deployed onto the starknet blockchain.<br>However, with Cairo 1.0, developers can now write contracts that are first compiled into Sierra, then deployed onto Starknet, and finally compiled into CASM, as you can see in the diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*kkaAYY7ZQXzkR0bcu-excA.png" /><figcaption>CAIRO 0 and CAIRO 1 FLOW</figcaption></figure><h4><strong>Improved syntax😎</strong></h4><p>Cairo 1.0, a programming language that draws inspiration from Rust, has been designed with developers in mind. One of its key features is its readability and ease of use. Unlike dynamically typed languages, Cairo 1.0 requires developers to declare the data type of each variable, which not only simplifies the coding process but also reduces the likelihood of errors occurring. This feature is especially helpful when working with complex logic and data structures.</p><h4><strong>Compiler💾</strong></h4><p>The Cairo 1.0 compiler offers faster feature development and greater community involvement as it is written from scratch.</p><h4><strong>Provability of Every Computation in Cairo 1.0 for DOS Protection and Censorship Resistance 🧾</strong></h4><p>Cairo 1.0 guarantees the provability of all computations, whereas existing versions of Cairo may fail under specific inputs, leading to unprovable computations. This enhancement is especially important for StarkNet’s DOS protection and censorship resistance, as it ensures that programs are provable in every branch.</p><h3>Sierra</h3><p>Sierra (Safe Intermediate Representation) acts as a secure intermediary between Cairo and compilation targets such as Cairo Assembly (CASM), preventing runtime errors and ensuring safety. Using a type system to express mid-level code, Sierra guarantees that every function returns and eliminates infinite loops through a compile-time error-detection system. This streamlined approach permits efficient compilation down to CASM.</p><h4>Major Importance of Sierra🤔</h4><p>As mentioned earlier, in Cairo 0, the Cairo contract is compiled to CASM and deployed on Starknet, after which users can then interact with the contract by signing a transaction and calling smart contract functions, which are then sent to the sequencer.</p><p>The sequencer then processes the transaction to obtain the user’s transaction fee, similar to how validators validate transactions on Ethereum’s mainnet for a fee. The prover, known as SHARP, generates a batch proof, which includes the transaction. The sequencer then charges a fee to include the transaction in a block.</p><p>However, it’s important to note that failed transactions are not included in a block with Cairo 0, which means that for every unsuccessful transaction, the sequencer does not receive any transaction fee.😢. Since failed transactions don’t have valid proofs, they can’t be included, and there is no way to enforce fee transfers for the sequencer.</p><p>This could be problematic as users could potentially overload the network with failed transactions, resulting in an unfair situation for sequencers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*8_x3Zo3nsCAgKfYiBREm0Q.png" /><figcaption>Pictorial Representation</figcaption></figure><p>Because of this issue, sequencers might decide not to execute transactions, which will make it difficult to differentiate between failed transactions and censorship.</p><h4>Preferrable Solution</h4><p>To combat this, Starknet implemented a system like Ethereum where all failed transactions are marked as reverted but are still included in blocks, which will allow sequencers to receive transaction fees for failed transactions, to prevent malicious users from overwhelming the network with invalid transactions. This would prevent legitimate transactions from being delayed, halting the network.</p><p>An introduction to Sierra, which is said to be<strong> <em>correct by construction</em></strong>, allows the sequencer to charge a fee for all transactions, making these things possible:</p><ul><li>contract completeness to ensure that transaction execution can always be verified, even if it’s expected to fail.</li><li>contract soundness to ensure that valid transactions are not rejected, thus avoiding censorship.</li></ul><h4>Conclusion</h4><p>To summarize, adopting Cairo 1.0 is a major step forward in improving the development process for writing contracts on Starknet. The latest version offers several enhancements, such as Sierra, upgraded syntax, and a quicker compiler, that boost the security and resilience of the system against DOS attacks and censorship. Sierra serves as a crucial component, acting as a secure intermediary between Cairo and compilation targets, which minimizes runtime errors and ensures safety. I will see you in my next article👋.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cd945c14260" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Smart Contract Development on Celo: A Beginner’s Guide to Writing and Deploying a Contract on the…]]></title>
            <link>https://medium.com/@ajaotosinserah/smart-contract-development-on-celo-a-beginners-guide-to-writing-and-deploying-a-contract-on-the-f25a0941e527?source=rss-3012defd7eba------2</link>
            <guid isPermaLink="false">https://medium.com/p/f25a0941e527</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[celos]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[celo-blockchain]]></category>
            <category><![CDATA[hard-hat]]></category>
            <dc:creator><![CDATA[Oluwatosin Serah]]></dc:creator>
            <pubDate>Tue, 18 Apr 2023 13:58:02 GMT</pubDate>
            <atom:updated>2023-04-18T13:58:02.410Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QZ0U6vsuV9wc9i9gr7IFtQ.png" /></figure><h3>Smart Contract Development on Celo: A Beginner’s Guide to Writing and Deploying a Contract on the Celo Blockchain</h3><p>This tutorial will provide you with a comprehensive guide on how to effectively deploy and interact with smart contracts on the Celo blockchain. You will gain knowledge on the essential steps required for writing, testing, and deploying smart contracts using Solidity, the most popular programming language for creating contracts on Celo. By the end of this tutorial, you will have a solid understanding of how to build and deploy your own decentralized applications on the Celo blockchain.</p><h4>Prerequisites:</h4><p>To get the most out of this tutorial on deploying and interacting with smart contracts on the Celo blockchain, there are a few prerequisites you’ll need to fulfill.</p><ul><li>Knowledge of Solidity, the programming language used to create smart contracts on Celo.</li><li>Good understanding of using Hardhat, a development environment designed specifically for building Ethereum-compatible smart contracts.</li><li>Familiarity with the command line is also recommended.</li></ul><p>By meeting these prerequisites, you will be well-equipped to successfully write, test, and deploy your own smart contracts on the Celo blockchain.</p><h4>Requirements:​</h4><ul><li>A text editor: For this tutorial, we will make use of Visual Studio Code, so ensure you have VS Code setup on your PC: VSCode is a popular integrated development environment (IDE) for building software.</li><li>You will need to have node.js installed on your system, with version V10. or higher.</li><li>npm (node package manager) used for installing and managing dependencies.</li></ul><p>With these tools in place, you will be able to easily install and configure the necessary packages and modules required for smart contract development and deployment on Celo.</p><h3>Step-by-step Tutorial</h3><h4><strong>STEP 1 — Set Up Hardhat Environment</strong></h4><p>To begin setting up the Hardhat environment for your smart contract implementation, you will first need to create a new folder on your system. You can do this by using the ‘mkdir’ command followed by the desired name of your folder. For example:</p><pre>mkdir my-celo-project</pre><p>Once you have created the folder, you can initialize a new npm project inside it by running the following command:</p><pre>npm init -y</pre><p>This will create a “package.json” file in your project folder with default settings. Next, navigate to your project folder using the ‘cd’ command, like so:</p><pre>cd my-celo-project</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pmDdsTGsPx6bevAm5dYxQw.png" /><figcaption>Your terminal should look something like this</figcaption></figure><p>Finally, open your project folder in Visual Studio Code by running the ‘code .’ command in your terminal:</p><pre>code .</pre><p>This will open up your project folder in Visual Studio Code, where you can start setting up your Hardhat environment and writing your smart contract code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BpoZKB7zs9ogkMovMwGwJw.png" /><figcaption>Visual Studio Code</figcaption></figure><p>Run the following command to initialize the Hardhat environment and create some default configuration files and folders required for building and testing smart contracts.</p><pre>npm install hardhat - save-dev<br>npx hardhat</pre><p>We will be using a typescript project for this tutorial, so click on “Create a typescript project” and enter this and other prompt options. You should see a console output similar to the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4MCUnaT-CrYTTTI3eYr7eg.png" /><figcaption>Hardhat Environment</figcaption></figure><h4>Step 2 — Create your smart contract</h4><p>You can create a new TypeScript file in the contracts folder, which is located in the root directory of your project.</p><p>For example, let’s say you want to create a simple “Hello, World” smart contract. You can create a new file called “Greeter.sol” and write your code. It should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0v8KW5hHWHgW2_l6mk-3fQ.png" /></figure><p>Once you’ve created your smart contract, you can compile it using the Hardhat compiler. To do this, run the following command:</p><pre>npx hardhat compile</pre><p>This will compile your contracts and generate some artifacts in the artifacts folder, which you can use in your tests and deployments.</p><p>After compiling your contracts, you can write tests to verify that they work as expected. You can create a new TypeScript file under the test folder and write your tests using the Hardhat testing framework. For example, you can create a new file called “Greeter.ts”</p><p>Once you’ve written your tests, you can run them using the Hardhat testing framework by running the following command:</p><pre>npx hardhat test</pre><p>This will run your tests and output the results in the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ffVhO-YLPaJpvJMdjOy3dA.png" /><figcaption>Hardhat test script</figcaption></figure><h4>Step 3 — Add Celo testnet to your Metamask</h4><p>To add the Celo testnet to your Metamask wallet, you can follow these steps:</p><ul><li>Open your Metamask wallet and click on the network dropdown menu in the top right corner.</li><li>Select “Custom RPC” at the bottom of the menu.</li><li>Fill in the following information in the “Add Network” dialog:​</li><li>Network Name: Celo (Alfajores Testnet)</li><li>New RPC URL: <a href="https://alfajores-forno.celo-testnet.org/">https://alfajores-forno.celo-testnet.org</a></li><li>Chain ID: 44787</li><li>Currency Symbol (Optional): CELO</li><li>Block Explorer URL (Optional): <a href="https://alfajores-blockscout.celo-testnet.org/">https://alfajores-blockscout.celo-testnet.org</a></li></ul><p>Click “Save” to add the Celo Testnet to your network list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*psa9zB_Ae0-en4YJSwp0ug.png" /></figure><p>To get testnet CELO, you can use the CELO testnet faucet by following these steps:</p><ol><li>Go to <a href="https://celo.org/developers/faucet">https://celo.org/developers/faucet</a> and click “Request Testnet Tokens”.</li><li>Enter your Celo Testnet address (which you can find in your Metamask wallet) and click “Submit”.</li><li>Wait for a few seconds, and you should receive testnet CELO in your Celo Testnet account. You can verify this by checking your account balance in your Metamask wallet.</li></ol><h4>Step 4 — Deploying your smart contract</h4><p>After testing your smart contract and verifying that it works as expected, you can deploy it to the Celo testnet using the Hardhat network configuration.</p><p>To deploy your contract to the Celo testnet, you will need to add the Celo network configuration to the hardhat.config.ts file located in the root directory of your project. Before that, we need to install an env file to be able to use our private key for our Celo account to deploy this contract. You can store your private key in an “.env” file and use the dotenv package to load it into your Hardhat configuration. Here’s an example of how to set it up:</p><ul><li>Install the dotenv package:</li></ul><pre>npm install dotenv</pre><ul><li>Create a .env file in the root directory of your project, paste your private key, and ETHERSCAN_API_KEY into it:</li></ul><pre>PRIVATE_KEY=&lt;your-private-key&gt;<br>ETHERSCAN_API_KEY = &lt;ETHERSCAN_API_KEY&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cBnQXUO-b1A8hUNhTg73eQ.png" /></figure><p>Here’s an example of how to add the Celo network configuration to your hardhat.config.ts file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0c1b_fB6lF3aswEpAWn4fA.png" /></figure><p>Next thing is to write our deploy scripts like so;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pq4PAHiMRdgvaqj2tD_6BQ.png" /></figure><p>Let’s deploy our contract using this command line in our VSCode terminal:</p><pre>npx hardhat run scripts/deploy.ts - network alfajores</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YLASS2hplbf00BzvP--UyA.png" /><figcaption>Deployment</figcaption></figure><h4>Step 5 — Verifying your contract</h4><p>To verify your contracts on the Celo Explorer, you can follow these steps:</p><p>After your contract has been deployed, go to the Celo Explorer (https://alfajores.celoscan.io/) and paste the contract’s address into the search field.</p><p>After locating the address of the contract, select the “Contract” button and proceed to click on “Verify and Publish” in order to initiate the verification process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YLke-kyTlFEndHlmz6ctpw.png" /><figcaption>Verify and Publish</figcaption></figure><p>Fill in the required information, such as the compiler version used to deploy your contract, the compiler type, and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dTkZndXsPbt1aEWQFRZRUQ.png" /><figcaption>Verify and Publish Contract Source Code</figcaption></figure><p>Then click on “Continue,” which will take you to another page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YOpYQfJW3pDE6HzCrmLh1Q.png" /></figure><p>To verify your smart contract, you must copy and paste its code into the “Enter the Solidity Contract Code below” field. Additionally, if your contract’s constructor function had any arguments passed during deployment, you will need to obtain the ABI-encoded argument and paste it into the “Constructor Arguments ABI-encoded” field. However, if there were no arguments provided during deployment, this step can be skipped. In the tutorial we are following, the contract code was deployed with an argument, so we must go through this process.</p><p>To obtain the ABI-encoded constructor arguments for your deployed smart contract, you will need to first copy the transaction hash of the contract deployment. Then, go to the Celo Explorer and paste the transaction hash into the search field. Once you have located the transaction, click on “Click to see more” to view the transaction details, including the ABI-encoded constructor arguments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OPsc7I87draBJcBcjamxRA.png" /></figure><p>The “Input Data” field contains the bytecode of the deployed smart contract. The ABI-encoded format of the constructor argument can be found by locating the first zero-padding at the end of the bytecode, and copying everything after it. This ABI-encoded format should then be copied into the “Constructor Arguments ABI-encoded” field so we can finish up with the contract verification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bAow_mYxtZxG5BRXTb1gtw.png" /></figure><p>Submit the verification request by clicking the “Verify and Publish” button , and wait for it to be processed. This usually takes a few seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kqjIAU5rFsILnBgNPavZ-Q.png" /></figure><p>After successfully verifying your smart contract, you should be able to see it on the Celo Explorer with a green checkmark indicating that it has been verified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZZ1TydmVLG2zzOP7aTUsIQ.png" /></figure><h4>Step 5 — Interacting with your deployed contract on Celo explorer</h4><p>Now that your smart contract has been successfully verified and deployed, the next step is to interact with it. This typically involves using a Web3 interface to call the functions defined in the contract and interact with its data. In this tutorial, we will be using Celo Explorer to interact with our smart contract.</p><p><strong>Reading your contract🥽</strong>: To retrieve data from your smart contract, you can click on the “Read Contract” field in Celo Explorer and then call the function that you want to retrieve data from. In this case, we want to see the current state of the “greet” variable.</p><p>See that when the function was triggered, it returned “Hello World,” which was the initial value that we set for the “greet” variable during contract deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NSAFy3u1oROUX707Enutgg.png" /><figcaption>Reading contract on Celoscan</figcaption></figure><p><strong>Writing to your contract</strong>📝: Here are the steps to write data to your smart contract on Celo Explorer:</p><ul><li>Click on the “Write Contract” tab in Celo Explorer.</li><li>Connect to your Celo wallet by clicking on the “Connect Wallet” button and choosing your wallet provider.</li><li>Select the function you want to write data to and fill in any required parameters.</li><li>Click the “Write” button to send the transaction to the blockchain.</li><li>Review the transaction details and confirm the gas fee.</li></ul><p>Once the transaction is confirmed on the blockchain, the data will be written to your smart contract.</p><p>Note that writing to a smart contract may require paying gas fees, which can vary depending on network congestion and other factors. Also, be sure to review the transaction details carefully before confirming the transaction to ensure that you are writing the correct data to your smart contract.</p><h4>Conclusion</h4><p>In summary, the process of writing, deploying, and interacting with smart contracts on the Celo blockchain can open up exciting possibilities for developers looking to build decentralized applications and streamline complex business processes. With all these skills and techniques at your disposal, the sky’s the limit for what you can achieve on the Celo blockchain. Best of luck on your smart contract journey🍀!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f25a0941e527" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Delegatecall in Solidity: A Comprehensive Guide with EVM Walkthrough]]></title>
            <link>https://medium.com/@ajaotosinserah/mastering-delegatecall-in-solidity-a-comprehensive-guide-with-evm-walkthrough-6ddf027175c7?source=rss-3012defd7eba------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ddf027175c7</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[upgradable-contracts]]></category>
            <category><![CDATA[delegatecall]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Oluwatosin Serah]]></dc:creator>
            <pubDate>Thu, 13 Apr 2023 15:53:23 GMT</pubDate>
            <atom:updated>2023-04-13T15:53:23.248Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qTnrQqpNgWt84HSSCmd-rw.png" /></figure><p>In this article, you will get a comprehensive overview of delegatecall in Solidity, how it works, and real-world examples of its use cases. We will also go through a step-by-step guide to using delegatecall with an EVM walkthrough, highlighting common pitfalls and how to avoid them. Without further ado, let’s begin.</p><p><strong>P<em>rerequisite: </em></strong><em>Before delving further into this article, make sure you have an understanding of how solidity state variable storage layout works. If not make sure you check out solidity documentation on it </em><a href="https://docs.soliditylang.org/en/v0.8.19/internals/layout_in_storage.html"><em>https://docs.soliditylang.org/en/v0.8.19/internals/layout_in_storage.html</em></a></p><h3>What is Delegatecall?</h3><p>In Solidity, delegatecall is a low-level function that allows a contract to delegate its call to another contract (borrowing the functionality of another contract) while still preserving its own storage and context. When a contract makes a delegatecall, the code at the target address is executed in the context of the calling contract. This means that the storage, state variables, and functions of the calling contract are accessible to the code being executed.</p><h4><strong>To understand how </strong><strong>delegatecall works better, let&#39;s consider the following scenario:</strong></h4><p>Let’s imagine that you’re a contractor👷 and you’ve been hired to build a house🏠. You’re responsible for coordinating with various other contractors who will be responsible for different aspects of the project, such as plumbing, electrical, carpentry, e.t.c.</p><p>In this scenario, you are like the calling contract, and the other contractors are like the contracts that you will be calling using delegatecall.</p><p>Now, imagine that you need the plumber to come in and install the pipes in the house. Instead of doing it yourself, you can use delegatecall to call the plumber and have him install the pipes for you. When you use delegatecall, the plumber comes to your worksite and installs the pipes in the context of your project rather than their own. This means that the plumber can access the tools, materials, and workers that you have available rather than having to bring their own. However, the plumber will still use their own expertise and knowledge to install the pipes correctly.</p><p>Similarly, when you use delegatecall in a smart contract, you can call another contract and execute its code in the context of your own contract. This allows you to access your own storage, state variables, and functions while still being able to execute the code of the other contract.</p><h3>Difference Between Call and DelegateCall</h3><p>Let’s pause for a moment and examine the distinction between utilizing call and delegatecall in Solidity. It is important to comprehend the disparity between these two, as it is vital for upgrading smart contracts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*MAjrD2X2e7X4L-7dVkUFpw.png" /></figure><p>call is a low-level Solidity function used to make an external call. When call is used, the target contract executes in its own context and any state changes it makes are confined to its own storage. call also returns a boolean value to indicate whether the call succeeded or not.</p><p>While delegatecall is similar to call, but instead of executing the target contract in its own context, it executes it in the context of the calling contract&#39;s current state as you can see in the diagram above. This means that any state changes made by the target contract are made to the calling contract&#39;s storage. This particular use case is of great significance when upgrading a contract, as it enables you to separate the contract&#39;s logic into multiple contracts without losing the original contract&#39;s state.</p><blockquote>For example, suppose you have a contract that needs to be upgraded. You can create a new contract with the upgraded logic and use delegatecall to execute the new contract&#39;s code in the context of the original contract&#39;s storage. This way, the upgraded logic can access and modify the original contract&#39;s state as needed.</blockquote><h4>Things to note when using delegatecall</h4><ul><li>When a contract makes a delegatecall, the value of address(this), msg.sender, and msg.value do not change their values. However, it’s important to note that while the target contract can access the storage variables of the calling contract, it doesn’t inherit the original message call parameters of the calling contract. The original message call parameters include msg.sender, which is the address of the account that sent the original message call, and msg.value, which is the amount of Ether sent along with the message call, if any.</li><li>When a contract is called using delegatecall, the values of msg.senderand msg.valuepassed to the target contract are not those of the delegate call but instead those of the original message call to the calling contract. This means that the target contract can’t access the actual address of the account that sent the delegatecall or the amount of Ether sent with the delegate call.</li></ul><blockquote>To illustrate this point, let’s say Contract A calls Contract B using delegatecall. If Contract B accesses msg.senderor msg.value, it will retrieve the values of the original message call to Contract A, not those of the delegate call from Contract A to Contract B. This is because delegatecall forwards the entire message (includingmsg.sender and msg.value) to the target contract but executes the called contract’s code in the context of the calling contract.</blockquote><ul><li>When a function is executed with delegatecall, reads and writes to state variables do not happen to the contract that loads and executes the function i.e the target contract. Instead, the reads and writes happen to the contract that defines the function being executed(caller contract). This is because the execution context is that of the target contract, not the calling contract. So any changes made to state variables within the target function will happen to the storage of the target contract, not the calling contract.</li></ul><blockquote>e.g., When ContractA uses <em>delegatecall</em> to execute a function from ContractB, the execution context is still within ContractA. This means that any reads or writes to state variables within that context will be to the state variables of ContractA, not ContractB. ContractB’s state variables are effectively “hidden” from ContractA’s execution context and cannot be read or written to directly. However, ContractB’s functions can still access and modify its own state variables, as long as they are called directly (i.e. not through <em>delegatecall</em>) or through another contract that uses call instead of <em>delegatecall</em>.</blockquote><h4>How to use delegatecall with code example</h4><p>In this code below, the CallingContract has the following;</p><ul><li>A state variable which is set to string “Something”</li><li>Aset function that takes an address _calledAddress as an argument. This address should correspond to the TargetContract contract address. The set function then uses delegatecall to call the changeMessage function from the TargetContract, passing the argument &quot;He is Alive&quot; as a string when called.</li><li>The changeMessage function of the TargetContract updates the message and owner state variables, and the changes are reflected in the CallingContract.</li><li>If the delegatecall function fails, the set function will revert and return an error message. The error message will indicate if the function call reverted or if there was another error.</li></ul><p>TargetContract which has the functionality to be implemented by the CallingContract using delegatecallhas the following;</p><ul><li>The contract has two state variables, message and owner, both declared as public, which means they can be accessed by anyone. The message variable is initialized with the string &quot;I love solidity&quot;, while the owner variable is initialized with the value passed to the constructor when the contract is deployed.</li><li>The constructor of the contract takes an argument _owner, which is an address representing the owner of the contract. This argument is used to initialize the owner variable.</li><li>The contract also has a function called changeMessage, which takes a string argument _msg and updates the message and owner variables. The message variable is set to the value of _msg, while the owner variable is set to the address of the function caller, which is obtained using msg.sender.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b192c7c010dfc90c45b42a036b1094d/href">https://medium.com/media/5b192c7c010dfc90c45b42a036b1094d/href</a></iframe><p>The TargetContract has the following when the changeMessage() is called with a new arguement;</p><ul><li>address(this) -&gt; 0x4401f7E80aDB3D7589E720e069CB7F81E0402550</li><li>msg.sender -&gt; 0x637CcDeBB20f849C0AA1654DEe62B552a058EA87</li><li>message(pass any string argument you want)-&gt; “Just updated”</li></ul><p>Before the set() function in the CallingContract is being called, the contract has the following;</p><ul><li>address(this) -&gt; 0xB82a6d6aAFbeB1d994604C119B97272Cba504F4F</li><li>owner -&gt; 0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2</li><li>message -&gt; “Something”</li></ul><p>After the set() function in the CallingContract is being called, the contract has the following;</p><ul><li>address(this) -&gt; 0xB82a6d6aAFbeB1d994604C119B97272Cba504F4F</li><li>msg.sender -&gt; 0xEB7A41D324ee4859E3cbFAd4b3820B82FCCe6658</li><li>message -&gt; “He is Alive”</li></ul><p>If you observe, the address(this) value didn’t change and also since the owner variable was assigned to the caller of the set() function which is the msg.sender, the CallingContract state variable gets updated with the current msg.senderin the context of the CallingContract and not the TargetContract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wg0hU3GPka3UhJo8ijVnZg.png" /></figure><p>The “owner” variable in theTargetContract still gives a value of 0x637CcDeBB20f849C0AA1654DEe62B552a058EA87, which is the same as the msg.senderthat deployed the TargetContract. When calling the “owner” variable in theCallingContract, it gives the value of the msg.sender who called the “set()” function, which is “0xEB7A41D324ee4859E3cbFAd4b3820B82FCCe6658” in this context. <br>Thus, all the requirements mentioned in “Things to note when using delegatecall” have been fulfilled.</p><h4>Common pitfalls to avoid when using delegatecall in Solidity</h4><ul><li><strong>Using </strong><strong>delegatecall to call an unknown or malicious contract:</strong> If you are using delegatecall to call a contract that you are not familiar with, there is a risk that the contract may behave maliciously or have vulnerabilities that could be exploited. Always make sure to thoroughly audit any contracts that you are calling with delegatecall.</li><li><strong>Managing the state variable layout between the calling contract and the target contract: </strong>When a function is called with delegatecall, it operates in the context of the calling contract’s storage, meaning that it shares the same state variable address space(slot position). Therefore, it is important for the calling contract and the target contract to have the same state variable layout for any state variables that are read from or written to by both contracts. This ensures that both contracts access the same state variables in the same order, preventing issues such as overwriting or misinterpreting each other’s state variables. By having the same state variable layout, both contracts can access the same data in the same memory locations, regardless of their individual implementation details.</li></ul><blockquote>For example let’s say that a ContractA declares state variables ‘string message;’ and ‘address owner;’ and ContractB declares state variables ‘uint256 num;’ and ‘address owner;’. They have different state variables at position 0 (‘string message’ and ‘uint256 num’) in contract storage and so they will write and read wrong data between them at position 0 if delegatecall is used between them.</blockquote><p>It is important to carefully plan and manage the state variable layout of contracts that use delegatecall to ensure that they are accessing the same data in the same memory locations. This can be achieved through strategies such as defining a shared interface or thoroughly communicating any changes to the state variable layout. To know more about using a shared storage for upgradeable contracts, check out my previous article on Diamond Standard: <a href="https://medium.com/@ajaotosinserah/upgradable-functionality-with-eip2535-a-comparative-analysis-c9c1d9954296">https://medium.com/@ajaotosinserah/upgradable-functionality-with-eip2535-a-comparative-analysis-c9c1d9954296</a></p><ul><li><strong>Changing state variables in the calling contract</strong>: When using delegatecall, you need to be careful not to accidentally modify state variables in the calling contract. If the called function modifies state variables, those changes will be made to the calling contract&#39;s state instead of the target contract&#39;s state. Always make sure to use call instead of delegatecall if you need to modify state variables in the calling contract.</li><li>It’s important to note that if delegatecall is called on an address that is not a contract(EOA), and thus has no code, it will return a true status value. This behavior can cause bugs if the code expects delegatecall functions to return false when they cannot execute. To avoid this issue, it’s advisable to verify that any address variable used with delegatecall contains code before executing the function. If there is any uncertainty as to whether the address will always contain code, it&#39;s important to check before using delegatecall and revert the transaction if the address does not contain code. Here is an example of code that checks if an address has code:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19f3453e8b2d98f4e016bf4ba9e6c248/href">https://medium.com/media/19f3453e8b2d98f4e016bf4ba9e6c248/href</a></iframe><ul><li><strong>Misusing the return value</strong>: delegatecall returns a boolean value indicating whether the call was successful or not. However, the return value of the function being called is not automatically returned. This can lead to unexpected behavior if the return value is not handled properly. Always make sure to handle the return value of the function being called correctly.</li><li><strong>Passing incorrect arguments</strong>: When using delegatecall, you need to ensure that the arguments being passed to the called function are correct. If the arguments are incorrect, the function being called may behave unexpectedly or even fail. Always make sure to pass the correct arguments to the function being called.</li></ul><p>To avoid these pitfalls, it’s important to thoroughly understand how delegatecall works and to use it judiciously. Make sure to test your code thoroughly and to audit any contracts that you are calling with delegatecall.</p><h4>EVM Walkthrough</h4><p>In the following discussion, we will briefly review the opcodes used in the previous code example and provide an explanation of how delegatecall OPCODE is utilized, as well as the gas price.</p><pre>146 JUMP <br>147 JUMPDEST <br>148 PUSH1 40 <br>150 MLOAD <br>151 PUSH2 0082 <br>154 SWAP2 <br>155 SWAP1 <br>156 PUSH2 02a3 <br>159 JUMP <br>160 JUMPDEST <br>161 PUSH1 40 <br>163 DUP1 <br>164 MLOAD <br>165 PUSH1 20 <br>167 PUSH1 24 <br>169 DUP3 <br>170 ADD <br>171 DUP2 <br>172 SWAP1 <br>173 MSTORE <br>174 PUSH1 0b <br>176 PUSH1 44 <br>178 DUP4 <br>179 ADD <br>180 MSTORE <br>181 PUSH11 486520697320416c697665 <br>193 PUSH1 a8 <br>195 SHL <br>196 PUSH1 64 <br>198 DUP1 <br>199 DUP5 <br>200 ADD <br>201 SWAP2 <br>202 SWAP1<br>203 SWAP2<br>204 MSTORE <br>205 DUP4 <br>206 MLOAD <br>207 DUP1 <br>208 DUP5 <br>209 SUB <br>210 SWAP1 <br>211 SWAP2 <br>212 ADD <br>213 DUP2 <br>214 MSTORE <br>215 PUSH1 84 <br>217 SWAP1 <br>218 SWAP3 <br>219 ADD <br>220 DUP4 <br>221 MSTORE <br>222 DUP2 <br>223 ADD <br>224 DUP1<br>225 MLOAD <br>226 PUSH1 01 <br>228 PUSH1 01 <br>230 PUSH1 e0 <br>232 SHL <br>233 SUB <br>234 AND <br>235 PUSH4 60fd1c4f <br>240 PUSH1 e0 <br>242 SHL <br>243 OR <br>244 SWAP1 <br>245 MSTORE <br>246 SWAP1 <br>247 MLOAD <br>248 PUSH1 00 <br>251 DUP3 <br>252 SWAP2 <br>253 PUSH1 01 <br>255 PUSH1 01 <br>257 PUSH1 a0 <br>259 SHL <br>260 SUB <br>261 DUP6 <br>262 AND <br>263 SWAP2 <br>264 PUSH2 0110 <br>267 SWAP2 <br>268 PUSH2 02d6 <br>271 JUMP <br>272 JUMPDEST <br>273 PUSH1 00 <br>275 PUSH1 40 <br>277 MLOAD <br>278 DUP1 <br>279 DUP4 <br>280 SUB <br>281 DUP2 <br>282 DUP6 <br>283 GAS <br>284 DELEGATECALL <br>285 SWAP2 <br>286 POP <br>287 POP </pre><p>The OPCODES above represent the low-level instructions executed by the EVM when the set() function was called in the CallingContract contract. Here is a brief explanation of each opcode;</p><ul><li>JUMP (opcode 146) : This opcode is used to implement control flow in the bytecode.</li><li>PUSH1 (opcode 148, 161, 181, 215, and 273) and PUSH2 (opcode 151, 156, 267, and 268): These opcodes push a constant value onto the stack. The constant values are used for memory addresses and offsets in the bytecode.</li><li>MLOAD (opcode 150 and 164) and MSTORE (opcode 173, 180, 213, and 221): These opcodes are used to read and write data from and to memory.</li><li>SWAP1, SWAP2, SWAP3, and DUP1 (opcodes 154, 155, 172, 206, 207, 208, 212, 217, 222, 223, 225, 228, 229, 231, 252, 253, and 280): These opcodes are used to manipulate the stack.</li><li>ADD (opcodes 169, 211, 213, 223, 260, and 262) and SUB (opcodes 209, 251, and 262): These opcodes are used to perform arithmetic operations.</li><li>GAS (opcode 283): This opcode pushes all the available gas onto the stack. It is used to limit the amount of gas available for the delegatecall operation.</li><li>DELEGATECALL (opcode 284): This opcode performs the actual delegatecall operation, transferring control to the called contract while preserving the calling contract&#39;s storage and executing in the calling contract&#39;s context.</li></ul><h4>Gas Price</h4><p>The gas price for a delegatecall opcode is calculated in the same way as for any other opcode in the Ethereum Virtual Machine (EVM). It is determined by the current gas price on the network multiplied by the gas limit for the transaction in which the delegatecall opcode is included.</p><p>The gas price for a delegatecall opcode is the gas cost of executing the code in the target contract, plus any additional gas required for the delegatecall itself. This gas cost is deducted from the gas limit of the calling contract, and any remaining gas is returned to the calling contract after the delegatecall is complete.</p><p>When using delegatecall, it is important to note that the gas cost is not only determined by the code being executed in the target contract, but also by the state of the calling contract. This means that if the state of the calling contract is complex, it may require more gas to execute the delegatecall opcode.</p><p>Therefore, it is important to carefully manage gas costs when using delegatecall to avoid running out of gas during execution. This can be done by estimating the gas cost of the delegatecall beforehand, using gas-efficient code and storage layouts, and testing the delegatecall thoroughly in a test environment before deploying it to the main network.</p><h3>Conclusion</h3><p>Delegatecall is a Solidity feature that allows contracts to execute code from other contracts while maintaining the calling contract’s storage and state. This article covered how delegatecall works, its benefits, and real-world use case. We also provided a step-by-step guide to using delegatecall and highlighted common pitfalls to avoid, including managing state variable layout, handling exceptions properly, and managing gas costs. By using delegatecall carefully, Solidity developers can increase code reuse and create more modular and flexible smart contracts. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ddf027175c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the Differences Between Payable and Non-Payable Functions in Solidity: An In-Depth…]]></title>
            <link>https://medium.com/coinmonks/exploring-the-differences-between-payable-and-non-payable-functions-in-solidity-an-in-depth-d031c6ae577b?source=rss-3012defd7eba------2</link>
            <guid isPermaLink="false">https://medium.com/p/d031c6ae577b</guid>
            <category><![CDATA[evm]]></category>
            <category><![CDATA[opcodes]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Oluwatosin Serah]]></dc:creator>
            <pubDate>Mon, 27 Mar 2023 20:50:16 GMT</pubDate>
            <atom:updated>2023-04-14T13:01:26.872Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g6k_6WsSbODih3nBNA0iNA.jpeg" /></figure><h3>Exploring the Differences Between Payable and Non-Payable Functions in Solidity: An In-Depth Analysis</h3><blockquote>Welcome to another article on Solidity’s payable and non-payable functions! If you’re interested in blockchain development and smart contracts, you’ve probably come across these terms before. In this article, we’ll explain what payable and non-payable functions are, how they work in Solidity, and why payable functions are less costly (in terms of gas) than non-payable ones. We’ll also explore some use cases for both types of functions and highlight the trade-offs that developers need to consider when choosing between them. <br>By the end of this article, you should have a clear understanding of how to use payable and non-payable functions effectively in your Solidity smart contracts. Let’s dive in!</blockquote><h3><strong>Payable Functions</strong></h3><p>In Solidity, a payable function is a function that can accept ether as an input. When a contract is called with a payable function, the caller can send ether along with the function call. The ether is then stored in the contract’s balance, which can be accessed using the “address(this).balance” property.</p><h4><strong>How to declare a payable function</strong></h4><p>In Solidity, you use the payable function when you want to allow a contract to receive ether. A payable function is declared using the ‘payable’ keyword, which makes it possible to receive ether as part of a function call. See code example below;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33303dd58219d2ce668ee4582b0710d4/href">https://medium.com/media/33303dd58219d2ce668ee4582b0710d4/href</a></iframe><p>The code above defines a contract that allows users to deposit ether into their accounts by calling the deposit function.</p><h3><strong>Non Payable Function</strong></h3><p>A non-payable function, on the other hand, is a function that cannot accept ether as an input. If a contract is called with a non-payable function and the caller tries to send ether with the call, it will result in an error. See code example below;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a32e7753f6f81f9533b49ef9ecd172e1/href">https://medium.com/media/a32e7753f6f81f9533b49ef9ecd172e1/href</a></iframe><h4><strong>Using msg.value in non-payable functions</strong></h4><p>In Solidity, using &quot;msg.value&quot; in non-payable functions is not permitted for security reasons. &quot;msg.value&quot; represents the amount of ether being sent with the function call. If it is used in a non-payable function, this indicates that the function is receiving ether, which was not intended. This could result in security problems and potential financial loss.</p><p>To handle this scenario, you need to either make the function payable or create a new internal function that uses “msg.value”. If the function needs to receive ether, you should make it payable by adding the payable keyword before the function definition. This allows the function to receive and process ether.</p><h4><strong>Functions that are implicitly payable</strong></h4><p>1. Receive function: The receive function is automatically payable and is called when the call data is empty. This means that if someone sends a transaction to the contract without specifying which function to call, the receive function will be executed. It is declared like this;</p><pre>receive() external payable{}</pre><p>2. Fallback function: The fallback function, on the other hand, is triggered when you call a function that doesn’t exist or match any function in a contract. If the receive function does not exist, the fallback function will handle calls with empty call data. If a fallback function is not payable, transactions or function calls that do not match any other function and also send value (ether) will revert. It is declared like this;</p><pre>fallback() external payable{}</pre><h4><strong>Explicit address conversion</strong></h4><p>It is important to note that not all addresses are payable, and if you try to send ethers to a non-payable address, the transaction will fail.</p><p>Explicit conversion from address to address payable is only possible if the contract has a receive or payable fallback function. The conversion can be performed using address(x), where x must be of type address.</p><p>However, if the contract type does not have a receive or payable fallback function, the conversion to address payable can be done using payable(address(x)). This is because a contract without a receive or payable fallback function cannot receive ether and therefore cannot be converted to a payable address.</p><p>In essence, the conversion from address to address payable is done to enable sending ether to the address. This conversion is used when calling a contract function that has the “payable” modifier, which allows it to receive ether. The “payable” keyword makes the function accept ether and increases the balance of the contract by the amount of ether received. See code example below;</p><pre>//address payable provides the transfer function<br>address payable payableAddress;</pre><h4><strong>Gas cost analysis for payable and non payable function</strong></h4><p>Let’s perform a transaction and observe the gas cost for each case using the following contracts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/624dcc9590a23eee41b0b053791724d7/href">https://medium.com/media/624dcc9590a23eee41b0b053791724d7/href</a></iframe><p>The depositEther transaction in the payable contract costs 30605 gas while the depositAmount transaction in the non payable contract costs 31141 gas. Notice that the gas cost for the payable function is cheaper than that of non payable function. Let’s unbox the mystery behind it!📜</p><h4><strong>Why payable functions are cheaper than non payable functions</strong></h4><p>Using this code below, we will shed light on why payable functions are more cost-effective than non-payable functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/867e0f5598b3da0a6213e987ec59dae1/href">https://medium.com/media/867e0f5598b3da0a6213e987ec59dae1/href</a></iframe><p>Instead of using the previous code, which the bytecode and opcode of the contracts would have been overly complex and lengthy, I will be utilizing the empty constructor function. By doing so, it will be easier for everyone to comprehend and subsequently apply the knowledge to other contracts without any confusion.</p><h4><strong>Init Code</strong></h4><p>The init code, also known as the constructor code, is executed only once when the contract is deployed. Its purpose is to initialize the contract’s state and set its initial values. The init code is used to create and store the contract’s variables, set up the contract’s logic, and perform any other setup tasks required for the contract to operate correctly.</p><h4><strong>Runtime Code</strong></h4><p>Runtime code is executed every time the contract is called or invoked. This code defines the logic of the contract, including how it interacts with other contracts, how it stores and retrieves data, and how it handles transactions. The runtime code is what executes when a contract is interacted with.</p><h4><strong>Bytecode for the Non-Payable contract</strong></h4><pre>[6080604052&quot;348015600f57600080fd5b50603f80601d&quot;6000396000f3fe] - Init Code<br>[6080604052600080fdfea2646970667358fe1220fefefefefe160342fefe35692fec668c4c7705aa8c111a45fe6447aec315841164736f6c63430008110033]- Runtime code</pre><h4><strong>Bytecode for the Payable contract</strong></h4><pre>[6080604052&quot;603f806011600039&quot;6000f3fe] - Init Code<br>[6080604052600080fdfea2646970667358fe1220fe09fefe93fef3f2a4fefefea49cfe11fefe99fe05fe7d05fa3e9cd05f3e143364736f6c63430008110033]- Runtime code</pre><p>If you observe, the init code for the non-payable function is longer than that of the payable function same goes for the opcodes below. The init is highlighted in double quotes.</p><h4><strong>Opcode for the Non- payable contract</strong></h4><pre>//Set up the free memory pointer<br>[00] PUSH1 80<br>[02] PUSH1 40<br>[04] MSTORE //Stores the word in memory<br>[05] CALLVALUE -&gt; Is the amount in wei that was with a transaction<br>[06] DUP1<br>[07] ISZERO<br>[08] PUSH1 0f<br>[0a] JUMPI<br>[0b] PUSH1 00<br>[0d] DUP1<br>[0e] REVERT<br>[0f] JUMPDEST<br>[10] POP<br>[11] PUSH1 3f<br>[13] DUP1<br>[14] PUSH1 1d -&gt;<br>[16] PUSH1 00<br>[18] CODECOPY<br>[19] PUSH1 00<br>[1b] RETURN<br>[1c] INVALID<br>[1d] PUSH1 80<br>[1f] PUSH1 40<br>[21] MSTORE<br>[22] PUSH1 00<br>[24] DUP1<br>[25] REVERT<br>[26] INVALID<br>[27] LOG2<br>[28] PUSH5 6970667358<br>[2e] INVALID<br>[2f] SLT<br>[30] SHA3<br>[31] PUSH31 bc71976c3da4aae3dc9fb5312d39cd8267899b40f5cbb457a9ed9feeec97d9<br>[51] PUSH5 736f6c6343<br>[57] STOP<br>[58] ADDMOD<br>[59] GT<br>[5a] STOP<br>[5b] CALLER</pre><p>The commented opcodes perform the following actions: the ‘CALLVALUE’ checks the amount in wei sent with the transaction, duplicates it with the ‘DUP’ opcode, and then determines if it’s equal to zero using the ‘ISZERO’ opcode.</p><p>If the value is zero, the ‘ISZERO’ opcode pushes 1 onto the stack, which means ‘true’, and continues execution. If not, it pushes 0, meaning ‘false’.</p><p>In this case, the ‘CALLVALUE’ is expected to be zero since the constructor wasn’t set to be payable, meaning no value was intended to be sent with the transaction. If a value is mistakenly sent, the execution will eventually revert, as indicated by the ‘INVALID’ opcode.</p><h4><strong>Opcode for the Payable contract</strong></h4><pre>//Set up the free memory pointer<br>[00] PUSH1 80<br>[02] PUSH1 40<br>[04] MSTORE<br>[05] PUSH1 3f -&gt;<br>[07] DUP1<br>[08] PUSH1 11<br>[0a] PUSH1 00<br>[0c] CODECOPY -&gt;<br>[0d] PUSH1 00<br>[0f] RETURN<br>[10] INVALID<br>[11] PUSH1 80<br>[13] PUSH1 40<br>[15] MSTORE<br>[16] PUSH1 00<br>[18] DUP1<br>[19] REVERT<br>[1a] INVALID<br>[1b] LOG2<br>[1c] PUSH5 6970667358<br>[22] INVALID<br>[23] SLT<br>[24] SHA3<br>[25] INVALID<br>[26] MULMOD<br>[27] INVALID<br>[28] INVALID<br>[29] SWAP4<br>[2a] INVALID<br>[2b] RETURN<br>[2c] CALLCODE<br>[2d] LOG4<br>[2e] INVALID<br>[2f] INVALID<br>[30] INVALID<br>[31] LOG4<br>[32] SWAP13<br>[33] INVALID<br>[34] GT<br>[35] INVALID<br>[36] INVALID<br>[37] SWAP10<br>[38] INVALID<br>[39] SDIV<br>[3a] INVALID<br>[3b] PUSH30 05fa3e9cd05f3e143364736f6c63430008110033</pre><p>For the payable contract, the EVM skips the checks as it assumes that a value will be sent with the transaction resulting in a lower gas cost compared to the non payable contract.</p><h3>Conclusion</h3><p>To summarize the gas cost analysis, the use of the ‘CALLVALUE’ and other opcodes which follow for non-payable functions results in increased gas costs, as each opcode incurs a gas fee.</p><p>Thank you for joining me on this journey through Solidity’s payable and non-payable functions! I trust that you now have a better understanding of how these functions operate, the distinctions between them, and why payable functions are a more gas-efficient alternative in Solidity smart contracts. If this article has been helpful to you, ensure you like, comment, follow me, and share this article with others so that it can reach a wider audience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d031c6ae577b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/exploring-the-differences-between-payable-and-non-payable-functions-in-solidity-an-in-depth-d031c6ae577b">Exploring the Differences Between Payable and Non-Payable Functions in Solidity: An In-Depth…</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>