<?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 molaratai on Medium]]></title>
        <description><![CDATA[Stories by molaratai on Medium]]></description>
        <link>https://medium.com/@molaratai?source=rss-cb00521e466f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KCF7xRuRXAezZBG_hdR_vw.jpeg</url>
            <title>Stories by molaratai on Medium</title>
            <link>https://medium.com/@molaratai?source=rss-cb00521e466f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 00:14:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@molaratai/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[Creating ERC20 Token Using OpenZeppelin]]></title>
            <link>https://levelup.gitconnected.com/creating-erc20-token-using-openzeppelin-4272e6ec08dd?source=rss-cb00521e466f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4272e6ec08dd</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[molaratai]]></dc:creator>
            <pubDate>Thu, 03 Oct 2024 20:27:52 GMT</pubDate>
            <atom:updated>2024-10-03T20:27:52.026Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating ERC20 Token Using OpenZeppelin.</h3><p>Building and Deploying ERC20 Token Using OpenZeppelin and Foundry</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*BVAfJKDN4W_Vwjm9gPgnBw.png" /></figure><p>Lately, I’ve been exploring the fascinating world of ERC20 tokens, and I decided it was time to try creating one myself.</p><p>Armed with OpenZeppelin’s trusted libraries and Foundry for deployment, I set off on this new project and learned a lot along the way.</p><p>In this article, I’ll guide you through building and deploying an ERC20 token from scratch, leveraging OpenZeppelin’s libraries to simplify the work while using Foundry for testing and deployment.</p><p>If you’re looking to understand how to get started with ERC20 tokens, let’s dive right in!</p><h3>Understanding ERC20 Standard</h3><p>ERC20 is a token standard that defines six mandatory and three optional functions for token interaction. OpenZeppelin’s <strong>ERC20</strong> contract already implements these functions, such as:</p><ol><li><strong>Six Mandatory Functions</strong>:</li></ol><ul><li>OpenZeppelin’s ERC20.sol contract <strong>implements</strong> all the six mandatory functions (<em>totalSupply, balanceOf, transfer, approve, allowance </em>and<em> transferFrom</em>).</li><li>The logic for each of these functions is already written and tested, making it easy for developers to integrate secure token functionality by inheriting from ERC20.</li></ul><p><strong>2. Three Optional Functions</strong>:</p><ul><li>OpenZeppelin also provides optional functionality, including the <em>name, symbol </em>and <em>decimals</em> functions. These can be customized by developers while inheriting the ERC20 contract.</li><li>For instance, in our token below, we would specify the token’s name and symbol in the constructor, while the <em>decimals </em>is usually set to 18 by default.</li></ul><h4>Benefits of Using OpenZeppelin’s ERC20</h4><ul><li><strong>Security</strong>: OpenZeppelin’s ERC20 implementation is widely audited and trusted by the community, significantly reducing the likelihood of vulnerabilities.</li><li><strong>Simplicity</strong>: Instead of implementing all the ERC20 functions yourself, you can inherit OpenZeppelin’s implementation and focus on customizing your specific token logic.</li><li><strong>Extendability</strong>: OpenZeppelin’s contracts are modular and extensible, allowing you to add features such as minting, burning, or pausing tokens with ease.</li></ul><p>We’ll extend OpenZeppelin’s ERC20 contract to create our own custom token.</p><h3>Setting Up the Development Environment</h3><p>Before writing the token contract, we’ll need to set up a smart contract development environment. You can use either Hardhat or Foundry. We’ll be using Foundry for this project.</p><h4><strong>Create a new Foundry project:</strong></h4><pre>mkdir erc20-token<br>cd erc20-token<br>forge init</pre><h4><strong>OpenZeppelin contracts</strong></h4><p>To use OpenZeppelin with Foundry, we need to install the OpenZeppelin contracts. We can do this by adding it to your project with the following command:</p><pre>forge install OpenZeppelin/openzeppelin-contracts --no-commit</pre><p>This will install the OpenZeppelin contracts in our project.</p><h4>Set it up:</h4><ol><li>Inside src, create a new file called <em>Token.sol</em>.</li><li>Inside the script, create a new file <em>DeployToken.s.sol</em>.</li><li>Inside the test folder, create a file <em>TestToken.t.sol</em>.</li><li>Inside foundry.toml add <em>remappings</em>:</li></ol><pre>remappings = [<br>    &#39;@openzeppelin=lib/openzeppelin-contracts/&#39;,<br>]</pre><p>Our Foundry project will have the following structure:</p><pre>erc20-token/<br>├── lib/<br>│   └── openzeppelin-contracts/            // OpenZeppelin dependencies<br>├── script/<br>│   └── DeployToken.s.sol                 // Deployment script<br>├── src/<br>│   └── Token.sol                        // ERC20 Token contract<br>├── test/<br>│   └── TestToken.t.sol                 // Token tests <br>├── foundry.toml                       // Foundry configuration file<br><br><br></pre><h3>File: src/Token.sol</h3><p>The ERC20 token contract will look like this:</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.27;<br><br>import {ERC20} from &quot;@openzeppelin/contracts/token/ERC20/ERC20.sol&quot;;<br><br>contract Token is ERC20 {<br>    constructor(uint256 initialSupply) ERC20(&quot;MyToken&quot;, &quot;MTK&quot;) {<br>        _mint(msg.sender, initialSupply);<br>    }<br>}</pre><h4>Explanation:</h4><ul><li><strong>ERC20 Contract</strong>: We&#39;re importing the ERC20 contract from OpenZeppelin, which provides the basic functionality of an ERC20 token.</li><li><strong>Constructor</strong>: In the constructor, we initialize the token with a name “MyToken” and symbol “MTK.” We also call the _mint function to create the initial supply and assign it to the contract deployer.</li></ul><h3>File: script/DeployToken.s.sol</h3><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.27;<br><br>import {Script} from &quot;forge-std/Script.sol&quot;;<br>import {Token} from &quot;../src/Token.sol&quot;;<br><br>contract Deploy is Script {<br>    uint256 public constant INITIAL_SUPPLY = 1_000_000 ether;<br><br>    function run() external returns (Token) {<br>        vm.startBroadcast();<br>        Token token = new Token(INITIAL_SUPPLY);<br>        vm.stopBroadcast();<br>        return token;<br>    }<br>}</pre><h4>Explanation:</h4><ul><li><strong>Script Contract</strong>: This contract inherits from the Script contract provided by Foundry, which gives us access to the vm object to handle the deployment.</li><li><strong>Initial Supply</strong>: We’re setting the initial token supply to 1,000,000 tokens (represented in wei with ether for better readability).</li><li><strong>vm.startBroadcast() and </strong><strong>vm.stopBroadcast()</strong>: These functions signal the beginning and end of the contract deployment, allowing the Foundry environment to broadcast the transaction on-chain.</li></ul><h3>File: test/TestToken.t.sol</h3><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.27;<br><br>import {Test} from &quot;forge-std/Test.sol&quot;;<br>import {Token} from &quot;../src/Token.sol&quot;;<br>import {Deploy} from &quot;../script/DeployToken.s.sol&quot;;<br><br>interface MintableToken {<br>    function mint(address, uint256) external;<br>}<br><br>contract TestToken is Test {<br>    Token public token;<br>    Deploy public deployer;<br>    uint256 bobInitialBalance = 100 ether;<br><br>    uint256 public constant INITIAL_SUPPLY = 1_000_000 ether;<br>    address public constant BOB = address(1);<br>    address public constant ALICE = address(2);<br><br>    function setUp() public {<br>        token = new Token(INITIAL_SUPPLY);<br>        token.transfer(msg.sender, INITIAL_SUPPLY);<br>        deployer = new Deploy();<br><br>        vm.prank(msg.sender);<br>        token.transfer(BOB, bobInitialBalance);<br>    }<br><br>    function testTotalSupply() public view {<br>        token.totalSupply();<br>        assertEq(token.totalSupply(), deployer.INITIAL_SUPPLY());<br>    }<br><br>    function testUsersCantMint() public {<br>        vm.expectRevert();<br>        MintableToken(address(token)).mint(address(this), 1);<br>    }<br><br>    function testBalance() public view {<br>        uint256 balance = token.totalSupply() - token.balanceOf(BOB);<br>        assertEq(token.balanceOf(msg.sender), balance);<br>    }<br><br>    function testTransfer() public {<br>        address MARK = address(3);<br>        vm.prank(msg.sender);<br>        token.transfer(MARK, 500 ether);<br>        uint256 balance = token.totalSupply() - (token.balanceOf(BOB) + token.balanceOf(MARK));<br>        assertEq(token.balanceOf(msg.sender), balance);<br>    }<br><br>    function testTransferFrom() public {<br>        vm.prank(BOB);<br>        token.approve(ALICE, 20 ether); // BOB approves ALICE to spend 20 ethers on his behalf<br><br>        vm.prank(ALICE);<br>        token.transferFrom(BOB, ALICE, 10 ether);<br>        assertEq(token.balanceOf(BOB), bobInitialBalance - 10 ether);<br>        assertEq(token.balanceOf(ALICE), 10 ether);<br><br>        vm.prank(ALICE);<br>        token.transferFrom(BOB, ALICE, 10 ether);<br>        assertEq(token.balanceOf(BOB), bobInitialBalance - token.balanceOf(ALICE));<br>        assertEq(token.balanceOf(ALICE), 20 ether);<br>    }<br><br>    function testTokenName() public view {<br>        assertEq(token.name(), &quot;MyToken&quot;);<br>        assertEq(token.symbol(), &quot;MTK&quot;);<br>    }<br><br>    function testDeployment() public {<br>        token = deployer.run();<br>        assertTrue(address(token) != address(0));<br><br>        assertTrue(deployer.INITIAL_SUPPLY() == INITIAL_SUPPLY);<br>    }<br>}</pre><p>Here’s an explanation and breakdown of the test file:</p><h4>1. MintableToken Interface</h4><pre>interface MintableToken {<br>    function mint(address, uint256) external;<br>}</pre><p>This interface defines a <strong>mint</strong> function that can be used to mint new tokens. However, this function <strong>does not exist</strong> in the Token contract since it inherits OpenZeppelin&#39;s ERC20 standard, which doesn&#39;t include a public mint function.</p><p><strong>Why Include This Interface?</strong> The purpose of including the MintableToken interface is to attempt minting in one of the test functions (testUsersCantMint) and ensure that users cannot mint tokens directly. It creates a way to check that the contract adheres to the standard ERC20 behavior by rejecting unauthorized minting attempts.</p><h4>2. State Variables</h4><pre>Token public token;<br>Deploy public deployer;<br>uint256 bobInitialBalance = 100 ether;<br><br>uint256 public constant INITIAL_SUPPLY = 1_000_000 ether;<br>address public constant BOB = address(1);<br>address public constant ALICE = address(2);</pre><ul><li><strong>token</strong>: Instance of the Token contract, used to interact with the token in tests.</li><li><strong>deployer</strong>: Instance of the deployment script (Deploy) used to test the deployment process.</li><li><strong>bobInitialBalance</strong>: A balance of 100 ethers, transferred to the BOB address as part of the tests.</li><li><strong>INITIAL_SUPPLY</strong>: The total supply of the token, set to 1,000,000 tokens (denoted in ethers to represent token units).</li><li><strong>BOB &amp; </strong><strong>ALICE</strong>: Placeholder addresses used for testing transfers and approvals.</li></ul><h4>3. Setup Function</h4><pre>function setUp() public {<br>    token = new Token(INITIAL_SUPPLY);  // Create the token with the initial supply<br>    token.transfer(msg.sender, INITIAL_SUPPLY);  // Transfer the total supply to msg.sender<br>    deployer = new Deploy();  // Initialize the deployment script<br><br>    vm.prank(msg.sender);<br>    token.transfer(BOB, bobInitialBalance);  // Transfer 100 tokens to BOB<br>}</pre><ul><li><strong>Purpose</strong>: The setUp() function runs before every test to initialize the state.</li><li><strong>new Token(INITIAL_SUPPLY)</strong>: Creates a new instance of the Token contract with an initial supply of 1,000,000 tokens.</li><li><strong>token.transfer(msg.sender, INITIAL_SUPPLY)</strong>: Transfers the entire supply to the contract deployer&#39;s (msg.sender) address.</li><li><strong>vm.prank()</strong>: Simulates a function call as if it is coming from another address (in this case, msg.sender and BOB).</li></ul><h4>4. Test for Total Supply</h4><pre>function testTotalSupply() public view {<br>    token.totalSupply();<br>    assertEq(token.totalSupply(), deployer.INITIAL_SUPPLY());<br>}</pre><ul><li><strong>Purpose</strong>: To test that the total supply of the token is correct.</li><li><strong>token.totalSupply()</strong>: Retrieves the total supply of the token.</li><li><strong>assertEq()</strong>: Asserts that the token&#39;s total supply equals the constant INITIAL_SUPPLY.</li></ul><h4>5. Test for Minting Restriction</h4><pre>function testUsersCantMint() public {<br>    vm.expectRevert();  // Expect the transaction to revert (fail)<br>    MintableToken(address(token)).mint(address(this), 1);  // Try to mint 1 token<br>}</pre><ul><li><strong>Purpose</strong>: To ensure that unauthorized users cannot mint new tokens.</li><li><strong>vm.expectRevert()</strong>: This function tells the test to expect a revert (i.e., a failed transaction). Since the token contract does not have a mint function, trying to mint will revert.</li><li><strong>MintableToken(address(token)).mint(address(this), 1)</strong>: This calls the non-existent mint function via the MintableToken interface. Since the Token contract does not support minting, this operation should fail, as expected.</li></ul><p>This is where the MintableToken interface is applied. It attempts to interact with a mint function that doesn’t exist in the contract to verify that users can&#39;t add new tokens arbitrarily.</p><h4>6. Test Balance Check</h4><pre>function testBalance() public view {<br>    uint256 balance = token.totalSupply() - token.balanceOf(BOB);<br>    assertEq(token.balanceOf(msg.sender), balance);<br>}</pre><ul><li><strong>Purpose</strong>: To check the balance of the deployer (msg.sender) after transferring 100 tokens to BOB.</li><li><strong>balanceOf(BOB)</strong>: Gets the balance of the BOB address.</li><li><strong>assertEq()</strong>: Asserts that the balance of msg.sender is equal to the total supply minus what was transferred to BOB.</li></ul><h4>7. Test Token Transfer</h4><pre>function testTransfer() public {<br>    address MARK = address(3);  // Another address for testing<br>    vm.prank(msg.sender);  // Simulate msg.sender<br>    token.transfer(MARK, 500 ether);  // Transfer 500 tokens to MARK<br>    uint256 balance = token.totalSupply() - (token.balanceOf(BOB) + token.balanceOf(MARK));<br>    assertEq(token.balanceOf(msg.sender), balance);<br>}</pre><ul><li><strong>Purpose</strong>: To test a simple token transfer from msg.sender to another address, MARK.</li><li><strong>token.transfer(MARK, 500 ether)</strong>: Transfers 500 tokens from msg.sender to MARK.</li><li><strong>assertEq()</strong>: Ensures that the new balance of msg.sender is correctly reduced after the transfer.</li></ul><h4>8. Test TransferFrom Functionality</h4><pre>function testTransferFrom() public {<br>    vm.prank(BOB);<br>    token.approve(ALICE, 20 ether);  // BOB approves ALICE to spend 20 tokens on his behalf<br><br>    vm.prank(ALICE);<br>    token.transferFrom(BOB, ALICE, 10 ether);  // ALICE transfers 10 tokens from BOB to herself<br>    assertEq(token.balanceOf(BOB), bobInitialBalance - 10 ether);<br>    assertEq(token.balanceOf(ALICE), 10 ether);<br>}</pre><ul><li><strong>Purpose</strong>: To test the approve and transferFrom mechanism, which allows one user to spend another user&#39;s tokens.</li><li><strong>approve(ALICE, 20 ether)</strong>: BOB approves ALICE to spend up to 20 tokens on his behalf.</li><li><strong>transferFrom(BOB, ALICE, 10 ether)</strong>: ALICE transfers 10 tokens from BOB to herself.</li><li><strong>assertEq()</strong>: Asserts that BOB&#39;s balance is reduced by 10 tokens, and ALICE&#39;s balance is increased by 10 tokens.</li></ul><h4>9. Test Token Name and Symbol</h4><pre>function testTokenName() public view {<br>    assertEq(token.name(), &quot;MyToken&quot;);<br>    assertEq(token.symbol(), &quot;MTK&quot;);<br>}</pre><ul><li><strong>Purpose</strong>: To check that the token’s name and symbol are correctly set.</li><li><strong>assertEq()</strong>: Verifies that the token’s name is &quot;MyToken&quot; and the symbol is &quot;MTK&quot;.</li></ul><h4>10. Test Deployment Script</h4><pre>function testDeployment() public {<br>    token = deployer.run();  // Run the deployment script<br>    assertTrue(address(token) != address(0));  // Ensure the token address is not zero<br><br>    assertTrue(deployer.INITIAL_SUPPLY() == INITIAL_SUPPLY);  // Ensure the initial supply is correct<br>}</pre><ul><li><strong>Purpose</strong>: To test that the deployment script works as expected and that the contract is deployed with the correct initial supply.</li><li><strong>deployer.run()</strong>: Calls the run() function from the deployment script to deploy the Token contract.</li><li><strong>assertTrue(address(token) != address(0))</strong>: Ensures that the deployed contract address is valid (non-zero).</li><li><strong>assertTrue()</strong>: Checks that the initial supply set during deployment matches the expected value.</li></ul><h3>Conclusion</h3><p>With OpenZeppelin’s secure libraries, we can easily implement the standard ERC20 functions while maintaining security best practices.</p><p>Using Foundry, the deployment and testing process becomes streamlined, allowing for efficient development.</p><p>As I continue my journey, I’ll keep exploring and sharing more advanced token features such as minting and burning to enhance my smart contract skills.</p><h3>Additional Resources</h3><p>Here are some helpful resources:</p><ol><li><a href="https://docs.openzeppelin.com/contracts/5.x/erc20"><strong>OpenZeppelin ERC20 Documentation</strong></a></li><li><a href="https://docs.soliditylang.org/en/v0.8.27/introduction-to-smart-contracts.html"><strong>Solidity Documentation</strong></a></li><li><a href="https://book.getfoundry.sh/"><strong>Foundry Documentation</strong></a></li><li><a href="https://ethereum.org/en/developers/docs/standards/tokens/erc-20/"><strong>Ethereum ERC20 Standard</strong></a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4272e6ec08dd" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/creating-erc20-token-using-openzeppelin-4272e6ec08dd">Creating ERC20 Token Using OpenZeppelin</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Simple Auction Contract: Creating, Testing and Deploying using Foundry]]></title>
            <link>https://levelup.gitconnected.com/a-simple-auction-contract-creating-testing-and-deploying-using-foundry-046d40016174?source=rss-cb00521e466f------2</link>
            <guid isPermaLink="false">https://medium.com/p/046d40016174</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[foundry]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[molaratai]]></dc:creator>
            <pubDate>Sun, 29 Sep 2024 16:54:18 GMT</pubDate>
            <atom:updated>2024-09-29T16:54:18.844Z</atom:updated>
            <content:encoded><![CDATA[<p>Exploring the Basics of Auction Functionality and Testing</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*wgvyuTiGywPa5RCxc6P0MQ.jpeg" /></figure><p>Recently, I decided to dive deep into the world of smart contract testing on my journey through development. I even posted my first tested contract in this <a href="https://medium.com/gitconnected/a-simple-voting-system-creating-testing-and-deploying-using-foundry-0d8d6de29e8b">article</a> .</p><p>In the spirit of learning, I embarked on a new project, and I’m glad I did.</p><p>Sure, I might have one pesky failing test function out of ten</p><pre><br>Ran 10 tests for test/TestAuction.t.sol:TestAuction<br>[PASS] test_FallbackFunction() (gas: 110575)<br>[PASS] test_auctionEndedModifier() (gas: 14344)<br>[PASS] test_deployment() (gas: 615474)<br>[PASS] test_onlyOwnerModifier() (gas: 11310)<br>[PASS] test_pickWinner() (gas: 151496)<br>[PASS] test_placeBid() (gas: 166304)<br>[PASS] test_recieveFunction() (gas: 109977)<br>[PASS] test_refund() (gas: 180477)<br>[PASS] test_remainingTime() (gas: 10460)<br>[FAIL: revert: WithdrawFailed] test_withdraw() (gas: 119648)<br>Suite result: FAILED. 9 passed; 1 failed; 0 skipped; finished in 39.03ms (32.84ms CPU time)</pre><p>(thanks for keeping me humble, code!), but I’ve learned so much along the way.</p><p>The best part? I’m on a mission to fix that little hiccup and will update the article soon! Let’s dive into the ups and downs of smart contract testing as a beginner together!</p><h3>1. src file(Auction.sol)</h3><p>The auction system includes a function for users to place their bid, a function for the contract owner to pick a winner and withdrawn Ether after the auction ends.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.20;<br><br>contract Auction {<br>    error Auction__InvalidWithdrawAmount();<br>    error Auction__OnlyOwnerCanCall();<br>    error Auction__MinimumNotMet();<br>    error Auction__BiddingNotOver();<br>    error Auction__InvalidAccount();<br>    error Auction__BidTooLow();<br>    error Auction__Ended();<br><br>    <br>    uint256 private constant MINIMUM_BID = 5 ether;<br>    address private immutable i_owner;<br>    uint256 private immutable i_bidEnded;<br>    uint256 private highestBid;<br>    uint256 private totalBid;<br>    address private highestBidder;<br><br>    mapping(address =&gt; uint256) private bidder;<br><br>    event PaymentFunction(string message);<br>    event HighestBid(address user, uint256 amount, string message);<br>    event Refunded(address user, uint256 amount);<br>    event WinnerPicked(string message, uint256 bid, address winner);<br><br>    modifier onlyOwner() {<br>        if (msg.sender != i_owner) {<br>            revert Auction__OnlyOwnerCanCall();<br>        }<br>        _;<br>    }<br><br>    modifier auctionEnded() {<br>        require(block.timestamp &gt;= i_bidEnded, Auction__BiddingNotOver());<br>        _;<br>    }<br><br>    constructor(uint256 _bidEnded) {<br>        i_owner = msg.sender;<br>        i_bidEnded = block.timestamp + _bidEnded;<br>    }<br><br>    receive() external payable {<br>        placeBid();<br>        emit PaymentFunction(&quot;Receive Function called&quot;);<br>    }<br><br>    fallback() external payable {<br>        if (msg.sender != i_owner) {<br>            placeBid();<br>            emit PaymentFunction(&quot;Fallback Function called&quot;);<br>        }<br>    }<br><br><br>    function placeBid() public payable {<br>        require(msg.value &gt; MINIMUM_BID, Auction__MinimumNotMet());<br>        require(msg.value &gt; highestBid, Auction__BidTooLow());<br>        require(msg.sender != address(0), Auction__InvalidAccount());<br>        require(block.timestamp &lt;= i_bidEnded, Auction__Ended());<br><br>        uint256 previousBid = bidder[msg.sender];<br>        bidder[msg.sender] = msg.value;<br>        totalBid += msg.value;<br><br>        if (previousBid &gt; 0) {<br>            (bool refundSuccess,) = msg.sender.call{value: previousBid}(&quot;&quot;);<br>            require(refundSuccess, &quot;Refund Failed&quot;);<br>            emit Refunded(msg.sender, previousBid);<br>        }<br><br>        highestBidder = msg.sender;<br>        highestBid = msg.value;<br><br>        emit HighestBid(msg.sender, msg.value, &quot;New highestBid added&quot;);<br>    }<br><br><br>    function pickWinner() public onlyOwner auctionEnded {<br>        require(highestBid &gt; 0 &amp;&amp; highestBidder != address(0), &quot;No bids placed&quot;);<br>        emit WinnerPicked(&quot;Winner selected!&quot;, highestBid, highestBidder);<br>    }<br><br><br>    function refund() public auctionEnded {<br>        uint256 biddedAmount = bidder[msg.sender];<br>        require(msg.sender != address(0) || msg.sender != highestBidder, &quot;Cannot Refund&quot;);<br>        require(biddedAmount &lt; highestBid, &quot;Higghest bidder cannot be Refunded&quot;);<br><br>        bidder[msg.sender] = 0; // Set their balance to 0<br>        totalBid -= biddedAmount; // Decrease the total donation amount<br><br>        // Send back the amount<br>        (bool success,) = msg.sender.call{value: biddedAmount}(&quot;&quot;);<br>        require(success, &quot;RefundFailed&quot;);<br><br>        emit Refunded(msg.sender, biddedAmount);<br>    }<br><br><br>    function withdraw() external onlyOwner auctionEnded {<br>        uint256 contractBalance = address(this).balance;<br><br>        require(contractBalance &gt; 0, &quot;Invalid withdraw amount&quot;);<br>         <br>        (bool success,) = i_owner.call{value: contractBalance}(&quot;&quot;);<br>        require(success, &quot;WithdrawFailed&quot;);<br><br>        emit PaymentFunction(&quot;Withdrawal completed!&quot;);<br>    }<br><br>    /////Getter functions/////<br><br>    function getOwner() public view returns (address) {<br>        return i_owner;<br>    }<br><br>    function getHighestBid() public view returns (uint256) {<br>        return highestBid;<br>    }<br><br>    function getHighestBidder() public view returns (address) {<br>        return highestBidder;<br>    }<br><br>    function getContractBalance() public view returns (uint256) {<br>        return address(this).balance;<br>    }<br><br>    function getTimeLeft() public view returns (uint256) {<br>        if (block.timestamp &gt;= i_bidEnded) {<br>            return 0;<br>        } else {<br>            return (i_bidEnded - block.timestamp);<br>        }<br>    }<br>}</pre><h4>Breaking down the code:</h4><h3>Constructor</h3><p>The constructor initializes the owner and sets the end time for the auction.</p><pre>constructor(uint256 _bidEnded) {<br>    i_owner = payable(msg.sender);<br>    i_bidEnded = block.timestamp + _bidEnded;<br>}</pre><p>The owner is the account that deploys the contract, and _bidEnded defines how long the auction will last.</p><blockquote>The constructor will be used while writing the deployment script to initialize _bidEnded to the specified time we want.</blockquote><blockquote>Deployment script is added after the Voting.sol contract explanation.</blockquote><h3>Modifiers</h3><p>Modifiers are used to restrict function execution or to add preconditions before a function is run.</p><p><strong>onlyOwner Modifier</strong></p><pre>modifier onlyOwner() {<br>    if (msg.sender != i_owner) {<br>        revert Auction__OnlyOwnerCanCall();<br>    }<br>    _;<br>}</pre><p>This modifier ensures that only the contract owner can call specific functions, like picking a winner or withdrawing funds.</p><p><strong>auctionEnded Modifier</strong></p><pre>modifier auctionEnded() {<br>    require(block.timestamp &gt;= i_bidEnded, Auction__BiddingNotOver());<br>    _;<br>}</pre><p>This modifier ensures that functions like withdrawing funds or picking the winner can only be called after the auction has ended.</p><h3>Fallback and Receive Functions</h3><p>Solidity provides two special functions to handle incoming Ether: fallback and receive. These functions ensure that any Ether sent to the contract during the auction is considered as a bid.</p><pre>receive() external payable {<br>    placeBid();<br>    emit PaymentFunction(&quot;Receive Function called&quot;);<br>}<br><br>fallback() external payable {<br>    if (msg.sender != i_owner) {<br>        placeBid();<br>        emit PaymentFunction(&quot;Fallback Function called&quot;);<br>    }<br>}</pre><p>The receive() function is called when Ether is sent directly to the contract. The fallback() function serves as a backup if receive() is not available.</p><p>The implemetation and interaction will be shown in the Test file below.</p><h3>Core Functions: Placing Bids, Picking the Winner, and Withdrawing Funds</h3><p>Here’s a breakdown of the most important functions:</p><h4>placeBid()</h4><pre>function placeBid() public payable {<br>    require(msg.value &gt; MINIMUM_BID, Auction__MinimumNotMet());<br>    require(msg.value &gt; highestBid, Auction__BidTooLow());<br>    require(msg.sender != address(0), Auction__InvalidAccount());<br>    require(block.timestamp &lt;= i_bidEnded, Auction__Ended());<br><br>    uint256 previousBid = bidder[msg.sender];<br>    bidder[msg.sender] = msg.value;<br><br>    if (previousBid &gt; 0) {<br>        (bool refundSuccess,) = msg.sender.call{value: previousBid}(&quot;&quot;);<br>        require(refundSuccess, &quot;Refund Failed&quot;);<br>        emit Refunded(msg.sender, previousBid);<br>    }<br><br>    highestBidder = msg.sender;<br>    highestBid = msg.value;<br><br>    emit HighestBid(msg.sender, msg.value, &quot;New highestBid added&quot;);<br>}</pre><p>This function allows users to place bids. It checks that the bid is higher than the minimum bid and the current highest bid.</p><p>If the bidder has placed a bid before, it refunds the previous amount. The new highest bid and bidder are updated.</p><h4>pickWinner()</h4><pre>function pickWinner() public onlyOwner auctionEnded {<br>    require(highestBid &gt; 0 &amp;&amp; highestBidder != address(0), &quot;No bids placed&quot;);<br>    emit WinnerPicked(&quot;Winner selected!&quot;, highestBid, highestBidder);<br>}</pre><p>Once the auction ends, the owner can call this function to declare the highest bidder as the winner.</p><h4>withdraw()</h4><pre>function withdraw() external onlyOwner auctionEnded {<br>    uint256 contractBalance = address(this).balance;<br>    require(contractBalance &gt; 0, &quot;No balance to withdraw&quot;);<br><br>    (bool success,) = i_owner.call{value: contractBalance}(&quot;&quot;);<br>    require(success, Auction__WithdrawFailed());<br><br>    emit PaymentFunction(&quot;Withdrawal completed!&quot;);<br>}</pre><p>This function allows the owner to withdraw the funds after the auction has ended. The contract balance is transferred to the owner’s address.</p><h3>2. script file(DeployAuction.s.sol)</h3><p>In addition to writing smart contracts, you need to deploy them. Below is a simple Foundry script that allows you to deploy your auction contract.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.20;<br><br>import {Script} from &quot;forge-std/Script.sol&quot;;<br>import {Auction} from &quot;../src/Auction.sol&quot;;<br><br>contract Deploy is Script {<br>    uint256 public constant AUCTION_DAYS = 5 days;<br><br>    function run() external returns (Auction) {<br>        vm.startBroadcast();<br>        Auction auction = new Auction(AUCTION_DAYS);<br>        vm.stopBroadcast();<br>        return auction;<br>    }<br>}</pre><h4>Explanation of the Deployment Script:</h4><ul><li><strong>Foundry Setup</strong>: The script uses Foundry’s forge-std library to manage the deployment.</li><li><strong>AUCTION_DAYS</strong>: This sets the duration of the auction to 5 days.</li><li><strong>run() Function</strong>: This function executes the deployment. vm.startBroadcast() broadcasts the transaction to deploy the Auction contract, and vm.stopBroadcast() stops the broadcast.</li></ul><p>Once the deployment is completed, an instance of the Auction contract is returned.</p><h4>Running the Script</h4><p>To deploy the contract using this script, run the following command in your terminal:</p><pre>forge script path/to/Deploy.sol --broadcast --rpc-url &lt;your_rpc_url&gt;</pre><p>This command broadcasts the transaction to deploy your contract to the specified network (e.g.,Sepolia testnet, or your local blockchain).</p><h3>3. test file(TestAuction.t.sol)</h3><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.20;<br><br>import {Test, console} from &quot;forge-std/Test.sol&quot;;<br>import {Auction} from &quot;../src/Auction.sol&quot;;<br>import {Deploy} from &quot;../script/DeployAuction.s.sol&quot;;<br><br>contract TestAuction is Test {<br>    Auction public auction;<br>    Deploy public deploy;<br><br>    uint256 public constant BIDDING_PERIOD = 5 days;<br>    address public constant BOB = address(1);<br>    address public constant ALICE = address(2);<br><br>    function setUp() public {<br>        auction = new Auction(BIDDING_PERIOD);<br>        deploy = new Deploy();<br><br>        vm.deal(BOB, 50 ether);<br>        vm.deal(ALICE, 50 ether);<br>    }<br><br>    function test_onlyOwnerModifier() public {<br>        vm.warp(block.timestamp + 6 days);<br>        vm.prank(BOB);<br>        vm.expectRevert(Auction.Auction__OnlyOwnerCanCall.selector);<br>        auction.withdraw();<br>    }<br><br>    function test_auctionEndedModifier() public {<br>        vm.warp(block.timestamp + 3 days);<br>        vm.expectRevert(Auction.Auction__BiddingNotOver.selector);<br>        auction.withdraw();<br>        vm.expectRevert(Auction.Auction__BiddingNotOver.selector);<br>        auction.pickWinner();<br>    }<br><br>    function test_placeBid() public {<br>        vm.prank(BOB);<br>        auction.placeBid{value: 10 ether}();<br><br>        vm.prank(ALICE);<br>        auction.placeBid{value: 15 ether}();<br><br>        vm.prank(BOB);<br>        auction.placeBid{value: 20 ether}();<br><br>        assertEq(auction.getHighestBid(), 20 ether);<br>        assertEq(auction.getContractBalance(), 35 ether);<br>        assertEq(auction.getHighestBidder(), BOB);<br>        auction.getContractBalance();<br>    }<br><br>    function test_refund() public {<br>        vm.warp(block.timestamp + BIDDING_PERIOD);<br><br>        vm.prank(BOB);<br>        auction.placeBid{value: 10 ether}();<br>        vm.prank(ALICE);<br>        auction.placeBid{value: 15 ether}();<br>        assertEq(auction.getContractBalance(), 25 ether);<br><br>        vm.prank(BOB);<br>        auction.placeBid{value: 20 ether}();<br>        vm.prank(ALICE);<br>        auction.placeBid{value: 25 ether}();<br>        assertEq(auction.getContractBalance(), 45 ether);<br><br>        vm.prank(BOB);<br>        auction.refund();<br>        assertEq(auction.getContractBalance(), 25 ether);<br>        auction.getHighestBid();<br>        auction.getHighestBidder();<br>    }<br><br>    function test_remainingTime() public {<br>        uint256 time = 5 days - block.timestamp + 1;<br>        assertEq(auction.getTimeLeft(), time);<br><br>        vm.warp(block.timestamp + 7 days);<br>        assertEq(auction.getTimeLeft(), 0);<br>    }<br><br>    function test_recieveFunction() public {<br>        vm.prank(BOB);<br>        (bool success,) = address(auction).call{value: 6 ether}(&quot;&quot;);<br>        require(success);<br><br>        assertEq(auction.getHighestBid(), 6 ether);<br>        assertEq(auction.getHighestBidder(), BOB);<br>    }<br><br>    function test_FallbackFunction() public {<br>        vm.prank(BOB);<br>        (bool success,) = address(auction).call{value: 10 ether}(abi.encodeWithSignature(&quot;invalidFunction()&quot;));<br>        require(success);<br>        assertEq(address(auction).balance, 10 ether);<br>    }<br><br>    function test_pickWinner() public {<br>        vm.prank(BOB);<br>        auction.placeBid{value: 20 ether}();<br><br>        vm.prank(ALICE);<br>        (bool success,) = address(auction).call{value: 30 ether}(abi.encodeWithSignature(&quot;invalidFunction()&quot;));<br>        require(success);<br><br>        vm.warp(block.timestamp + 5 days); // Move time past the auction end<br>        auction.pickWinner();<br><br>        assertEq(auction.getHighestBid(), 30 ether);<br>        assertEq(auction.getHighestBidder(), ALICE);<br>        auction.getContractBalance();<br>        auction.getHighestBidder();<br>    }<br><br>    function test_withdraw() public {<br>        vm.prank(BOB);<br>        auction.placeBid{value: 20 ether}();<br><br>        auction.getHighestBid();<br>        auction.getContractBalance();<br><br>        vm.warp(block.timestamp + 5 days);<br>        vm.startPrank(auction.getOwner());<br>        auction.withdraw();<br>        assertEq(address(auction).balance, 0);<br>        vm.stopPrank();<br>    }<br><br>    function test_deployment() public {<br>        auction = deploy.run();<br>        assertTrue(address(auction) != address(0), &quot;Auction invalid address&quot;);<br><br>        uint256 auctionPeriod = BIDDING_PERIOD;<br>        uint256 currentTime = block.timestamp;<br>        uint256 expectedAuctionEnd = currentTime + 5 days;<br><br>        assertTrue(<br>            auctionPeriod &gt;= expectedAuctionEnd - 2 &amp;&amp; auctionPeriod &lt;= expectedAuctionEnd + 2,<br>            &quot;Auction duration should be approximately 5 days&quot;<br>        );<br>    }<br>}</pre><p>Let’s break down the test file for the Auction contract step by step, explaining each function in detail:</p><h3>Contract Setup</h3><pre>contract TestAuction is Test {<br>    Auction public auction;<br>    Deploy public deploy;<br><br>    uint256 public constant BIDDING_PERIOD = 5 days;<br>    address public constant BOB = address(1);<br>    address public constant ALICE = address(2);</pre><ul><li>The TestAuction contract inherits from the Test contract provided by Foundry, allowing us to use testing features.</li><li>auction is an instance of the Auction contract being tested, while deploy is used to deploy instances of the Auction.</li><li>BIDDING_PERIOD sets a constant bidding duration of 5 days.</li><li>BOB and ALICE are predefined addresses representing two bidders.</li></ul><h3>setUp Function</h3><pre>function setUp() public {<br>    auction = new Auction(BIDDING_PERIOD);<br>    deploy = new Deploy();<br><br>    vm.deal(BOB, 50 ether); // set BOB account to 50 ether<br>    vm.deal(ALICE, 50 ether); // set ALICE account to 50 ether<br>}</pre><ul><li>This function initializes the test environment. It is automatically called before each test function.</li><li>A new Auction contract instance is created with the defined bidding period.</li><li>The vm.deal() function assigns 50 ether to both BOB and ALICE, simulating an environment where these accounts have sufficient funds to participate in the auction.</li></ul><h3>Test Functions</h3><h4>1. test_onlyOwnerModifier</h4><pre>function test_onlyOwnerModifier() public {<br>    vm.warp(block.timestamp + 6 days);<br>    vm.prank(BOB);<br>    vm.expectRevert(Auction.Auction__OnlyOwnerCanCall.selector);<br>    auction.withdraw();<br>}</pre><ul><li><strong>Purpose</strong>: Tests that only the owner of the auction can call the withdraw function after the auction has ended.</li><li>vm.warp() simulates the passage of time, moving the current block timestamp forward by 6 days.</li><li>vm.prank(BOB) sets the context so that any calls made afterward will be treated as if they are coming from BOB.</li><li>vm.expectRevert() anticipates a revert with the specified selector when auction.withdraw() is called, confirming that the modifier works correctly.</li></ul><h4>2. test_auctionEndedModifier</h4><pre>function test_auctionEndedModifier() public {<br>    vm.warp(block.timestamp + 3 days);<br>    vm.expectRevert(Auction.Auction__BiddingNotOver.selector);<br>    auction.withdraw();<br>    vm.expectRevert(Auction.Auction__BiddingNotOver.selector);<br>    auction.pickWinner();<br>}</pre><ul><li><strong>Purpose</strong>: Tests the behavior when trying to withdraw funds or pick a winner before the auction has ended.</li><li>Similar to the previous test, it uses vm.warp() to simulate time progression, but here it sets it to 3 days.</li><li>It checks for reverts for both the withdraw and pickWinner functions, confirming they cannot be called until the auction period is complete.</li></ul><h4>3. test_placeBid</h4><pre>function test_placeBid() public {<br>    vm.prank(BOB);<br>    auction.placeBid{value: 10 ether}();<br>    <br>    vm.prank(ALICE);<br>    auction.placeBid{value: 15 ether}();<br>    <br>    vm.prank(BOB);<br>    auction.placeBid{value: 20 ether}();<br><br>    assertEq(auction.getHighestBid(), 20 ether);<br>    assertEq(auction.getContractBalance(), 35 ether);<br>    assertEq(auction.getHighestBidder(), BOB);<br>}</pre><ul><li><strong>Purpose</strong>: Tests placing bids by multiple users and verifies that the highest bid is correctly tracked.</li><li>Each user (BOB and ALICE) places bids with different values.</li><li>Assertions at the end ensure the highest bid, total contract balance, and highest bidder are accurately updated.</li></ul><h4>4. test_refund</h4><pre>function test_refund() public {<br>    vm.warp(block.timestamp + BIDDING_PERIOD);<br><br>    vm.prank(BOB);<br>    auction.placeBid{value: 10 ether}();<br>    vm.prank(ALICE);<br>    auction.placeBid{value: 15 ether}();<br><br>    vm.prank(BOB);<br>    auction.placeBid{value: 20 ether}();<br>    vm.prank(ALICE);<br>    auction.placeBid{value: 25 ether}();<br><br>    vm.prank(BOB);<br>    auction.refund();<br>    assertEq(auction.getContractBalance(), 25 ether);<br>}</pre><ul><li><strong>Purpose</strong>: Tests the refund mechanism after the auction ends.</li><li>After warping time to the end of the bidding period, both bidders place their bids.</li><li>The test checks that BOB can call refund and verifies the contract balance afterwards.</li></ul><h4>5. test_remainingTime</h4><pre>function test_remainingTime() public {<br>    uint256 time = 5 days - block.timestamp + 1;<br>    assertEq(auction.getTimeLeft(), time);<br><br>    vm.warp(block.timestamp + 7 days);<br>    assertEq(auction.getTimeLeft(), 0);<br>}</pre><ul><li><strong>Purpose</strong>: Tests the function that returns the time left in the auction.</li><li>It checks the remaining time immediately after deployment and confirms it is accurate.</li><li>After warping the time past the auction end, it asserts that the time left is zero.</li></ul><h4>6. test_recieveFunction</h4><pre>function test_recieveFunction() public {<br>    vm.prank(BOB);<br>    (bool success,) = address(auction).call{value: 6 ether}(&quot;&quot;);<br>    require(success);<br><br>    assertEq(auction.getHighestBid(), 6 ether);<br>    assertEq(auction.getHighestBidder(), BOB);<br>}</pre><ul><li><strong>Purpose</strong>: Tests the fallback function when ether is sent directly to the contract without the sender calling any function.</li><li>It uses a low-level call to send ether, simulating a bid.</li><li>Assertions verify that the auction records this as the highest bid.</li></ul><h4>7. test_FallbackFunction</h4><pre>function test_FallbackFunction() public {<br>    vm.prank(BOB);<br>    (bool success,) = address(auction).call{value: 10 ether}(abi.encodeWithSignature(&quot;invalidFunction()&quot;));<br>    require(success);<br>    assertEq(address(auction).balance, 10 ether);<br>}</pre><ul><li><strong>Purpose</strong>: Tests the fallback function’s behavior when an invalid function is called.</li><li>It confirms that ether can still be sent to the contract even if the placeBid function is not called and that the contract balance updates accordingly.</li></ul><h4>8. test_pickWinner</h4><pre>function test_pickWinner() public {<br>    vm.prank(BOB);<br>    auction.placeBid{value: 20 ether}();<br><br>    vm.prank(ALICE);<br>    (bool success,) = address(auction).call{value: 30 ether}(abi.encodeWithSignature(&quot;invalidFunction()&quot;));<br>    require(success);<br><br>    vm.warp(block.timestamp + 5 days);<br>    auction.pickWinner();<br><br>    assertEq(auction.getHighestBid(), 30 ether);<br>    assertEq(auction.getHighestBidder(), ALICE);<br>}</pre><ul><li><strong>Purpose</strong>: Tests the winner selection after the auction has ended.</li><li>After placing bids, it simulates the auction ending and calls pickWinner.</li><li>Assertions confirm that the highest bid and bidder are correctly identified.</li></ul><h4>9. test_withdraw(the failed test)</h4><pre>function test_withdraw() public {<br>    vm.prank(BOB);<br>    auction.placeBid{value: 20 ether}();<br>    <br>    vm.warp(block.timestamp + 5 days);<br>    vm.startPrank(auction.getOwner());<br>    auction.withdraw();<br>    assertEq(address(auction).balance, 0);<br>    vm.stopPrank();<br>}</pre><ul><li><strong>Purpose</strong>: Tests the withdraw function, ensuring the auction owner can withdraw funds after the auction ends.</li></ul><blockquote>The withdraw function throws an error when trying to call it. The article would be updated once it’s fixed.</blockquote><blockquote>If you have a suggestion, please drop a comment. Thanks!</blockquote><h4>10. test_deployment</h4><pre>function test_deployment() public {<br>    auction = deploy.run();<br>    assertTrue(address(auction) != address(0), &quot;Auction invalid address&quot;);<br><br>    uint256 auctionPeriod = BIDDING_PERIOD;<br>    uint256 currentTime = block.timestamp;<br>    uint256 expectedAuctionEnd = currentTime + 5 days;<br><br>    assertTrue(<br>        auctionPeriod &gt;= expectedAuctionEnd - 2 &amp;&amp; auctionPeriod &lt;= expectedAuctionEnd + 2,<br>        &quot;Auction duration should be approximately 5 days&quot;<br>    );<br>}</pre><ul><li><strong>Purpose</strong>: Tests the deployment process of the auction.</li><li>It checks that the auction contract was successfully deployed and verifies the auction period is within expected bounds.</li></ul><h3>Conclusion</h3><p>Each function in this test file plays a crucial role in validating the functionality of the Auction contract. By simulating user interactions and checking expected outcomes, the tests help ensure the contract behaves as intended and is secure against misuse.</p><h3>Additional Resources</h3><ul><li><a href="https://book.getfoundry.sh/">Foundry Documentation</a></li><li><a href="https://docs.soliditylang.org/en/v0.8.27/">Solidity Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=046d40016174" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/a-simple-auction-contract-creating-testing-and-deploying-using-foundry-046d40016174">A Simple Auction Contract: Creating, Testing and Deploying using Foundry</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Simple Voting System: Creating, Testing and Deploying using Foundry]]></title>
            <link>https://levelup.gitconnected.com/a-simple-voting-system-creating-testing-and-deploying-using-foundry-0d8d6de29e8b?source=rss-cb00521e466f------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d8d6de29e8b</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[molaratai]]></dc:creator>
            <pubDate>Fri, 27 Sep 2024 02:00:24 GMT</pubDate>
            <atom:updated>2024-09-27T08:15:44.420Z</atom:updated>
            <content:encoded><![CDATA[<p>Creating a simple voting contract, a deployment script file and a test file for testing both voting and deployment files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*9rWO5_O21_mwRH6S7H3wbA.jpeg" /></figure><h3><strong>Introduction</strong></h3><p>I’ve always shied away from testing, but as I’ve progressed in smart contract development, I’ve realized just how essential it is.</p><p>Lately, I’ve been diving deep into Foundry’s testing functionality, working to improve and boost my test coverage to over 95%.</p><p>In this article, I’m excited to share my journey of building and testing a decentralized voting system using Solidity.</p><p>I’ll walk you through three core files: the Voting smart contract, the deployment script, and the test file.</p><p>My aim is to provide a clear breakdown of each file so that you can follow along, even if you’re just starting out, like me!</p><h3>1. The Voting Smart Contract(Voting.sol)</h3><p>This is the heart of the voting system. The <strong>Voting</strong> contract defines all the functionalities required for adding candidates, casting votes, and determining the winner. Here&#39;s the code:</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.20;<br><br>contract Voting {<br>    error Voting__onlyOwner();<br>    error Voting__VotingEnded();<br>    error Voting__alreadyVoted();<br>    error Voting__invalidCandidateIndex();<br>    error Voting__NoCandidateAvailable();<br><br>    address private immutable i_owner;<br>    uint256 public immutable i_votingEnded;<br>    uint256 public totalVotes;<br><br>    mapping(address =&gt; bool) public hasVoted;<br>    <br>    struct Candidate {<br>        string name;<br>        string partyName;<br>        uint256 voteCount;<br>    }<br><br>    // Mapping for candidates and counter for keeping track of candidates<br>    mapping(uint256 =&gt; Candidate) public candidates;<br>    uint256 public candidateCount;<br><br>    constructor(uint256 _votingDuration) {<br>        i_owner = msg.sender;<br>        i_votingEnded = block.timestamp + _votingDuration;<br>    }<br><br>    event CandidateAdded(string name, string partyName);<br>    event VoteCasted(address voter, uint256 candidateIndex);<br><br><br>    modifier onlyOwner() {<br>        require(msg.sender == i_owner, Voting__onlyOwner());<br>        _;<br>    }<br><br><br>    modifier votingTime() {<br>        require(block.timestamp &lt; i_votingEnded, Voting__VotingEnded());<br>        _;<br>    }<br><br><br>    function addCandidate(string memory _name, string memory _partyName) public onlyOwner {<br>        candidates[candidateCount] = Candidate(_name, _partyName, 0);<br>        candidateCount++;<br><br>        emit CandidateAdded(_name, _partyName);<br>    }<br><br><br>    function vote(uint256 candidateIndex) public votingTime {<br>        require(!hasVoted[msg.sender], Voting__alreadyVoted());<br>        require(candidateIndex &lt; candidateCount, Voting__invalidCandidateIndex());<br><br>        hasVoted[msg.sender] = true;<br>        candidates[candidateIndex].voteCount += 1;<br>        totalVotes += 1;<br><br>        emit VoteCasted(msg.sender, candidateIndex);<br>    }<br><br>      function getWinner() public view returns (string memory winnerName, string memory winnerParty, uint256 winnerVoteCount) {<br>        require(candidateCount &gt; 0, Voting__NoCandidateAvailable());<br>        <br>        uint256 winningVoteCount = 0;<br>        uint256 winningIndex = 0;<br><br>        for (uint256 i = 0; i &lt; candidateCount; i++) {<br>            if (candidates[i].voteCount &gt; winningVoteCount) {<br>                winningVoteCount = candidates[i].voteCount;<br>                winningIndex = i;<br>            }<br>        }<br>        Candidate memory winner = candidates[winningIndex];<br>        return (winner.name, winner.partyName, winner.voteCount);<br>    }<br><br><br>    function getCanditateIndex(uint256 index) public view returns (string memory, string memory, uint256) {<br>        require(index &lt; candidateCount, Voting__invalidCandidateIndex());<br>        Candidate memory candidate = candidates[index];<br>        return (candidate.name, candidate.partyName, candidate.voteCount);<br>    }<br><br>    function getCandidateCount() public view returns (uint256) {<br>        return candidateCount;<br>    }<br><br>    function getRemainingVotingTime() public view returns (uint256) {<br>        if (block.timestamp &gt;= i_votingEnded) {<br>            return 0;<br>        }<br>        return (i_votingEnded - block.timestamp);<br>    }<br><br>    function getTotalVotes() public view returns (uint256) {<br>        return totalVotes;<br>    }<br><br>    function getVotePerCandidate(uint256 candidateIndex) public view returns (uint256) {<br>        return candidates[candidateIndex].voteCount;<br>    }<br>}</pre><h4>Here’s a detailed breakdown:</h4><pre>contract Voting {<br>    error Voting__onlyOwner();<br>    error Voting__VotingEnded();<br>    error Voting__alreadyVoted();<br>    error Voting__invalidCandidateIndex();<br>    error Voting__NoCandidateAvailable();</pre><p><strong>Custom Errors</strong>: Custom errors are used instead of regular require statements because they save gas. For example, Voting__onlyOwner will be used to indicate that only the owner can perform a specific action.</p><pre>    address private immutable i_owner;<br>    uint256 public immutable i_votingEnded;<br>    uint256 public totalVotes;</pre><ul><li><strong>State Variables</strong>: The contract stores the owner’s address, the voting end time, and the total number of votes.</li><li>i_owner is marked as immutable, meaning it can only be set once during contract deployment and will never change.</li></ul><pre> struct Candidate {<br>        string name;<br>        string partyName;<br>        uint256 voteCount;<br>    }<br><br>    mapping(uint256 =&gt; Candidate) public candidates;<br>    uint256 public candidateCount;</pre><ul><li><strong>Candidate Structure</strong>: Each candidate has a name, a party name, and a vote count.</li><li>Candidates are stored in a mapping using their index number, and candidateCount tracks how many candidates have been added.</li></ul><p><strong>Constructor and Modifiers</strong></p><pre>constructor(uint256 _votingDuration) {<br>        i_owner = msg.sender;<br>        i_votingEnded = block.timestamp + _votingDuration;<br>    }</pre><p>The constructor sets the contract owner to the address that deploys the contract (msg.sender) and calculates when the voting period will end by adding the given duration to the current timestamp.</p><pre> modifier onlyOwner() {<br>        require(msg.sender == i_owner, Voting__onlyOwner());<br>        _;<br>    }<br><br>    modifier votingTime() {<br>        require(block.timestamp &lt; i_votingEnded, Voting__VotingEnded());<br>        _;<br>    }</pre><p><strong>Modifiers</strong>: These are reusable pieces of code that can be attached to functions.</p><ul><li>onlyOwner: Restricts certain actions to the contract owner.</li><li>votingTime: Ensures that certain actions (like voting) can only be done during the voting period.</li></ul><h4>Main Functions</h4><pre>   function addCandidate(string memory _name, string memory _partyName) public onlyOwner {<br>        candidates[candidateCount] = Candidate(_name, _partyName, 0);<br>        candidateCount++;<br>        emit CandidateAdded(_name, _partyName);<br>    }</pre><p><strong>addCandidate</strong>: Only the contract owner can add candidates, and each candidate has a name and party affiliation.</p><pre>    function vote(uint256 candidateIndex) public votingTime {<br>        require(!hasVoted[msg.sender], Voting__alreadyVoted());<br>        require(candidateIndex &lt; candidateCount, Voting__invalidCandidateIndex());<br><br>        hasVoted[msg.sender] = true;<br>        candidates[candidateIndex].voteCount += 1;<br>        totalVotes += 1;<br><br>        emit VoteCasted(msg.sender, candidateIndex);<br>    }</pre><p><strong>vote</strong>: This function allows users to vote for a candidate. It checks if the user has already voted and ensures the vote is cast within the voting period.</p><pre>    function getWinner() public view returns (string memory winnerName, string memory winnerParty, uint256 winnerVoteCount) {<br>        require(candidateCount &gt; 0, Voting__NoCandidateAvailable());<br>        <br>        uint256 winningVoteCount = 0;<br>        uint256 winningIndex = 0;<br><br>        for (uint256 i = 0; i &lt; candidateCount; i++) {<br>            if (candidates[i].voteCount &gt; winningVoteCount) {<br>                winningVoteCount = candidates[i].voteCount;<br>                winningIndex = i;<br>            }<br>        }<br>        Candidate memory winner = candidates[winningIndex];<br>        return (winner.name, winner.partyName, winner.voteCount);<br>    }</pre><p><strong>getWinner</strong>: This function returns the candidate with the highest vote count. It loops through all the candidates and compares their vote counts to find the winner.</p><h3>2. Deployment Script (DeplyVoting.s.sol)</h3><p>The deployment script helps automate the process of deploying the Voting contract onto a blockchain.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.20;<br><br>import {Script} from &quot;forge-std/Script.sol&quot;;<br>import {Voting} from &quot;../src/Voting.sol&quot;;<br><br>contract Deploy is Script {<br>    uint256 public constant VOTING_DAYS = 5 days;<br><br>    function run() external returns (Voting) {<br>        vm.startBroadcast();<br>        Voting voting = new Voting(VOTING_DAYS);<br>        vm.stopBroadcast();<br>        return voting;<br>    }<br>}</pre><p><strong>run</strong>: This is the core function that deploys the Voting contract. It sets the voting duration to 5 days, and calls vm.startBroadcast() to begin broadcasting transactions to the blockchain, followed by vm.stopBroadcast() when the deployment is done.</p><h3>3. Test File (TestVoting.t.sol)</h3><p>This file tests different functionalities of the Voting contract. Here&#39;s the code:</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.20;<br><br>import {Test, console} from &quot;forge-std/Test.sol&quot;;<br>import {Voting} from &quot;../src/Voting.sol&quot;;<br>import {Deploy} from &quot;../script/DeployVoting.s.sol&quot;;<br><br>contract testVote is Test {<br>    uint256 public constant votingDays = 5 days;<br><br>     Voting public voting;<br>     Deploy public deploy;<br><br>    function setUp() public {<br>        voting = new Voting(votingDays);<br>        deploy = new Deploy();<br><br>          voting.addCandidate(&quot;Obama&quot;, &quot;party1&quot;);<br>          voting.addCandidate(&quot;Trump&quot;, &quot;party2&quot;);<br>    }<br><br>    function test_addcandidate() public {<br>        voting.addCandidate(&quot;Kamela&quot;, &quot;party3&quot;);<br>        assertEq(voting.getCandidateCount(), 3);<br>    }<br><br>    function test_getCandidateIndex() public {<br>      (string memory name, string memory party, uint256 voteCount) = voting.getCanditateIndex(0);<br>      assertEq(name, &quot;Obama&quot;);<br>      assertEq(party, &quot;party1&quot;);<br>      assertEq(voteCount, 0);<br><br>    }<br><br>    function test_vote() public {<br>        vm.warp(block.timestamp + 4 days);<br>        voting.vote(0);<br>        vm.prank(address(0x1234));<br>        voting.vote(1);<br>        vm.prank(address(0x5678));<br>        voting.vote(0);<br>        assertEq(voting.getTotalVotes(), 3);<br>        assertEq(voting.getVotePerCandidate(1), 1);<br>        voting.getRemainingVotingTime();<br>        voting.getWinner();<br>    }<br><br>    function test_onlyOwnerAddCandidate() public {<br>    vm.prank(address(0x1234)); // Using address(0x1234) as a non-owner address<br>    vm.expectRevert(Voting.Voting__onlyOwner.selector);<br>    voting.addCandidate(&quot;NonOwnerCandidate&quot;, &quot;party4&quot;);<br>}<br><br>    function test_votingTime() public {<br>        vm.warp(block.timestamp + 10 days);<br>        vm.expectRevert(Voting.Voting__VotingEnded.selector);<br>        voting.vote(0);<br>    }<br><br>    function test_remainingTime() public {<br>        vm.warp(block.timestamp + 7 days);<br>        voting.getRemainingVotingTime();<br>        assertEq(voting.getRemainingVotingTime(), 0);<br>    }<br><br>     function test_getCandidateCount() public {<br>        voting.getCandidateCount();<br>        assertEq(voting.getCandidateCount(), 2);<br>    }<br><br>    <br>    function test_deployment() public {<br>        voting = deploy.run();<br>        <br>        // Check if the contract was deployed correctly<br>        assertTrue(address(voting) != address(0), &quot;Voting contract not deployed&quot;);<br><br>        // Validate the voting duration is set correctly with a tolerance<br>        uint256 votingDuration = voting.i_votingEnded();<br>        uint256 currentTime = block.timestamp;<br>        uint256 expectedVotingEnd = currentTime + 5 days;<br>        <br>        // Allow a tolerance of ±2 seconds<br>        assertTrue(votingDuration &gt;= expectedVotingEnd - 2 &amp;&amp; votingDuration &lt;= expectedVotingEnd + 2, &quot;Voting duration should be approximately 5 days&quot;);<br>    }<br><br>}</pre><p><strong>Here’s how it works:</strong></p><h4><strong>Imports</strong></h4><pre>import {Test} from &quot;forge-std/Test.sol&quot;;<br>import {Voting} from &quot;../src/Voting.sol&quot;;<br>import {Deploy} from &quot;../script/DeployVoting.s.sol&quot;;</pre><ul><li><strong>Test</strong>: This is a utility from Foundry that provides useful functions for writing tests.</li><li><strong>Voting</strong>: Imports your Voting contract to run tests against it.</li><li><strong>Deploy</strong>: Imports a script that handles deploying the contract during testing.</li></ul><h4>State Variables</h4><pre>uint256 public constant votingDays = 5 days;<br>Voting public voting;<br>Deploy public deploy;</pre><ul><li><strong>votingDays</strong>: The duration of the voting period (5 days) is defined here.</li><li><strong>voting</strong>: A variable that represents the instance of your Voting contract.</li><li><strong>deploy</strong>: An instance of the Deploy contract, used to deploy the Voting contract for testing.</li></ul><h4>setUp Function</h4><pre>function setUp() public {<br>    voting = new Voting(votingDays);<br>    deploy = new Deploy();<br><br>    voting.addCandidate(&quot;Obama&quot;, &quot;party1&quot;);<br>    voting.addCandidate(&quot;Trump&quot;, &quot;party2&quot;);<br>}</pre><ul><li><strong>setUp()</strong>: This function runs before each test. It sets up the environment by deploying the Voting contract and adding two initial candidates, &quot;Obama&quot; and &quot;Trump.&quot;</li><li>After this function is run, the tests can use the deployed contract with these candidates.</li></ul><h4>Test: test_addcandidate</h4><pre>function test_addcandidate() public {<br>    voting.addCandidate(&quot;Kamela&quot;, &quot;party3&quot;);<br>    assertEq(voting.getCandidateCount(), 3);<br>}</pre><p><strong>Purpose</strong>: This test checks if you can add a candidate to the Voting contract.</p><p><strong>Explanation</strong>: It adds a new candidate “Kamela” and then checks if the total number of candidates is now 3 (using assertEq, which checks if two values are equal).</p><ul><li><strong>assertEq</strong>: Confirms that the candidate count has been incremented after adding the candidate.</li></ul><h4>Test: test_getCandidateIndex</h4><pre>function test_getCandidateIndex() public {<br>    (string memory name, string memory party, uint256 voteCount) = voting.getCanditateIndex(0);<br>    assertEq(name, &quot;Obama&quot;);<br>    assertEq(party, &quot;party1&quot;);<br>    assertEq(voteCount, 0);<br>}</pre><p><strong>Purpose</strong>: This test ensures that you can fetch the details of a candidate.</p><p><strong>Explanation</strong>: It retrieves the candidate at index 0 (Obama) and checks that:</p><ul><li>The candidate’s name is “Obama.”</li><li>The party is “party1.”</li><li>The vote count is initially 0.</li><li><strong>assertEq</strong>: Confirms that the data returned from the contract matches the expected values.</li></ul><h4>Test: test_vote</h4><pre>function test_vote() public {<br>    vm.warp(block.timestamp + 4 days);<br>    voting.vote(0);<br>    vm.prank(address(0x1234));<br>    voting.vote(1);<br>    vm.prank(address(0x5678));<br>    voting.vote(0);<br>    assertEq(voting.getTotalVotes(), 3);<br>    assertEq(voting.getVotePerCandidate(1), 1);<br>    voting.getRemainingVotingTime();<br>    voting.getWinner();<br>}</pre><p><strong>Purpose</strong>: Tests the core voting functionality, ensuring votes are cast correctly and totals are updated.</p><p><strong>Steps</strong>:</p><p><strong>Advance Time</strong>: Uses vm.warp to move the blockchain&#39;s timestamp forward by 4 days, keeping it within the 5-day voting period.</p><p><strong>Cast Votes</strong>:</p><ul><li><strong>First Vote</strong>: Casts a vote for candidate 0 (“Obama”).</li><li><strong>Second Vote</strong>: Uses vm.prank to simulate a different user (0x1234) casting a vote for candidate 1 (&quot;Trump&quot;).</li><li><strong>Third Vote</strong>: Simulates another user (0x5678) casting another vote for candidate 0 (&quot;Obama&quot;).</li></ul><p><strong>Assert Vote Totals</strong>:</p><ul><li><strong>Total Votes</strong>: Checks if the total votes are now 3.</li><li><strong>Candidate Votes</strong>: Ensures candidate 1 (“Trump”) has exactly 1 vote.</li></ul><p><strong>Additional Function Calls</strong>:</p><ul><li>Calls getRemainingVotingTime() and getWinner() to ensure these functions execute without issues after voting.</li></ul><p><strong>Explanation</strong>:</p><ul><li><strong>vm.warp</strong>: Simulates the passage of time, essential for testing time-dependent functionalities.</li><li><strong>vm.prank</strong>: Mocks different users interacting with the contract, testing multi-user scenarios.</li><li><strong>Assertions</strong>: Confirms that voting increments the correct counters and that vote counts are accurate.</li></ul><h4>Test: test_onlyOwnerAddCandidate</h4><pre>function test_onlyOwnerAddCandidate() public {<br>    vm.prank(address(0x1234)); // Simulate a non-owner address<br>    vm.expectRevert(Voting.Voting__onlyOwner.selector);<br>    voting.addCandidate(&quot;NonOwnerCandidate&quot;, &quot;party4&quot;);<br>}</pre><p><strong>Purpose</strong>: Ensures that only the contract owner can add new candidates.</p><p><strong>Steps</strong>:</p><ul><li><strong>Simulate Non-Owner</strong>: Uses vm.prank to change the msg.sender to 0x1234, a non-owner address.</li><li><strong>Expect Revert</strong>: Sets up an expectation that the next operation will revert with the Voting__onlyOwner error.</li><li><strong>Attempt to Add Candidate</strong>: Tries to add a candidate “NonOwnerCandidate” from “party4”.</li></ul><p><strong>Explanation</strong>:</p><ul><li><strong>Security Check</strong>: Verifies that the onlyOwner modifier correctly restricts access to the addCandidate function.</li><li><strong>Reversion</strong>: The test expects the transaction to fail, ensuring unauthorized users cannot modify the contract state.</li></ul><h4>Test: test_votingTime</h4><pre>function test_votingTime() public {<br>    vm.warp(block.timestamp + 10 days);<br>    vm.expectRevert(Voting.Voting__VotingEnded.selector);<br>    voting.vote(0);<br>}</pre><p><strong>Purpose</strong>: Tests if voting fails after the voting period ends.</p><p><strong>Explanation</strong>:</p><ul><li><strong>vm.warp(block.timestamp + 10 days)</strong>: Fast-forwards time by 10 days, past the 5-day voting period.</li><li><strong>vm.expectRevert(Voting.Voting__VotingEnded.selector)</strong>: Checks that voting now reverts with the Voting__VotingEnded error because the voting period has ended.</li></ul><h4>Test: test_remainingTime</h4><pre>function test_remainingTime() public {<br>    vm.warp(block.timestamp + 7 days);<br>    voting.getRemainingVotingTime();<br>    assertEq(voting.getRemainingVotingTime(), 0);<br>}</pre><p><strong>Purpose</strong>: Tests if the getRemainingVotingTime() function works after the voting period has ended.</p><p><strong>Explanation</strong>:</p><ul><li>It fast-forwards time by 7 days (past the 5-day voting period) and calls getRemainingVotingTime().</li><li>The function should return the remaining voting time correctly, even after the voting period has ended.</li></ul><h4><strong>Test: </strong><strong>test_getCandidateCount</strong></h4><pre>function test_getCandidateCount() public {<br>    voting.getCandidateCount();<br>    assertEq(voting.getCandidateCount(), 2);<br>}</pre><p><strong>Purpose</strong>: This simple test checks if the getCandidateCount() function works correctly.</p><p><strong>Explanation</strong>: The function retrieves the total number of candidates from the contract. In this case, it should return the correct count.</p><h4>Test: test_deployment</h4><pre>function test_deployment() public {<br>    voting = deploy.run();<br>    <br>    assertTrue(address(voting) != address(0), &quot;Voting contract not deployed&quot;);<br><br>    uint256 votingDuration = voting.i_votingEnded();<br>    uint256 currentTime = block.timestamp;<br>    uint256 expectedVotingEnd = currentTime + 5 days;<br>    <br>    assertTrue(votingDuration &gt;= expectedVotingEnd - 2 &amp;&amp; votingDuration &lt;= expectedVotingEnd + 2, &quot;Voting duration should be approximately 5 days&quot;);<br>}</pre><p><strong>Purpose</strong>: Tests the deployment of the Voting contract.</p><p><strong>Explanation</strong>:</p><ul><li><strong>deploy.run()</strong>: Runs the Deploy script to deploy the Voting contract.</li><li><strong>assertTrue(address(voting) != address(0))</strong>: Ensures that the Voting contract was deployed correctly (i.e., its address is not zero).</li></ul><p><strong>Checks the voting duration</strong>:</p><ul><li>It retrieves the voting end time (i_votingEnded).</li><li>Compares it with the current time plus 5 days, allowing a tolerance of ±2 seconds due to slight variations during deployment.</li></ul><h3>4. Test Coverage Results</h3><p>After running the tests, I achieved the following coverage for the Voting contract:</p><pre>Ran 8 tests for test/TestVoting.t.sol:testVote<br>[PASS] test_addcandidate() (gas: 68113)<br>[PASS] test_deployment() (gas: 1075011)<br>[PASS] test_getCandidateCount() (gas: 7882)<br>[PASS] test_getCandidateIndex() (gas: 24645)<br>[PASS] test_onlyOwnerAddCandidate() (gas: 11054)<br>[PASS] test_remainingTime() (gas: 8995)<br>[PASS] test_vote() (gas: 171898)<br>[PASS] test_votingTime() (gas: 9684)<br>Suite result: ok. 8 passed; 0 failed; 0 skipped; finished in 77.80ms (46.80ms CPU time)<br><br>Ran 1 test suite in 80.52ms (77.80ms CPU time): 8 tests passed, 0 failed, 0 skipped (8 total tests)<br>| File                      | % Lines         | % Statements    | % Branches     | % Funcs         |<br>|---------------------------|-----------------|-----------------|----------------|-----------------|<br>| script/DeployVoting.s.sol | 100.00% (4/4)   | 100.00% (5/5)   | 100.00% (0/0)  | 100.00% (1/1)   |<br>| src/Voting.sol            | 100.00% (31/31) | 100.00% (33/33) | 71.43% (10/14) | 100.00% (11/11) |<br>| Total                     | 100.00% (35/35) | 100.00% (38/38) | 71.43% (10/14) | 100.00% (12/12) |</pre><p><strong>Summary:</strong></p><ul><li><strong>100% Line Coverage</strong>: All lines of code in both DeployVoting.s.sol and Voting.sol were executed during the tests.</li><li><strong>100% Statement Coverage</strong>: All statements in both files were successfully covered.</li><li><strong>71.43% Branch Coverage</strong>: Some conditional branches in the Voting.sol contract were not fully tested so I’m going to work more on this.</li><li><strong>100% Function Coverage</strong>: Every function in the contracts was executed during testing.</li></ul><h3>Additional Resources</h3><ul><li><strong>Foundry Documentation</strong>: <a href="https://book.getfoundry.sh/">https://book.getfoundry.sh/</a></li><li><strong>Solidity Documentation</strong>: <a href="https://docs.soliditylang.org/">https://docs.soliditylang.org/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d8d6de29e8b" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/a-simple-voting-system-creating-testing-and-deploying-using-foundry-0d8d6de29e8b">A Simple Voting System: Creating, Testing and Deploying using Foundry</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DeFi concepts for beginners: Mint, Burn, Liquidate, and more [with code snippets]]]></title>
            <link>https://medium.com/cryptocurrency-scripts/defi-concepts-for-beginners-mint-burn-liquidate-and-more-with-code-snippets-f2c6d48ab3de?source=rss-cb00521e466f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2c6d48ab3de</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[solidity-tutorial]]></category>
            <dc:creator><![CDATA[molaratai]]></dc:creator>
            <pubDate>Fri, 13 Sep 2024 15:53:06 GMT</pubDate>
            <atom:updated>2024-09-14T07:35:15.491Z</atom:updated>
            <content:encoded><![CDATA[<p>Minting, burning, liquidating, and using OpenZeppelin for added security and control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nAiIEdMIPgn1242D" /><figcaption>Photo by <a href="https://unsplash.com/@theshubhamdhage?utm_source=medium&amp;utm_medium=referral">Shubham Dhage</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Decentralized Finance (DeFi) is revolutionizing the way we think about financial systems, allowing anyone to participate in lending, borrowing, and trading without needing a bank.</p><p>DeFi smart contracts make this possible, but for many newcomers, the technical terminology can feel like a different language — at least, that’s how it felt for me at first!</p><p>If you’ve been curious about building DeFi smart contracts or simply want to understand how these systems work, this article is for you.</p><p>We’ll break down key concepts like <strong>minting</strong>, <strong>burning</strong>, <strong>liquidation</strong>, and <strong>thresholds</strong> in a way that’s easy to understand — even if you’re completely new to DeFi or programming.</p><h3>Key DeFi concepts :</h3><p>1. <strong>Mint</strong>: Think of minting like creating new money. In DeFi, minting refers to generating new tokens or assets in a smart contract.</p><p>For example, if a protocol needs more tokens for rewards or users, it mints them to increase the supply.</p><p><strong>2. Burn</strong>: Burning is the opposite of minting. It’s like taking money out of circulation by destroying it.</p><p>When tokens are burned, they’re sent to an address where they can never be used again.</p><p>This reduces the total supply of tokens, which can sometimes increase the value of the remaining ones.</p><p><strong>3. Liquidate</strong>: Liquidation happens when a borrower can’t repay their loan or the collateral they provided isn’t enough to cover the loan anymore (due to price drops, for instance).</p><p>When this happens, the borrower’s collateral is sold (or “liquidated”) to pay back the loan. It helps keep the lending protocol balanced.</p><p><strong>4. Threshold</strong>: A threshold is a limit or value that triggers an action.</p><p>For example, in lending protocols, if the value of your collateral drops below a certain threshold, it might trigger liquidation.</p><p>Thresholds are set to ensure the system stays safe and stable.</p><p><strong>5. Collateral</strong>: In DeFi, collateral is something you put down as security when borrowing assets.</p><p>It’s like a house you use as collateral for a loan.</p><p>If the value of your collateral drops too much, it might get liquidated (sold off).</p><p><strong>6. Staking</strong>: Staking involves locking up your tokens in a protocol to support its operations, like validating transactions.</p><p>In return, you earn rewards, often in the form of more tokens.</p><p><strong>7. Yield Farming</strong>: This is like putting your money to work in different DeFi protocols to earn returns.</p><p>You provide liquidity or stake tokens and, in return, earn interest or rewards.</p><p><strong>8. Liquidity Pool</strong>: A pool of tokens locked in a smart contract that traders can use to swap between different tokens.</p><p>People who contribute to liquidity pools earn fees or rewards for helping the system.</p><p><strong>9. Slippage</strong>: This is the difference between the expected price of a trade and the actual price you get due to market fluctuations.</p><p>It can happen if a trade is too large or if the market is moving quickly.</p><p>Let’s explore some real-life scenarios to help make these concepts more tangible:</p><h3>Mint</h3><p><strong>Scenario</strong>: Imagine a DeFi project like a video game rewards system.</p><ul><li>You’re playing a game where every time you complete a mission, you earn tokens (like game points).</li><li>The DeFi project “mints” new tokens every time someone finishes a mission. This increases the supply of the in-game tokens.</li><li>For example, if 100 players finish a mission and each earns 10 tokens, 1,000 new tokens are minted and added to the game economy.</li></ul><pre>contract GameToken {<br>    uint256 public totalSupply;<br>    mapping(address =&gt; uint256) public balances;<br><br>    function mint(address _to, uint256 _amount) public {<br>        totalSupply += _amount;<br>        balances[_to] += _amount;<br>    }<br>}</pre><p>This <strong><em>mint</em></strong> function adds new tokens to the total supply and assigns them to the user’s balance.</p><h3>Burn</h3><p><strong>Scenario</strong>: Let’s say a DeFi project has too many tokens in circulation, and they want to reduce supply to make each token more valuable (like destroying old coins).</p><ul><li>Users voluntarily send their tokens to a special “burn address,” and these tokens are removed from the supply.</li><li>For example, you decide to burn 50 tokens you earned. Once burned, they’re no longer usable.</li></ul><pre>contract BurnableToken {<br>    uint256 public totalSupply;<br>    mapping(address =&gt; uint256) public balances;<br><br>    function burn(uint256 _amount) public {<br>        require(balances[msg.sender] &gt;= _amount, &quot;Not enough tokens&quot;);<br>        totalSupply -= _amount;<br>        balances[msg.sender] -= _amount;<br>    }<br>}</pre><p>This function reduces the total supply and the user’s balance, effectively destroying tokens.</p><h3>Liquidation</h3><p><strong>Scenario</strong>: You take out a loan on a DeFi platform like Aave by putting down collateral (e.g., ETH).</p><ul><li>Let’s say you borrow $100 worth of stablecoins, and you put up $150 worth of ETH as collateral.</li><li>If the price of ETH drops and your $150 collateral becomes worth only $90, the platform will liquidate your collateral to cover your loan, since it’s now too risky for the lender.</li></ul><pre>contract LendingPlatform {<br>    mapping(address =&gt; uint256) public collateral;<br>    mapping(address =&gt; uint256) public debt;<br>    uint256 public liquidationThreshold = 110;  // 110%<br><br>    function liquidate(address _borrower) public {<br>        uint256 collateralValue = collateral[_borrower];<br>        uint256 debtValue = debt[_borrower];<br>        require(collateralValue * 100 / debtValue &lt; liquidationThreshold, &quot;Collateral still safe&quot;);<br><br>        // Liquidate the collateral<br>        debt[_borrower] = 0;<br>        collateral[_borrower] = 0;<br>    }<br>}</pre><p>If the borrower’s collateral falls below the threshold, the <strong><em>liquidate</em></strong> function is triggered, selling off the collateral to repay the loan.</p><h3>Threshold</h3><p><strong>Scenario</strong>: You stake tokens in a DeFi platform, and it pays rewards as long as your stake is above a certain threshold (like a bank requiring a minimum balance).</p><ul><li>If your balance falls below a threshold, you no longer earn rewards, or in a loan situation, you may face liquidation.</li></ul><pre>contract StakingRewards {<br>    uint256 public rewardThreshold = 1000;  // Minimum tokens required to earn rewards<br>    mapping(address =&gt; uint256) public staked;<br><br>    function checkRewardsEligibility(address _user) public view returns (bool) {<br>        return staked[_user] &gt;= rewardThreshold;<br>    }<br>}</pre><p>In this case, the threshold determines whether users qualify for rewards.</p><h3>Yield Farming</h3><p><strong>Scenario</strong>: You deposit two types of tokens (ETH and a stablecoin like USDC) into a liquidity pool on a decentralized exchange like Uniswap.</p><p>In return, you receive rewards based on how much liquidity you provide.</p><ul><li>The more liquidity you provide, the more rewards (yield) you farm over time.</li></ul><pre>contract LiquidityPool {<br>    mapping(address =&gt; uint256) public liquidity;<br>    mapping(address =&gt; uint256) public rewards;<br><br>    function provideLiquidity(uint256 _amount) public {<br>        liquidity[msg.sender] += _amount;<br>        // Rewards calculation<br>        rewards[msg.sender] += calculateYield(_amount);<br>    }<br><br>    function calculateYield(uint256 _amount) internal pure returns (uint256) {<br>        // Simplified reward logic<br>        return _amount / 10;  // Example: 10% reward<br>    }<br>}</pre><blockquote><strong>Why These Concepts Matter</strong></blockquote><blockquote>As you begin your journey into building DeFi smart contracts, having a solid grasp of these concepts is critical.</blockquote><blockquote>Not only will you be able to design better, more secure systems, but you’ll also understand the economic mechanics that drive the DeFi ecosystem.</blockquote><blockquote>In the examples provided, we’ve walked through practical code snippets that show how minting, burning, and liquidation can be implemented.</blockquote><blockquote>These concepts will serve as the foundation for more advanced DeFi mechanisms you may encounter or build in the future.</blockquote><h3>Leveraging External Libraries Like OpenZeppelin for DeFi Contracts</h3><p>Now that we’ve covered the basics, let’s talk about something that can make your life much easier when building DeFi contracts: using external libraries like OpenZeppelin.</p><p><strong>OpenZeppelin</strong> is a popular open-source library of secure and audited smart contract code.</p><p>It provides reusable components for common tasks in Solidity, like token creation (ERC-20 or ERC-721), access control, and upgrades.</p><p>By using OpenZeppelin, you can avoid reinventing the wheel and ensure that your contracts are built on solid, secure foundations.</p><h4>Why Use OpenZeppelin?</h4><ul><li><strong>Security</strong>: OpenZeppelin contracts are thoroughly tested and audited, which reduces the risk of vulnerabilities in your code.</li><li><strong>Efficiency</strong>: You don’t have to spend time writing code for basic tasks, like token minting or role management, as they are already provided.</li><li><strong>Best Practices</strong>: The library follows best coding practices, ensuring your contracts are up to industry standards.</li></ul><p>By leveraging OpenZeppelin’s libraries, you can focus on the unique aspects of your DeFi protocol without worrying about the boilerplate code, allowing you to write cleaner, safer, and more efficient smart contracts.</p><p>Let’s dive deeper into how OpenZeppelin can be integrated into different aspects of DeFi contracts, making your development process smoother, more secure, and scalable.</p><h3>1. Token Standards (ERC-20 &amp; ERC-721)</h3><p>The most common use of OpenZeppelin in DeFi is through <strong>ERC-20</strong> (fungible tokens) and <strong>ERC-721</strong> (non-fungible tokens or NFTs) standards.</p><p>These contracts provide the core structure for creating tokens that follow Ethereum’s widely adopted standards.</p><p>Instead of writing the entire token logic from scratch, you can inherit from OpenZeppelin’s implementation and add your custom functionality as needed.</p><h4>Example: ERC-20 Token with Minting and Burning</h4><p>You can easily create a DeFi token with minting and burning features using OpenZeppelin’s <strong>ERC20</strong> contract:</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>import { ERC20, Ownable } from &quot;@openzeppelin/contracts/token/ERC20/ERC20.sol&quot;;<br><br>contract MyDeFiToken is ERC20, Ownable {<br>    constructor() ERC20(&quot;MyDeFiToken&quot;, &quot;MDT&quot;) {}<br><br>    function mint(address to, uint256 amount) public onlyOwner {<br>        _mint(to, amount);<br>    }<br><br>    function burn(uint256 amount) public {<br>        _burn(msg.sender, amount);<br>    }<br>}</pre><p>Here, OpenZeppelin’s <strong>ERC20</strong> contract provides the necessary token functionality, while <strong>Ownable</strong> restricts the minting privilege to the contract owner. The <strong>_burn</strong> function allows users to destroy tokens, decreasing the supply.</p><h3>2. Access Control with Ownable and Role-based Access</h3><p>DeFi contracts often need strict control over who can perform specific actions (like minting or pausing a contract). OpenZeppelin’s <strong>Ownable</strong> and <strong>AccessControl</strong> contracts make implementing access control much easier.</p><h4>Ownable</h4><p>This contract restricts certain functions to the contract owner, which is useful for functions like minting or upgrading the contract.</p><pre>import { Ownable } from &quot;@openzeppelin/contracts/access/Ownable.sol&quot;;<br><br>// Your contract can inherit Ownable<br>contract MyContract is Ownable {<br>    function restrictedAction() public onlyOwner {<br>        // Only the owner can perform this action<br>    }<br>}</pre><h4>AccessControl</h4><p>For more fine-grained control, where different roles have different privileges, OpenZeppelin’s <strong>AccessControl</strong> comes in handy. You can assign roles (e.g., a “MINTER” role or “PAUSER” role) to specific addresses.</p><pre>import  { AccessControl } from &quot;@openzeppelin/contracts/access/AccessControl.sol&quot;;<br><br>contract MyDeFiContract is AccessControl {<br>    bytes32 public constant MINTER_ROLE = keccak256(&quot;MINTER_ROLE&quot;);<br><br>    constructor() {<br>        _setupRole(DEFAULT_ADMIN_ROLE, msg.sender);<br>        _setupRole(MINTER_ROLE, msg.sender);<br>    }<br><br>    function mint(address to, uint256 amount) public {<br>        require(hasRole(MINTER_ROLE, msg.sender), &quot;Caller is not a minter&quot;);<br>        // Mint tokens<br>    }<br>}</pre><p>With <strong>AccessControl</strong>, you can create multiple roles, assign them to users, and manage permissions for each role.</p><h3>3. Pausable Contracts</h3><p>Many DeFi protocols include a safety mechanism called <strong>pausing</strong>, which allows the contract owner or a privileged user to stop certain functions during an emergency, such as if a vulnerability is detected.</p><p>OpenZeppelin’s <strong>Pausable</strong> contract makes this easy to implement. By inheriting from <strong>Pausable</strong>, you can pause specific functions like token transfers, staking, or borrowing.</p><p><strong>Example: Pausing Token Transfers</strong></p><pre><br>import { Pausable } from &quot;@openzeppelin/contracts/security/Pausable.sol&quot;;<br>import { ERC20 } from &quot;@openzeppelin/contracts/token/ERC20/ERC20.sol&quot;;<br>import { Ownable } from &quot;@openzeppelin/contracts/access/Ownable.sol&quot;;<br><br>contract MyDeFiToken is ERC20, Ownable, Pausable {<br>    constructor() ERC20(&quot;MyDeFiToken&quot;, &quot;MDT&quot;) {}<br><br>    function pause() public onlyOwner {<br>        _pause();<br>    }<br><br>    function unpause() public onlyOwner {<br>        _unpause();<br>    }<br><br>    function _beforeTokenTransfer(address from, address to, uint256 amount) internal override whenNotPaused {<br>        super._beforeTokenTransfer(from, to, amount);<br>    }<br>}</pre><p>In this example, token transfers are paused when the<strong><em> pause</em></strong> function is called. The contract owner can pause and unpause the contract, providing an extra layer of security in case something goes wrong.</p><h3>4. Security: Reentrancy Guards and SafeMath</h3><p>Security is paramount in DeFi, where millions (or even billions) of dollars are at stake. OpenZeppelin offers useful security tools such as <strong>ReentrancyGuard</strong> and <strong>SafeMath</strong> to prevent common vulnerabilities.</p><p><strong>ReentrancyGuard</strong>: Prevents reentrancy attacks, where an attacker might exploit a contract by repeatedly calling a function before previous executions are finished.</p><pre>import { ReentrancyGuard } from &quot;@openzeppelin/contracts/security/ReentrancyGuard.sol&quot;;<br><br>contract MyDeFiContract is ReentrancyGuard {<br>    function withdraw() public nonReentrant {<br>        // Withdrawal logic<br>    }<br>}</pre><p><strong>SafeMath</strong>: Before Solidity 0.8, arithmetic operations could overflow or underflow. OpenZeppelin’s <strong>SafeMath</strong> library prevents this by checking for overflow and underflow conditions.</p><pre>import { SafeMath } from &quot;@openzeppelin/contracts/utils/math/SafeMath.sol&quot;;<br><br>contract MyDeFiContract {<br>    using SafeMath for uint256;<br><br>    function calculate(uint256 a, uint256 b) public pure returns (uint256) {<br>        return a.add(b);<br>    }<br>}</pre><p>While Solidity 0.8+ has built-in overflow checks, <strong>SafeMath</strong> remains useful for projects using earlier Solidity versions.</p><h3>OpenZeppelin Makes DeFi Development Safer and Faster</h3><p>By leveraging OpenZeppelin’s contracts and libraries, you can build DeFi protocols that are secure, scalable, and efficient.</p><p>Whether you’re managing tokens, controlling access, or building upgradeable systems, OpenZeppelin provides well-audited, easy-to-use components that save you time and reduce risk.</p><p>Next time you’re building a DeFi project, take advantage of OpenZeppelin to focus on what really matters — your unique application logic — while relying on trusted tools for the core building blocks.</p><p>Ready to start writing your own DeFi smart contracts?</p><p>Stay tuned for more detailed guides on coding strategies, security practices, and advanced DeFi features!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2c6d48ab3de" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cryptocurrency-scripts/defi-concepts-for-beginners-mint-burn-liquidate-and-more-with-code-snippets-f2c6d48ab3de">DeFi concepts for beginners: Mint, Burn, Liquidate, and more [with code snippets]</a> was originally published in <a href="https://medium.com/cryptocurrency-scripts">Cryptocurrency Scripts</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why smart contract developers should choose VSCode and Foundry over Remix IDE]]></title>
            <link>https://coinsbench.com/why-smart-contract-developers-should-choose-vscode-and-foundry-over-remix-ide-e4d47e87cc44?source=rss-cb00521e466f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4d47e87cc44</guid>
            <category><![CDATA[blockchain-development]]></category>
            <category><![CDATA[remix-ide]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[molaratai]]></dc:creator>
            <pubDate>Fri, 06 Sep 2024 16:27:04 GMT</pubDate>
            <atom:updated>2024-09-11T13:39:08.394Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_SAdatSayvZ8owtf" /><figcaption>Photo by <a href="https://unsplash.com/@karishea?utm_source=medium&amp;utm_medium=referral">Kari Shea</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When getting started with smart contract development, many developers find themselves using <strong>Remix IDE</strong>, a browser-based tool designed for quick prototyping and learning the basics.</p><p>While Remix is perfect for small projects and beginners, it has its limitations as your development grows more complex.</p><p>This is where a dedicated development environment like <strong>VSCode</strong> and <strong>Foundry</strong> becomes invaluable.</p><p>Let’s explore why smart contract developers should consider transitioning from Remix IDE to more powerful tools like VSCode and Foundry.</p><h4>1. Advanced Features and Customization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uuIpilXKWrmPscmr" /><figcaption>Photo by <a href="https://unsplash.com/@afgprogrammer?utm_source=medium&amp;utm_medium=referral">Mohammad Rahmani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>VSCode offers a rich array of features that enhance the coding experience, making it easier to write and maintain code.</p><p><strong>Syntax highlighting</strong>, <strong>auto-completion</strong>, and <strong>linting</strong> help you spot and fix errors early.</p><p>Moreover, VSCode allows you to customize your setup by installing extensions tailored for Solidity development, such as Solhint for linting, Solidity support, and others that simplify writing, debugging, and deploying contracts.</p><p>In contrast, Remix IDE lacks many of these advanced features and customization options, limiting its scalability and efficiency for professional developers.</p><h4>2. Git and Version Control Integration</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zO_sMNMZt9WcnyfQ" /><figcaption>Photo by <a href="https://unsplash.com/@synkevych?utm_source=medium&amp;utm_medium=referral">Roman Synkevych</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>One major advantage of VSCode is its built-in <strong>Git integration</strong>.</p><p>Smart contract projects often involve frequent changes and require proper version control.</p><p>With VSCode, managing Git repositories becomes seamless. You can easily track code changes, manage branches, and collaborate with other developers on projects.</p><p>Foundry also integrates with Git, allowing you to organize your project history and version control in a structured way.</p><p>Remix, on the other hand, doesn’t offer native Git integration.</p><p>While you can manually export and manage files, it doesn’t provide the robust, efficient version control that’s necessary for team-based or large-scale projects.</p><h4>3. Local Development with Foundry</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vTeJFJJrpRQpMHCY" /><figcaption>Photo by <a href="https://unsplash.com/@jeshoots?utm_source=medium&amp;utm_medium=referral">JESHOOTS.COM</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>While Remix IDE runs in a browser, a local development environment like Foundry gives you complete control over your development setup.</p><p>Foundry enables you to <strong>build, test, and deploy smart contracts locally</strong>.</p><p>You can create scripts for automating deployments, run tests more efficiently, and experiment without worrying about network issues or browser limitations.</p><p>By working locally with VSCode and Foundry, developers gain the flexibility to run <strong>unit tests</strong>, <strong>fuzz tests</strong>, and manage dependencies.</p><p>This ensures your code behaves as expected in different scenarios and reduces the chance of bugs going unnoticed.</p><h4>4. Scalability for Larger Projects</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iKgRzk_3evJrm6YV" /><figcaption>Photo by <a href="https://unsplash.com/@jramos10?utm_source=medium&amp;utm_medium=referral">Josue Isai Ramos Figueroa</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As your smart contract projects grow, you’ll need a development environment that can handle more complex structures.</p><p>VSCode is built to manage large projects with multiple files, dependencies, and complex folder hierarchies.</p><p>Tools like <strong>Hardhat</strong> or <strong>Foundry</strong> work seamlessly with VSCode, allowing you to manage your entire project efficiently.</p><p>Remix is great for small projects and prototyping but starts to become cumbersome when dealing with large codebases or complex contract systems.</p><p>VSCode and Foundry provide the structure and tooling required for scaling smart contract development.</p><h4>5. Better Team Collaboration</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2oIhJacQhN6u4eix" /><figcaption>Photo by <a href="https://unsplash.com/@brookecagle?utm_source=medium&amp;utm_medium=referral">Brooke Cagle</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>For larger teams, collaboration is key.</p><p>VSCode integrates seamlessly with collaboration tools like GitHub, making it easy for multiple developers to work on the same codebase, track changes, and resolve conflicts.</p><p>This is essential for larger projects where many developers are contributing code at the same time.</p><p>Foundry’s CLI tools also make collaboration more efficient, providing easy access to project dependencies and testing tools.</p><p>Remix, being browser-based, doesn’t offer the same level of collaboration support, making it less suited for team projects.</p><h4>6. Extensibility and Testing with Foundry</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mfc18Ld6fW2O_h-f" /><figcaption>Photo by <a href="https://unsplash.com/@jeswinthomas?utm_source=medium&amp;utm_medium=referral">Jeswin Thomas</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>One of the standout features of Foundry is its <strong>testing framework</strong>. Foundry allows developers to write automated tests, including unit tests and integration tests, all from the command line.</p><p>It also supports advanced features like fuzz testing, which allows you to simulate unexpected inputs and scenarios, ensuring your contracts are robust.</p><p>This is particularly important for smart contracts, where even small bugs can lead to severe consequences.</p><p>While Remix does provide basic testing functionality, it doesn’t offer the same depth of testing capabilities or flexibility that Foundry does.</p><p>Although Remix IDE is a great tool for beginners and quick prototyping, smart contract developers will greatly benefit from using a full-fledged development environment like <strong>VSCode</strong> and <strong>Foundry</strong>.</p><p>The advanced features, local development capabilities, version control integration, and scalability make them the perfect tools for managing larger, more complex smart contract projects.</p><p>By transitioning to these tools, you’ll not only enhance your development workflow but also ensure your code is maintainable, scalable, and secure.</p><p>If you’re looking to install VSCode and Foundry, check out my guide on how to set them up <a href="https://medium.com/@molaratai/a-quick-guide-on-installing-foundry-vscode-git-npm-and-node-js-c7b648804d16">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4d47e87cc44" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/why-smart-contract-developers-should-choose-vscode-and-foundry-over-remix-ide-e4d47e87cc44">Why smart contract developers should choose VSCode and Foundry over Remix IDE</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A quick guide on installing foundry, vscode, git, npm and node.js]]></title>
            <link>https://coinsbench.com/a-quick-guide-on-installing-foundry-vscode-git-npm-and-node-js-c7b648804d16?source=rss-cb00521e466f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7b648804d16</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[smart-contract-blockchain]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[molaratai]]></dc:creator>
            <pubDate>Fri, 06 Sep 2024 16:00:52 GMT</pubDate>
            <atom:updated>2024-09-11T13:39:09.840Z</atom:updated>
            <content:encoded><![CDATA[<p>A guide on essential tools needed to build your smart contract development environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XeQYlcinvC1MJu59" /><figcaption>Photo by <a href="https://unsplash.com/@scdisilviabrazzoduro?utm_source=medium&amp;utm_medium=referral">Silvia Brazzoduro</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Getting started with smart contract development can feel overwhelming, especially when it comes to setting up your environment.</p><p>If you’re anything like I was, sticking to Remix IDE at the beginning, you might be wondering why you even need to switch things up.</p><p>I’ve got an article that explains why, which you can check out <a href="https://medium.com/@molaratai/why-smart-contract-developers-should-choose-vscode-and-foundry-over-remix-ide-e4d47e87cc44">here</a>.</p><p>But no worries — I’ll walk you through the whole setup process step by step using the command line, making it super easy to follow along!</p><h3>Table of Contents</h3><ol><li>Install VSCode</li><li>Install Git</li><li>Install Node.js and npm</li><li>Install Foundry</li><li>Verify Installations</li><li>Configure git and github</li><li>VSCode extentions</li></ol><h3>Installing VSCode</h3><p>Why use VSCode?</p><p>It’s a free and popular code editor that simplifies writing code with features like syntax highlighting, auto-completion, and linting, which help spot and fix errors quickly.</p><p>It also integrates seamlessly with Git, making version control and code management easier.</p><p>Now, let’s get you set up with VSCode based on your operating system.</p><h4>For Linux Users</h4><ol><li><strong>Download VSCode</strong><br>Open your terminal and run this command to download VSCode:</li></ol><pre>wget -O code-latest.deb &#39;https://code.visualstudio.com/sha/download?build=stable&amp;os=linux-deb-x64&#39;</pre><p><strong>2. Install VSCode</strong><br>Install the downloaded file by running:</p><pre>sudo apt install ./code-latest.deb</pre><blockquote>You’ll be asked to enter your password. Note: Your password won’t show as you type — it’s hidden for security.</blockquote><p><strong>3. Delete the installer file</strong><br>To clean up, delete the installer:</p><pre>rm code-latest.deb</pre><p><strong>Open VSCode</strong></p><ul><li>From the Applications menu, or</li><li>Type<strong><em> code</em></strong> in the terminal.</li></ul><h4>For macOS Users</h4><ol><li><strong>Download VSCode</strong><br>Download the latest VSCode installer (.zip) from this link:<br><a href="https://code.visualstudio.com/sha/download?build=stable&amp;os=darwin-universal">VSCode for macOS</a></li></ol><p><strong>2. Install VSCode</strong></p><ul><li>Open your Downloads folder.</li><li>Double-click the <strong>VSCode-darwin-universal.zip</strong> file.</li><li>Drag the <strong>Visual Studio Code.app</strong> into your <strong>Applications</strong> folder.</li></ul><p><strong>3. Delete the installer file</strong></p><ul><li>Open <strong>Finder</strong>.</li><li>Go to <strong>Downloads</strong> and move the <strong><em>.zip</em></strong> file to the trash.</li></ul><p><strong>4. Open VSCode</strong></p><ul><li>Go to <strong>Applications</strong>, then double-click <strong>Visual Studio Code</strong>.</li></ul><h3>Install Git</h3><p>Git is essential for version control and collaborating on smart contracts.</p><h4>For Linux Users</h4><p>Update system:</p><pre>sudo apt update<br>sudo apt upgrade</pre><p>Install Git:</p><pre>sudo apt install git</pre><h4>For <strong>MacOS Users</strong></h4><p>Install homebrew if you don’t already have it installed.</p><p>If you do move to the git update instead.</p><p>Install Homebrew:</p><pre>/bin/bash -c &quot;$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)&quot;</pre><p>Update Git:</p><pre>brew install git</pre><h3>Install Node.js and npm</h3><p>Node.js and npm (Node Package Manager) are necessary for many blockchain tools and packages.</p><h4>For Linux Users:</h4><pre>sudo apt update<br>sudo apt install nodejs npm</pre><h4>For <strong>MacOS Users </strong>(using Homebrew):</h4><pre>brew install node</pre><h3>Install Foundry</h3><p><em>Foundry</em> is a fast, portable, and modular toolkit for Ethereum application development.</p><p>It allows you to compile, deploy, test, and debug smart contracts.</p><h4>Command for Installation:</h4><p>For all systems:</p><pre>curl -L https://foundry.paradigm.xyz | bash</pre><p>Then, install Foundry’s dependencies and tools:</p><pre>foundryup</pre><h3>Verify Installations</h3><p>Let’s make sure everything is installed properly:</p><p>To check<strong> VSCode:</strong></p><pre>code --version</pre><p>To check <strong>Git</strong>:</p><pre>git --version</pre><p>To check <strong>Node.js</strong> and <strong>npm</strong>:</p><pre>node -v<br>npm -v</pre><p>To check <strong>Foundry</strong>:</p><pre>forge --version</pre><h3>Configure Git and GitHub</h3><p>When you commit changes to a Git repository, Git attaches your name and email to each commit.</p><p>This information is used to identify who made the changes, both for your local projects and when collaborating with others.</p><p>Setting the correct username and email ensures that your contributions are properly attributed.</p><h4>Step 1: Create a GitHub Account</h4><ol><li>Visit <a href="https://github.com/">GitHub.com</a> and create an account using your real email address (used to identify your contributions).</li><li>If you’re privacy-conscious, go to <strong>Settings &gt; Emails</strong> and check the following options:</li></ol><ul><li><strong>Keep my email address private</strong></li><li><strong>Block command line pushes that expose my email</strong></li></ul><p>This will prevent your personal email from being exposed in your commits. You can also use the private GitHub email provided, like <em>123456789+username@users.noreply.github.com.</em></p><h4>Step 2: Set Up Git</h4><p>To link Git to GitHub, you need to configure your username and email in Git.</p><p><strong>Configure your global username and email</strong>:</p><pre>git config --global user.name &quot;Your Name&quot;<br>git config --global user.email &quot;yourname@example.com&quot;</pre><p>If you prefer to use GitHub’s private email:</p><pre>git config --global user.email &quot;123456789+username@users.noreply.github.com&quot;</pre><p><strong>Additional recommended settings</strong>:</p><ul><li>Change the default Git branch to <strong><em>main</em></strong> (GitHub’s default):</li></ul><pre>git config --global init.defaultBranch main</pre><ul><li>Enable colored output for Git:</li></ul><pre>git config --global color.ui auto</pre><ul><li>Set the default pull behavior to merging</li></ul><pre>git config --global pull.rebase false</pre><p><strong>Verify the configuration</strong>:</p><pre>git config --get user.name<br>git config --get user.email</pre><h4>For macOS Users: Ignore .DS_Store Files</h4><p>macOS creates invisible <strong><em>.DS_Store</em></strong> files that can clutter your Git history. To ignore them:</p><pre>echo .DS_Store &gt;&gt; ~/.gitignore_global<br>git config --global core.excludesfile ~/.gitignore_global</pre><h4>Step 3.1: Create an SSH Key</h4><p>SSH keys allow you to securely connect to GitHub without repeatedly typing your username and password.</p><p><strong>Check if an SSH key already exists</strong>:</p><pre>ls ~/.ssh/id_ed25519.pub</pre><p>If no such file exists, create a new SSH key:</p><pre>ssh-keygen -t ed25519</pre><ul><li>Press <strong>Enter</strong> to accept the default location.</li><li>Enter a passphrase if desired (optional).</li></ul><h4>Step 3.2: Link Your SSH Key to GitHub</h4><ol><li>Log into GitHub and go to <strong>Settings &gt; SSH and GPG keys</strong>.</li><li>Click <strong>New SSH Key</strong>, give it a descriptive title (e.g., “linux-ubuntu”), and leave this window open.</li><li>Copy your SSH key to the clipboard:</li></ol><pre>cat ~/.ssh/id_ed25519.pub</pre><p>Paste the copied key into GitHub and click <strong>Add SSH Key</strong>.</p><h4>Step 3.3: Test Your SSH Key</h4><p>Test the SSH connection to GitHub:</p><pre>ssh -T git@github.com</pre><p>If successful, you’ll see:</p><pre>Hi username! You&#39;ve successfully authenticated, but GitHub does not provide shell access.</pre><h3>VSCode extentions</h3><h4>1. Solidity by Nomic Foundation</h4><ul><li><strong>Description</strong>: Provides syntax highlighting, IntelliSense, code completion, and Solidity compilation support.</li><li><strong>Features</strong>: Helps with writing, compiling, and debugging smart contracts efficiently.</li><li><strong>Install</strong>: Search for “Solidity by Nomic Foundation” in the VSCode marketplace.</li></ul><h4>2. TOML by tamasfe</h4><ul><li><strong>Description</strong>: Enables syntax highlighting and better handling of TOML files, which is crucial when working with Foundry’s <strong><em>foundry.toml</em></strong>.</li><li><strong>Features</strong>: Makes configuring Foundry projects easier by improving readability and catching errors early.</li><li><strong>Install</strong>: Search for “TOML by tamasfe” in the VSCode marketplace.</li></ul><h4>3. Code Spell Checker by Street Side Software</h4><ul><li><strong>Description</strong>: Detects spelling mistakes in your code, especially useful for variable names, comments, and string literals.</li><li><strong>Features</strong>: Customizable dictionary, multilingual support, and smart suggestions for corrections.</li><li><strong>Install</strong>: Search for “Code Spell Checker” by Street Side Software in the marketplace.</li></ul><h4>4. Prettier — Code Formatter</h4><ul><li><strong>Description</strong>: A powerful code formatter that ensures your Solidity code (and other languages) follows consistent styling rules.</li><li><strong>Features</strong>: Automatically formats your code upon saving, keeping your work clean and standardized.</li><li><strong>Install</strong>: Search for “Prettier — Code Formatter” in the marketplace.</li></ul><p>If you’re interested in learning more about essential Solidity concepts like arrays, structs, and more, I’ve got another article that covers everything you need to know as a smart contract developer.</p><p>You can check it out <a href="https://medium.com/gitconnected/all-about-solidity-arrays-mapping-error-handling-events-constructors-modifiers-visibility-75c5afdcae87">here</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7b648804d16" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/a-quick-guide-on-installing-foundry-vscode-git-npm-and-node-js-c7b648804d16">A quick guide on installing foundry, vscode, git, npm and node.js</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All about Solidity: arrays, mapping, error handling, events, constructors, modifiers, visibility…]]></title>
            <link>https://levelup.gitconnected.com/all-about-solidity-arrays-mapping-error-handling-events-constructors-modifiers-visibility-75c5afdcae87?source=rss-cb00521e466f------2</link>
            <guid isPermaLink="false">https://medium.com/p/75c5afdcae87</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[smart-contract-blockchain]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[molaratai]]></dc:creator>
            <pubDate>Wed, 04 Sep 2024 09:51:56 GMT</pubDate>
            <atom:updated>2024-09-27T08:09:22.597Z</atom:updated>
            <content:encoded><![CDATA[<h3>All about Solidity: arrays, mapping, error handling, events, constructors, modifiers, visibility, fallback, struct….[with code snippets]</h3><p>From understanding data types to sending eth, a beginner’s guide to smart contract development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2iGDVU0Cuq_jy09z" /><figcaption>Photo by <a href="https://unsplash.com/@tbonz?utm_source=medium&amp;utm_medium=referral">Emmanuel Edward</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Starting in smart contract development can feel overwhelming, with so many concepts to learn. It’s normal to feel intimidated by the vast amount of knowledge ahead. But remember, every expert was once a beginner, facing the same uncertainty.</p><p>You don’t need to know everything at once. Solidity is learned step by step, and each concept you master brings you closer to building something incredible.</p><p>This article will guide you through the essentials, so you can start your journey with confidence.</p><p>Let’s take that first step together.</p><h3>Table Of Contents</h3><ol><li>Data types</li><li>Variables and Scope</li><li>Function and State Variable Visibility — public, private, internal, external</li><li>View and Pure functions</li><li>Constant</li><li>Constructor</li><li>Immutable</li><li>Array</li><li>Mapping</li><li>Struct</li><li>Data locations — storage, memory, and calldata</li><li>Payable</li><li>Enum</li><li>Function Modifier</li><li>Inheritance</li><li>Error handling</li><li>Interface</li><li>Event</li><li>Fallback and Receive Function</li><li>Sending Eth</li></ol><h3>Data Types</h3><p>In many programming languages like JavaScript, you can declare variables like this:</p><pre>const name = &quot;Legolas&quot;; // string<br>let num = 23; // integer<br>let active = true; // boolean</pre><p>However, this approach won’t work in Solidity.</p><p>In this section, we’ll explore four fundamental data types in Solidity: <em>uint, int, bool, and string</em>. We&#39;ll also look at some code examples to see how these types are used in practice.</p><ul><li><strong><em>uint</em></strong>: Used to store non-negative integers. You can specify the size of the integer, ranging from <em>uint8(8 bits) </em>to<em> uint256(256 bits)</em>. By default, <em>uint</em> an alias for <em>uint256</em>.</li><li><strong><em>int</em></strong>: Used to store both positive and negative integers. Similar to <em>uint</em>, you can specify the size, ranging<em> from int8 </em>to<em> int256</em> . By default, <em>int</em> is an alias for <em>int256</em>.</li><li><strong><em>bool</em></strong>: Used to store <em>true</em> or<em> false</em> values. This type is particularly useful for conditions and control flow within your smart contracts.</li><li><strong><em>string</em></strong>: Used to store sequences of characters, i.e., <em>text.</em> Unlike other data types, string is more complex as it represents a dynamic array of bytes.</li></ul><blockquote><strong>Note:</strong> If you’re not familiar with<em> pure, view and public</em>, don’t worry! We’ll explain them in detail later, so you can skip over them for now.</blockquote><p>Here’s a simple Solidity example that uses these data types:</p><pre>// SPDX-License-Identifier: MIT<br><br>pragma solidity ^0.8.19;<br><br>contract DataTypes {<br>    uint256 public myUint = 12345; // 256-bit unsigned integer<br>    int256 public myInt = -12345; // 256-bit signed integer<br>    bool public isActive = true;<br>    string public greeting = &quot;Hello, Readers!&quot;;<br><br>    // Function to interact with bool and string<br>    function checkStatus() public view returns (string memory) {<br>        if (isActive) {<br>            return greeting;  // Returns the greeting if isActive is true<br>        } else {<br>            return &quot;The contract is inactive.&quot;; // Simple message if isActive is false<br>        }<br>    }<br><br>     // Function to interact with uint and int<br>     function addToUint(uint256 value, int256 multiplier) public {<br>        myUint += value; // Add value to myUint<br>        myInt *= multiplier; // Multiply myInt by the multiplier<br>    }<br>}</pre><h3>Variable and Scope</h3><p><em>Variables </em>are storage locations that hold data values, while scope defines where in the code those variables can be accessed or modified.</p><p>The <em>scope</em> determines the visibility and lifetime of a variable, ranging from the entire contract to a specific block or function.</p><p>In essence,<em> variables</em> represent data, and <em>scope</em> dictates where that data can be used.</p><h4>Types of Variables in Solidity</h4><p><strong>State Variables</strong>: These are variables that are stored on the blockchain and have a permanent state. They are defined at the contract level.</p><p><strong>Local Variables</strong>: These variables are declared within functions and exist only during the execution of the function. They do not persist on the blockchain.</p><p><strong>Global Variables</strong>: These are special variables that provide information about the blockchain and the transaction. They are predefined by Solidity and can be accessed anywhere in the contract.</p><p>Understanding how to interact with smart contracts involves knowing about key global variables <em>msg.sender</em>, <em>msg.value</em>, <em>msg.data </em>and<em> block.timestamp.</em></p><ul><li><strong><em>msg.sender</em></strong>: The person or contract calling the current function, think of it as the sender’s address.</li><li><strong><em>msg.value</em></strong>: The amount of Ether (cryptocurrency) sent with the function call, it’s like the payment made during the transaction.</li><li><strong><em>msg.data</em></strong>: The raw information sent with the transaction, including the function name and any inputs, it’s the detailed message delivered in the call.</li><li><strong><em>block.timestamp:</em></strong> it returns the current block’s timestamp. It’s used for time-based operations in smart contracts.</li></ul><p>Here’s a simple Solidity example that uses state, local and global variables:</p><pre>// SPDX-License-Identifier: MIT<br><br>pragma solidity ^0.8.19;<br><br>contract Variables {<br>    uint public count = 10; // State variable stored on the blockchain, they are declared in a contract and outside a function<br><br>    function sumNumbers() public view returns (uint, uint){<br>       uint timestamp = block.timestamp; // Global variable (Current block timestamp)<br>       uint num = 15; // local variable not stored on the blockchain, they are declared within a function<br>       uint sum = count + num;<br>       return (timestamp, sum); // Returns Current block timestamp and 25<br>    }<br>}</pre><h4>Understanding Variable Scope</h4><p>Variable scope determines where in the code a variable can be accessed. Solidity has three levels of scope:</p><ol><li><strong>Contract-level scope</strong>: State variables are accessible throughout the contract.</li><li><strong>Function-level scope</strong>: Local variables are accessible only within the function where they are declared.</li><li><strong>Block-level scope</strong>: Variables declared inside blocks (<em>if, for,</em> etc.) are only accessible within that block.</li></ol><p>Here is an example:</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>contract VariableScope {<br>    uint public x = 10; // Contract-level scope<br><br>    function scopeExample() public view returns (uint) {<br>        uint y = 20; // Function-level scope<br><br>        if (x &lt; y) {<br>            uint z = 30; // Block-level scope<br>            return z;<br>        }<br><br>        // Uncommenting the line below will cause an error because z is out of scope<br>        // return z;<br>        <br>        return y;<br>    }<br>}</pre><h3>Function and State Variable Visibility</h3><p>Solidity provides four key visibility specifiers : <em>Private, Internal, Public, </em>and<em> external.</em></p><h4>Private: Keeping Things to Yourself</h4><p>The <em>private </em>keyword restricts access to a function or state variable so that it is only accessible within the contract where it is defined. Even contracts that inherit from this contract cannot access these private members.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract ParentContract {<br>    uint256 private secretValue = 42;<br><br>    function privateFunction() private view returns (uint256) {<br>        return secretValue;<br>    }<br><br>    function publicFunction() public view returns (uint256) {<br>        // This works fine<br>        return privateFunction();<br>    }<br>}<br><br><br>contract ChildContract is ParentContract {<br>    function attemptToAccessPrivateFunction() public view returns (uint256) {<br>        // This will not compile<br>        return privateFunction(); //Error<br>    }<br><br>    function attemptToAccessPrivateVariable() public view returns (uint256) {<br>        // This will not compile<br>         return secretValue; //Error<br>    }<br>}</pre><blockquote>The “<strong>is</strong>” keyword is used when a contract is inheriting from another contract. We’ll discuss inheritance later in this lesson.</blockquote><p>In the example above, the<strong> <em>privateFunction</em></strong> and <em>secretValue</em><strong> </strong>are only accessible within <strong>ParentContract</strong>. Any attempt to access them from <strong>ChildContract</strong> will result in a compilation error.</p><h4>Internal: Sharing with Family</h4><p>The <em>internal </em>keyword allows access within the contract it is defined in and any contracts that inherit from it. This is useful when you want to allow derived contracts to use certain functions or state variables.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract ParentContract {<br>    uint256 internal sharedValue = 100;<br><br>    function internalFunction() internal view returns (uint256) {<br>        return sharedValue;<br>    }<br>}<br><br>contract ChildContract is ParentContract {<br>    function accessInternalFunction() public view returns (uint256) {<br>        // This works fine<br>        return internalFunction();<br>    }<br><br>    function accessInternalVariable() public view returns (uint256) {<br>        // This works fine<br>        return sharedValue;<br>    }<br>}</pre><p>Here, <strong><em>internalFunction </em></strong>and <em>sharedValue</em> are accessible both in <strong>ParentContract<em> </em></strong>and <strong>ChildContract.</strong></p><h4>Public: Open to All</h4><p>The <em>public</em> keyword makes functions and state variables accessible from anywhere, including other contracts, accounts, and within the contract itself.</p><blockquote><strong>Note:</strong> If you’re not familiar with<em> </em><strong>constructor</strong> or some other concepts used in this example, don’t worry! Follow along for now, we’ll discuss them in detail as we progress.</blockquote><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract VisibilityExample {<br>    uint256 public publicValue = 200;<br><br>    function publicFunction() public view returns (uint256) {<br>        return publicValue;<br>    }<br>}<br><br>contract ExternalContract {<br>    VisibilityExample visibilityExample;<br><br>    constructor(address _visibilityExampleAddress) {<br>        visibilityExample = VisibilityExample(_visibilityExampleAddress);<br>    }<br><br>    function accessPublicFunction() public view returns (uint256) {<br>        return visibilityExample.publicFunction();<br>    }<br>}</pre><p>In this example, <strong><em>publicValue</em></strong> and <strong><em>publicFunction </em></strong>can be accessed by any external contract, as demonstrated by the<strong><em> </em>ExternalContract</strong>.</p><h4>External: For Outsiders Only</h4><p>The <em>external</em> keyword makes a function callable from outside the contract but not from within the same contract.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract VisibilityExample {<br>    function externalFunction() external pure returns (string memory) {<br>        return &quot;This is an external function&quot;;<br>    }<br><br>    function tryToCallExternalFunction() public pure returns (string memory) {<br>        // This will not compile<br>        // return externalFunction();<br>    }<br>}<br><br>contract ExternalContract {<br>    VisibilityExample visibilityExample;<br><br>    constructor(address _visibilityExampleAddress) {<br>        visibilityExample = VisibilityExample(_visibilityExampleAddress);<br>    }<br><br>    function callExternalFunction() public view returns (string memory) {<br>        return visibilityExample.externalFunction();<br>    }<br>}</pre><p>In this scenario, <strong><em>externalFunction</em></strong> can only be called from outside the <strong>VisibilityExample</strong> contract, as shown by the <strong>ExternalContract</strong>. Any attempt to call it within the same contract will result in a compilation error.</p><p>The line “<em>VisibilityExample visibilityExample;”</em> in the code is a declaration of a state variable named <em>visibilityExample</em><strong><em> </em></strong>that is of type <strong>VisibilityExample.</strong></p><p>What the Line Means:</p><pre>VisibilityExample visibilityExample;</pre><p>This line declares a variable called <em>visibilityExample</em>, which is meant to store a reference (or “pointer”) to a deployed instance of the contract <strong>VisibilityExample</strong>.</p><h4>Explanation:</h4><ol><li><strong>Contract Type as a Data Type:</strong></li></ol><ul><li>In Solidity, you can use a contract name as a data type, just like you would use <em>uint, string, or bool</em>.</li><li>Here, <strong>VisibilityExample </strong>is the name of another contract. By using <strong>VisibilityExample<em> </em></strong>as a type, you’re creating a variable that can hold a reference to an instance of this contract.</li></ul><p><strong>2. Creating a Reference:</strong></p><ul><li>The v<em>isibilityExample</em><strong><em> </em></strong>variable is designed to hold a reference to an instance of the <strong>VisibilityExample<em> </em></strong>contract, meaning it will point to an already deployed <strong>VisibilityExample<em> </em></strong>contract on the blockchain.</li><li>At this point in the declaration, v<em>isibilityExample</em><strong><em> </em></strong>is just a variable without any assigned value or reference. It needs to be initialized with the address of an actual deployed contract instance.</li></ul><p><strong>3. Initialization in the Constructor:</strong></p><ul><li>The constructor in the <strong>ExternalContract<em> </em></strong>contract takes an address as an argument. This address should be the address of a deployed <strong>VisibilityExample<em> </em></strong>contract.</li><li>The line <em>visibilityExample = VisibilityExample(_visibilityExampleAddress);</em> initializes the v<em>isibilityExample</em><strong><em> </em></strong>variable with a reference to the <strong>VisibilityExample<em> </em></strong>contract deployed at the address <strong><em>_visibilityExampleAddress</em></strong>.</li></ul><pre>constructor(address _visibilityExampleAddress) {<br>        visibilityExample = VisibilityExample(_visibilityExampleAddress);<br>    }</pre><ul><li>This effectively “links” the v<em>isibilityExample </em>variable to the specific <strong>VisibilityExample<em> </em></strong>contract instance, allowing <strong>ExternalContract<em> </em></strong>to interact with it.</li></ul><p><strong>4. Using the Reference:</strong></p><ul><li>Once initialized, the V<em>isibilityExample</em><strong><em> </em></strong>variable can be used to call functions on the <strong>VisibilityExample<em> </em></strong>contract.</li></ul><p>For example, the function <strong><em>callExternalFunction</em></strong> uses <strong><em>visibilityExample.externalFunction();</em></strong> to call the <strong><em>externalFunction </em></strong>from the V<strong>isibilityExample </strong>contract.</p><blockquote>Remember, while <strong>private</strong> and <strong>internal</strong> restrict access within the contract or its derivatives, they do not hide data on the blockchain.</blockquote><blockquote>All data stored on the blockchain is visible to everyone, so avoid storing sensitive information in these variables.</blockquote><h3>View and Pure Functions</h3><p>In Solidity, functions can be categorized not just by their visibility (<em>public, private, internal and external</em>) but also by their behavior.</p><p>Two important behavioral keywords are <em>view</em> and <em>pure</em>.</p><p>These keywords restrict what a function can and cannot do, specifically when it comes to interacting with the state of the blockchain.</p><h4>View Functions</h4><p>A <em>view </em>function promises not to modify the state of the blockchain. This means that it can read state variables but cannot change them.</p><p>Let’s look at a valid example of a <em>view </em>function. Here, we define a contract that keeps track of a user&#39;s balance and allows us to check the balance without modifying it.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract BalanceChecker {<br>    uint256 private userBalance;<br><br>    constructor() {<br>        userBalance = 100; // Initial balance set to 100<br>    }<br><br>    function getBalance() public view returns (uint256) {<br>        return userBalance;<br>    }<br>}</pre><p>In this example, the <strong><em>getBalance</em></strong> function reads the state variable <strong><em>userBalance </em></strong>but does not modify it, making it a valid <em>view </em>function.</p><h4>What Happens If a view Function Tries to Modify the State?</h4><p>Let’s try modifying the state inside a <em>view </em>function and see what happens:</p><pre>function updateBalance() public view returns (uint256) {<br>    // Trying to modify state<br>    userBalance += 50; // error <br>    return userBalance; // compiller error, function violates promise<br>    }</pre><h4>Pure Functions</h4><p><em>pure</em> functions take things a step further by promising not to read or modify the state of the blockchain.</p><p>In other words, they can’t interact with any state variables, and they can only use their local variables.</p><pre>function addNumbers(uint256 a, uint256 b) public pure returns (uint256) {<br>    return a + b;<br>    }</pre><p>This function doesn’t read or modify any state variables; it simply returns the sum of two input values, making it a valid <em>pure </em>function.</p><h4>What Happens If a pure Function Tries to Read the State?</h4><p>If you mistakenly try to read from the state within a <em>pure </em>function, you’ll also encounter a compilation error. Let’s see an example:</p><pre>contract BalanceChecker {<br>    uint256 private userBalance;<br><br>    constructor() {<br>        userBalance = 100; // Initial balance set to 100<br>    }<br>    <br>    function calculateBalance(uint256 increment) public pure returns (uint256) {<br>    return userBalance + increment; // Attempting to read a state variable<br>}<br>}</pre><p>This code will not compile because the <strong><em>calculateBalance</em></strong> function is marked as <em>pure </em>but attempts to read the <em>userBalance</em><strong> </strong>state variable.</p><h4>Combining view and pure Functions</h4><p>While <em>view </em>functions allow reading the state, and <em>pure </em>functions allow only local operations without any state interaction, you can use these functions together in your contracts to create efficient and secure smart contracts.</p><p>For example, a contract could use a <em>pure </em>function for internal calculations and a <em>view </em>function to fetch data based on those calculations.</p><pre>contract Calculator {<br>    uint256 private baseNumber = 10;<br><br>    function addBaseNumber(uint256 num) public view returns (uint256) {<br>        return pureAdd(num, baseNumber);<br>    }<br><br>    function pureAdd(uint256 a, uint256 b) public pure returns (uint256) {<br>        return a + b;<br>    }<br>}</pre><p>In this example, the <strong><em>pureAdd</em></strong> function is a <strong><em>pure </em></strong>function used by the <strong><em>addBaseNumber</em></strong> function, which is a<strong><em> view</em></strong> function. The <strong><em>addBaseNumber </em></strong>function reads the state but does not modify it, while <strong><em>pureAdd </em></strong>does not interact with the state at all.</p><h3>Constant</h3><p>A constant in Solidity is a state variable that cannot be modified after it has been declared and assigned a value.</p><p>Declaring a variable as constant ensures that its value remains unchanged throughout the contract’s lifecycle.</p><p>This immutability has several advantages, including reduced gas consumption when the variable is accessed in a function.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract ConstantsExample {<br>   // Declare a constant uint variable<br>    uint256 public constant MY_NUMBER = 42;<br><br>    // Function to return the constant number<br>    function getMyNumber() public pure returns (uint256) {<br>        return MY_NUMBER;<br>    }<br>}</pre><blockquote>Notice that by convention, constant variable names are written in uppercase letters, often with underscores separating words.</blockquote><h4>Gas Savings with Constants</h4><p>To demonstrate the gas savings that come with using constants, let’s compare the function <strong><em>getMyNumber</em></strong> and <strong><em>getMyNum</em></strong> in the contract below.</p><p>Here we declared a variable <em>myNumber</em> and a <strong>constant</strong> variable <em>MY_NUM</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*PS_p-VbuCDmRu-GdTDOMtg.png" /><figcaption>remix.IDE</figcaption></figure><h4>Comparing Gas Costs</h4><p>To compare the gas costs, calling <strong><em>getMyNumber</em></strong> on the <strong>CompareGas</strong> contract might cost around <strong>2,459 gas</strong>, while <strong><em>getMyNum </em></strong>on the same<strong><em> </em></strong>contract could cost approximately <strong>315 gas</strong> as showed in the image above.</p><p>This difference in gas cost, can add up significantly, especially in contracts with frequent function calls.</p><blockquote>In Solidity, <strong>pure</strong> functions can return constant variables because constants are hardcoded into the contract&#39;s bytecode and do not require accessing storage.</blockquote><blockquote>Since <strong>pure</strong> functions don&#39;t interact with the blockchain&#39;s state, returning constants aligns with their purpose. This allows for efficient, state-independent operations in <strong>pure</strong> functions.</blockquote><h3>Constructor</h3><p>A <em>constructor</em> in Solidity is a special function that is executed only once when a smart contract is deployed.</p><p>It’s primary purpose is to initialize state variables or perform any setup tasks that your contract needs before it can be used.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract SimpleStorage {<br>    uint public storedValue;<br><br>    // Constructor to initialize the stored value<br>    constructor(uint _initialValue) {<br>        storedValue = _initialValue;<br>    }<br><br>    // Function to update the stored value<br>    function setStoredValue(uint _newValue) public {<br>        storedValue = _newValue;<br>    }<br>}</pre><p>In the contract above, state variable <em>storedValue</em><strong><em> </em></strong>that takes in an integer and is not assigned a value upon declaration.</p><p>The constructor is used to set an initial value for the <em>storedValue</em><strong><em> </em></strong>variable when the contract is deployed.</p><p>The constructor takes an input parameter, <em>_initialValue</em>, and assigns it to <em>storedValue</em>. When deploying the contract, you can specify this initial value, which is then stored on the blockchain.</p><h4>Deploying the Contract</h4><p>When you deploy the <strong>SimpleSmart</strong> contract, you will be asked to provide a value for<strong><em> </em></strong><em>_initialValue</em>. For example, if you pass 100 as the initial value:</p><ul><li>The <em>storedValue</em> will be set to 100 at the time of deployment.</li><li>If you call <strong><em>setStoredValue(200)</em></strong>, the <em>storedValue </em>will update to 200</li><li><strong>Check the Initial Value:</strong> Use <strong><em>storedValue() </em></strong>to check the initial value stored.</li><li><strong>Update the Value:</strong> Use the <strong><em>setStoredValue()</em></strong> function to change the value of <em>storedValue</em><strong><em>.</em></strong></li></ul><p>Using a constructor ensures that important variables like <em>storedValue</em><strong><em> </em></strong>are properly initialized at the start.</p><h3>Immutable</h3><p>An <em>immutable</em> variable in Solidity is similar to a constant variable, but with a key difference: it can be initialized once, typically within the constructor of the contract, and afterward, it cannot be altered.</p><p>This ensures that the value remains fixed after the contract is deployed.</p><p><em>Immutable</em> variables, like constants, can also help save on gas costs, leading to slightly lower gas fees compared to regular state variables.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract ImmutableExample {<br>    // Immutable variable to store the creator&#39;s address<br>    address public immutable i_creator;<br><br>    // Constructor to initialize the immutable variable<br>    constructor() {<br>        // Set the creator&#39;s address to the address that deploys the contract<br>        i_creator = msg.sender;<br>    }<br><br>    // Function to get the creator&#39;s address (just for demonstration)<br>    function getCreator() external view returns (address) {<br>        return i_creator;<br>    }<br>}</pre><p>This example sets the <strong><em>i_creator</em></strong> address as immutable when the contract is deployed, meaning it can&#39;t be changed afterward.</p><p>The constructor assigns the deployer&#39;s address to<strong><em> i_creator</em></strong>, demonstrating how immutable variables work in Solidity.</p><p>If you have <strong>multiple immutable variables</strong>, you can initialize them all in the constructor like this:</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract Example3 {<br>    // Declare multiple immutable variables<br>    address public immutable i_owner;<br>    uint256 public immutable i_creationTime;<br>    uint256 public immutable i_totalSupply;<br><br>    constructor(uint256 _totalSupply) {<br>        // Initialize all immutable variables in the constructor<br>        i_owner = msg.sender;<br>        i_creationTime = block.timestamp;<br>        i_totalSupply = _totalSupply;<br>    }<br>}</pre><blockquote>Constants are less flexible and slightly more gas-efficient, while immutables offer flexibility for deployment-specific values.</blockquote><blockquote>Use constants for universally fixed values and immutables for deployment-dependent values.</blockquote><h3>Array</h3><p>Arrays are a fundamental data structure used to store collections of values. They can be either fixed-size or dynamic.</p><p>We’ll use a dynamic array of <em>string </em>types as our example to illustrate these concepts.</p><h4>1. Initializing Arrays</h4><p><strong>Dynamic arrays</strong> in Solidity can change size after deployment. Let’s declare a dynamic array of <em>string </em>to hold user names.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract UserNames {<br>    // Dynamic array of strings<br>    string[] public userNames;<br>    <br>    // Function to add a new user name<br>    function addUserName(string memory _name) public {<br>        userNames.push(_name);<br>    }<br>}</pre><p>In the example above, <em>userNames </em>is a dynamic array that we can grow or shrink. We initialize it as an empty array and add names using the <strong><em>addUserName</em></strong><em> </em>function.</p><p><strong>Fixed-size arrays</strong> have a predetermined length that cannot be changed. For instance, if we want to create a fixed-size array to store exactly three user names:</p><pre>contract FixedUserNames {<br>    // Fixed-size array of strings<br>    string[3] public userNames = [&quot;Charles&quot;, &quot;Alex&quot;, &quot;Becky&quot;];<br>}</pre><p>Here, <em>userNames </em>can only hold three names, and attempting to add more names will result in a compilation error.</p><h4>2. Array Operations</h4><p>Let’s explore various operations you can perform on arrays.</p><p><strong>Inserting Elements: </strong>To add elements to a dynamic array, use the push method:</p><pre>function addUserName(string memory _name) public {<br>    userNames.push(_name);<br>}</pre><p>For a fixed-size array, you cannot add new elements beyond the initial size.</p><p><strong>Getting Elements: </strong>Access elements by their index. Note that Solidity arrays are zero-indexed:</p><pre>function getUserName(uint index) public view returns (string memory) {<br>    require(index &lt; userNames.length, &quot;Index out of bounds&quot;);<br>    return userNames[index];<br>}</pre><p>The <em>require</em> statement in Solidity is used to enforce certain conditions that must be met before the execution of a function can proceed.</p><p>If the condition specified in this <em>require</em> statement is not met, the function execution is halted, and the transaction is reverted with the error message “<em>Index out of bound</em>”.</p><blockquote>We will discuss more about the <strong>require</strong> statement when we get to the error handling section.</blockquote><p><strong>Updating Elements: </strong>Update elements by reassigning values at a specific index:</p><pre>function updateUserName(uint index, string memory _newName) public {<br>    require(index &lt; userNames.length, &quot;Index out of bounds&quot;);<br>    userNames[index] = _newName;<br>}</pre><p><strong>Deleting Elements: t</strong>o delete an element, use the <em>delete</em> keyword. This will reset the element to its default value:</p><pre>function deleteUserName(uint index) public {<br>    require(index &lt; userNames.length, &quot;Index out of bounds&quot;);<br>    delete userNames[index];<br>}</pre><p><strong>Popping Elements:</strong> to remove the last element of a dynamic array:</p><pre>function removeLastUserName() public {<br>    require(userNames.length &gt; 0, &quot;No names to remove&quot;);<br>    userNames.pop();<br>}</pre><p><strong>Getting the Length of an Array: </strong>to get the number of elements in a dynamic array:</p><pre>function getUserNamesCount() public view returns (uint) {<br>    return userNames.length;<br>}</pre><h4>3. Arrays in Memory</h4><p>You can create arrays in memory for temporary use. Memory arrays are fixed-size and can’t be resized:</p><pre>function createMemoryArray() public pure returns (string[] memory) {<br>    string;<br>    tempArray[0] = &quot;Charles&quot;;<br>    tempArray[1] = &quot;Alex&quot;;<br>    tempArray[2] = &quot;Becky&quot;;<br>    return tempArray;<br>}</pre><p>Note that operations like <strong>push</strong> or <strong>pop </strong>are not available for memory arrays.</p><h4><strong>Why</strong>?</h4><p>Arrays can be stored in two main data locations: <strong>storage</strong> and <strong>memory</strong>. The location determines the behavior and capabilities of the array.</p><h4>Storage vs. Memory Arrays</h4><p><strong>Storage Arrays</strong>: These arrays are stored on the blockchain. They are persistent, meaning any changes made to them are recorded and will persist across function calls and transactions.</p><p>Storage arrays can be dynamic, meaning their size can change over time using operations like <strong>push </strong>and <strong>pop</strong>.</p><p><strong>Memory Arrays</strong>: These arrays are temporary and only exist during the execution of a function. They are not saved to the blockchain, so once the function execution is complete, the memory arrays are discarded.</p><p>Memory arrays must have a fixed size when they are created because they are allocated a specific amount of memory space that cannot be expanded or reduced.</p><h4>4. Returning Arrays from Functions</h4><p>Returning an array from a function can be gas-intensive for large arrays, so it’s often avoided.</p><p>Here’s how you can return a dynamic array from a function:</p><pre>function getUserNames() public view returns (string[] memory) {<br>    return userNames;<br>}</pre><h3>Mapping</h3><p>A mapping is like a virtual storage locker where you can store values (like a number, a string, or a boolean) using a key (like an address or a number).</p><p>Think of it like a real-life locker system where each locker has a unique number (the key), and inside that locker, you can store some items (the value).</p><pre>mapping(address =&gt; uint) public balances;</pre><p>In this example:</p><ul><li><em>address</em> is the key type. It’s like the locker number. In Ethereum, every user has a unique address.</li><li><em>uint</em> is the value type. It’s like the items you put in the locker. Here, we’re storing a number, which represents something like a balance of tokens.</li></ul><p>To set a value in a mapping, use the following syntax:</p><pre>balances[msg.sender] = 123;</pre><p>This sets the balance of the address <strong><em>msg.sender </em></strong>to 123.</p><p><strong>Retrieving</strong> a value from a mapping is similar to accessing an array:</p><pre>uint balance = balances[msg.sender];</pre><p>If you try to get a value from a mapping that hasn’t been set, it will return the default value for the value type. For<em> uint</em>, the default value is 0:</p><pre>uint balance = balances[address(1)]; // returns 0</pre><p>You can <strong>update</strong> a mapping just by setting a new value:</p><pre>balances[msg.sender] = 456;</pre><p>If you want to <strong>increment </strong>the value, you can do so using the<strong> +=</strong> operator:</p><pre>balances[msg.sender] += 200; // 456 + 200 = 656</pre><p>After this operation, the balance of <strong><em>msg.sender </em></strong>will be the sum of the previous balance and 200.</p><p>To<strong> delete</strong> a value in a mapping, use the <em>delete </em>keyword:</p><pre>delete balances[msg.sender];</pre><p>This resets the balance of <strong><em>msg.sender</em></strong> to the default value, which for <em>uint</em> is <strong>0</strong>.</p><h4>Why Use Mappings?</h4><p>Mappings are useful because they allow you to quickly look up a value based on a key without having to search through a list.</p><p>For example, if you want to set, know or clear someone’s balance, you just ask the mapping using their address, and it will tell you immediately.</p><p>Let’s put this all together in a simple contract:</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract Mapping {<br>    // This mapping stores the balance for each address<br>    mapping(address =&gt; uint) public balances;<br><br>    // Function to set the balance for the sender&#39;s address<br>    function setBalance(uint _amount) public {<br>        balances[msg.sender] = _amount;<br>    }<br><br>    // Function to get the balance for the sender&#39;s address<br>    function getBalance() public view returns (uint) {<br>        return balances[msg.sender];<br>    }<br><br>    // Function to clear the balance (set it to 0)<br>    function clearBalance() public {<br>        delete balances[msg.sender];<br>    }<br>}</pre><ul><li><strong>Set a Balance:</strong> When someone calls <strong><em>setBalance(100)</em></strong>, their balance is stored as <strong>100</strong> in the <em>balances</em> mapping.</li><li><strong>Get a Balance:</strong> They can check their balance by calling <strong><em>getBalance()</em></strong>, which returns <strong>100</strong>.</li><li><strong>Clear a Balance:</strong> If they call <strong><em>clearBalance()</em></strong>, their balance is reset to<strong> 0</strong>.</li></ul><p>Let’s take a look at another example while applying <em>immutable, constructor</em> and <em>mapping</em> below:</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract MyToken {<br>    // Immutable variable to store the total supply of tokens<br>    uint256 public immutable i_totalSupply;<br><br>    // Mapping to store the balances of each address<br>    mapping(address =&gt; uint256) public balances;<br><br>    // Constructor to initialize the immutable totalSupply<br>    constructor(uint256 _initialSupply) {<br>        // Set the total supply of tokens<br>        i_totalSupply = _initialSupply;<br><br>        // Assign the entire supply to the contract deployer<br>        balances[msg.sender] = _initialSupply;<br>    }<br><br>    // Function to transfer tokens from the sender to a recipient<br>    function transfer(address _recipient, uint256 _amount) external {<br>        require(balances[msg.sender] &gt;= _amount, &quot;Insufficient balance&quot;);<br>        require(_recipient != address(0), &quot;Invalid address&quot;);<br><br>        // Transfer the tokens<br>        balances[msg.sender] -= _amount;<br>        balances[_recipient] += _amount;<br>    }<br>}</pre><p>The<strong><em> </em></strong><em>i_totalSupply</em> is an immutable variable set during deployment and can&#39;t be changed later. The constructor assigns the entire supply to the deployer, and the <strong><em>transfer</em></strong> function enables token transfers.</p><h3>Struct</h3><p>Structs allows for the grouping of multiple data types into a single entity.</p><p>This can be especially useful when dealing with complex data structures like records, user profiles, or in this case, book.</p><h4>Defining a simple struct.</h4><p>In this example, we’ll create a struct named<em> Book,</em> which will represent a book in a library.</p><p>The <strong><em>Book</em></strong> struct will include a <em>title</em>, an <em>author</em>, and the<em> year</em> of publication.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract Library {<br>    struct Book {<br>        string title;<br>        string author;<br>        uint16 year;<br>    }<br><br>    // Declaring a state variable to hold the books<br>    Book[] public books;<br>}</pre><h4>Initializing a Struct</h4><p>There are three ways to initialize a struct in Solidity, and we’ll explore each of them.</p><h4>Method 1: Positional Arguments</h4><p>The first method involves passing the values directly as arguments in the order they were defined in the struct.</p><pre>function addBook(string memory _title, string memory _author, uint16 _year) public {<br>    Book memory newBook = Book(_title, _author, _year);<br>    books.push(newBook);<br>}</pre><p>Here, we create a new <strong><em>Book </em></strong>struct by providing the title, author, and year as arguments. The newly created <strong><em>Book </em></strong>is then added to the <strong><em>books</em></strong> array.</p><h4>Method 2: Key-Value Pairs</h4><p>The second method allows you to initialize a struct by specifying the field names, making it clear what each value represents.</p><pre>function addBook(string memory _title, string memory _author, uint16 _year) public {<br>    Book memory newBook = Book({ title: _title, author: _author, year: _year });<br>    books.push(newBook);<br>}</pre><p>With key-value pairs, the order of the fields doesn’t matter, which can improve readability.</p><h4>Method 3: Default Values</h4><p>The third method is to initialize a struct with its default values and then assign values to each field individually.</p><pre>function addDefaultBook() public {<br>    Book memory defaultBook;<br>    defaultBook.title = &quot;Default Title&quot;;<br>    defaultBook.author = &quot;Default Author&quot;;<br>    defaultBook.year = 2024;<br><br>    books.push(defaultBook);<br></pre><p>In this method, the <strong><em>Book </em></strong>struct is initialized with default values ( &quot;&quot;for strings and 0 for numbers), and then each field is updated individually.</p><h4>Updating a Struct</h4><p>Once a struct is stored in a state variable (such as in our <em>books</em> array), you can update its values. To do this, you need to load the struct into storage instead of memory.</p><pre>function updateBook(uint index, string memory _title, string memory _author, uint16 _year) public {<br>    Book storage bookToUpdate = books[index];<br>    bookToUpdate.title = _title;<br>    bookToUpdate.author = _author;<br>    bookToUpdate.year = _year;<br>}</pre><p>In this example, the<strong><em> Book</em></strong> struct is loaded into storage, which allows us to modify its fields. Any changes made to the<strong><em> bookToUpdate</em></strong> struct will persist after the function execution.</p><h4>Deleting a Struct</h4><p>To reset a struct’s fields to their default values, you can use the <em>delete</em> keyword.</p><pre>function deleteBook(uint index) public {<br>    delete books[index];<br>}</pre><p>This will reset the <strong><em>Book </em></strong>struct at the specified index, setting the<em> title</em> and <em>author</em> to &quot;&quot; and the <em>year</em> to 0.</p><h3>Data Location</h3><h4>Storage: Modifying Persistent Data</h4><p><em>storage</em> refers to data that is stored permanently on the blockchain.</p><p>When you change something in <em>storage</em>, the changes are saved on the blockchain.</p><p><strong>Example: </strong>Updating a User’s Information:</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract StorageExample {<br>    struct User {<br>        string name;<br>        uint age;<br>    }<br><br>    mapping(address =&gt; User) public users;<br><br>    // Function to update user details<br>    function updateUser(string memory _name, uint _age) public {<br>        User storage user = users[msg.sender]; // Load the struct from storage<br>        user.name = _name; // Update the name<br>        user.age = _age;   // Update the age<br>    }<br>}</pre><p>In this example, we have a <strong>User</strong> struct that stores a user&#39;s name and age.</p><p>The <strong><em>updateUser</em></strong> function allows the user to update their information. Since we use <em>storage</em>, the changes are saved on the blockchain.</p><h4>Memory: Temporary Data</h4><p><em>memory</em> is used for data that only needs to exist temporarily, while a function is running. Once the function is done, the data in <em>memory </em>is gone.</p><p><strong>Example: </strong>Viewing User Information:</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract MemoryExample {<br>    struct User {<br>        string name;<br>        uint age;<br>    }<br><br>    mapping(address =&gt; User) public users;<br><br>    // Function to view user details temporarily<br>    function viewUser() public view returns (string memory, uint) {<br>        User memory user = users[msg.sender]; // Load the struct into memory<br>        return (user.name, user.age); // Return the user&#39;s information<br>    }<br>}</pre><p>In this example, the <strong><em>viewUser</em></strong> function lets you see the user&#39;s name and age without making any changes to the blockchain.</p><p>The data is loaded into <em>memory</em>, used temporarily, and then discarded.</p><h4>Calldata: Efficient Input Handling</h4><p><em>calldata</em> is similar to<em> memory</em>, but it&#39;s specifically for function inputs. Data in <em>calldata </em>cannot be changed, which can make your functions more efficient.</p><p><strong>Example: </strong>Adding Numbers in an Array:</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract CalldataExample {<br>    // Function to add up numbers in an array<br>    function sumNumbers(uint[] calldata numbers) public pure returns (uint) {<br>        uint total = 0;<br>        for (uint i = 0; i &lt; numbers.length; i++) {<br>            total += numbers[i];<br>        }<br>        return total;<br>    }<br>}</pre><p>Here, the<strong><em> sumNumbers </em></strong>function takes an array of numbers and adds them together. By using <em>calldata</em>, we handle the input efficiently without modifying the original data.</p><h3>Payable</h3><p>In Solidity, the <em>payable</em> keyword is essential for functions that need to send or receive Ether.</p><p>Without it, your smart contract won&#39;t be able to handle Ether transactions.</p><p>Let&#39;s explore this concept by creating a simple donation contract that can accept and track donations.</p><h4>1. Setting Up the Contract</h4><p>First, let’s define our contract and create a state variable to store the contract’s owner. The owner will be the account that deploys the contract.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract Donation {<br>    address payable public owner;<br><br>    constructor() {<br>        owner = payable(msg.sender); // Initialize owner as the contract deployer<br>    }<br>}</pre><p>Here, we declare a <em>address payable</em> variable called <strong><em>owner</em></strong> and set it to the address that deploys the contract using <strong><em>msg.sender.</em></strong></p><p>The <em>payable</em> keyword allows the owner to send and receive Ether.</p><h4>2. Creating a Payable Donation Function</h4><p>Now, let’s add a function to allow users to send donations to the contract. This function must be marked as <em>payable </em>to accept Ether.</p><pre>function donate() public payable {<br>    require(msg.value &gt; 0, &quot;Donation must be greater than 0&quot;);<br>}</pre><p>The <strong><em>donate</em></strong> function allows anyone to send Ether to the contract. The <strong><em>msg.value</em></strong> represents the amount of Ether sent with the transaction.</p><p>We use <em>require</em> to ensure that the donation is greater than zero or an error with a message <em>“Donation must be greater than 0”</em> will be thrown.</p><h4>3. Checking the Contract’s Balance</h4><p>To keep track of the donations, let’s create a function to check the contract’s balance.</p><pre>function getBalance() public view returns (uint) {<br>    return address(this).balance;<br>}</pre><p>The <strong><em>getBalance</em></strong> function returns the current Ether balance of the contract.</p><p>This function is marked as<em> view</em> because it doesn&#39;t modify the state of the contract.</p><h4>4. Withdrawing Donations</h4><p>Finally, let’s add a function that allows the owner to withdraw the donations.</p><pre>function withdraw() public {<br>    require(msg.sender == owner, &quot;Only the owner can withdraw&quot;);<br>    require(address(this).balance &gt; 0, &quot;No funds to withdraw&quot;);<br><br>    owner.transfer(address(this).balance);<br>}</pre><p>The <strong><em>withdraw</em></strong> function ensures that only the owner can withdraw the funds and that there is a balance to withdraw.</p><p>The <em>transfer</em> method is used to send the entire balance to the owner&#39;s address.</p><h3>Enum</h3><p>While the<em> bool</em> data type allows you to express binary choices (<em>true</em> or <em>false</em>), there are many cases where you need to represent more than two states. This is where<em> enums</em> become incredibly useful.</p><p>An <em>enum</em> (short for “enumeration”) is a user-defined type in Solidity that allows you to create a set of named constants. These constants represent a collection of related values.</p><p>Let’s start by defining an <em>enum </em>that represents the various stages a crowdfunding campaign can go through:</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract CrowdfundingCampaign {<br>    // Define an enum to represent the different stages of a crowdfunding campaign<br>    enum CampaignStage { <br>         NotStarted, <br>         Funding, <br>         Successful,<br>         Failed, <br>         Completed <br>    }<br><br>    // State variable to store the current stage of the campaign<br>    CampaignStage public stage;<br><br>    // Initialize the campaign with the &#39;NotStarted&#39; stage<br>    constructor() {<br>        stage = CampaignStage.NotStarted;<br>    }<br><br>    // Function to update the stage of the campaign<br>    function updateStage(CampaignStage _stage) external {<br>        stage = _stage;<br>    }<br><br>    // Function to get the current stage of the campaign<br>    function getStage() external view returns (CampaignStage) {<br>        return stage;<br>    }<br><br>    // Function to reset the campaign stage to its default value (&#39;NotStarted&#39;)<br>    function resetStage() external {<br>        delete stage;<br>    }<br>}</pre><h4>Breaking Down the Code</h4><p><strong>Enum Definition:</strong> We start by defining an enum <strong>CampaignStage</strong> that lists all possible stages of a crowdfunding campaign: <em>NotStarted, Funding, Successful, Failed</em> and<em> Completed.</em></p><p><strong>State Variable</strong>: We declare a state variable <em>stage </em>of type<strong> CampaignStage</strong> to store the current stage of the campaign.</p><p><strong>Constructor</strong>: The constructor initializes the campaign with the <em>NotStarted </em>stage when the contract is deployed.</p><p><strong>Updating the Stage</strong>: The <strong><em>updateStage</em></strong> function allows us to update the stage of the campaign by passing in one of the enum values.</p><p><strong>Getting the Stage</strong>: The <strong><em>getStage</em></strong> function returns the current stage of the campaign.</p><p><strong>Resetting the Stage</strong>: The <strong><em>resetStage</em></strong> function resets the stage of the campaign to its default value, which in this case is the first value in the enum (<em>NotStarted</em>).</p><h4>Using the Enum in Practice</h4><p>After deploying the contract, the campaign stage is set to <em>NotStarted</em>. You can then update the stage as the campaign progresses. For example:</p><p><strong>Start the funding phase</strong>:</p><pre>updateStage(CampaignStage.Funding);</pre><p><strong>Mark the campaign as successful</strong>:</p><pre>updateStage(CampaignStage.Successful);</pre><p><strong>Indicate a failed campaign</strong>:</p><pre>updateStage(CampaignStage.Failed);</pre><p><strong>Complete the campaign</strong>:</p><pre>updateStage(CampaignStage.Completed);</pre><h4>Resetting the Campaign Stage</h4><p>If, for any reason, you need to reset the campaign stage to its initial state, you can use the <strong><em>resetStage</em></strong> function:</p><pre>resetStage();</pre><p>This will set the stage back to <em>NotStared,</em> as it is the default value of the <strong>CampaignStage</strong> enum.</p><h3>Function Modifier</h3><p>A function <em>modifier</em> allows you to wrap a function with additional logic.</p><p>This can be useful for things like access control, input validation, or executing code before and after the main function logic.</p><p>By using <em>modifiers</em>, you can avoid code repetition and improve the readability of your contracts.</p><p>Let’s create a simple voting system where only authorized users can vote, and we want to limit the voting period. We’ll use function modifiers to enforce these rules.</p><blockquote>It’s totally Ok if you don’t understand everything going on in the code below right now, just follow along and pay attention to how the modifiers are declared and implemented in the functions. I promise I’ll try to make sense of it.</blockquote><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract VotingSystem {<br>    address public owner;<br>    uint256 public endTime;<br>    mapping(address =&gt; bool) public hasVoted;<br>    mapping(address =&gt; bool) public authorizedVoters;<br>    uint256 public totalVotes;<br><br>    constructor(uint256 _votingDuration) {<br>        owner = msg.sender;<br>        endTime = block.timestamp + _votingDuration;<br>    }<br><br>    modifier onlyOwner() {<br>        require(msg.sender == owner, &quot;Not authorized: Only owner can perform this action.&quot;);<br>        _;<br>    }<br><br>    modifier onlyAuthorized() {<br>        require(authorizedVoters[msg.sender], &quot;Not authorized: You are not allowed to vote.&quot;);<br>        _;<br>    }<br><br>    modifier onlyDuringVoting() {<br>        require(block.timestamp &lt; endTime, &quot;Voting has ended.&quot;);<br>        _;<br>    }<br><br>    function authorizeVoter(address _voter) external onlyOwner {<br>        authorizedVoters[_voter] = true;<br>    }<br><br>    function vote() external onlyAuthorized onlyDuringVoting {<br>        require(!hasVoted[msg.sender], &quot;You have already voted.&quot;);<br>        hasVoted[msg.sender] = true;<br>        totalVotes += 1;<br>    }<br><br>    function endVoting() external onlyOwner {<br>        endTime = block.timestamp;<br>    }<br><br>    function getRemainingTime() external view returns (uint256) {<br>        if (block.timestamp &gt;= endTime) {<br>            return 0;<br>        }<br>        return endTime - block.timestamp;<br>    }<br>}</pre><h4>Breaking Down the Modifiers</h4><p><strong>onlyOwner Modifier</strong>: The <em>onlyOwner</em> modifier restricts certain functions to be called only by the owner of the contract. This is commonly used for administrative tasks.</p><pre>modifier onlyOwner() {<br>    require(msg.sender == owner, &quot;Not authorized: Only owner can perform this action.&quot;);<br>    _;<br>}</pre><p><strong>onlyAuthorized Modifier</strong>: The <em>onlyAuthorized</em> modifier ensures that only authorized users can vote. This prevents unauthorized access to the voting function.</p><pre>modifier onlyAuthorized() {<br>    require(authorizedVoters[msg.sender], &quot;Not authorized: You are not allowed to vote.&quot;);<br>    _;<br>}</pre><p><strong>onlyDuringVoting Modifier:</strong> The <em>onlyDuringVoting</em> modifier checks that the voting period is still active. It prevents users from voting after the deadline.</p><pre>modifier onlyDuringVoting() {<br>    require(block.timestamp &lt; endTime, &quot;Voting has ended.&quot;);<br>    _;<br>}</pre><h4>Applying Modifiers</h4><p>In our contract, the<strong><em> authorizedVoter</em></strong> function is restricted to the owner using the <strong><em>onlyOwner</em></strong> modifier.</p><p>Similarly, the <strong><em>vote</em></strong> function requires the caller to be an authorized voter and checks that the voting period is still active using both the <strong><em>onlyAuthorized</em></strong><em> </em>and <strong><em>onlyDuringVoting</em></strong><em> </em>modifiers.</p><h3>Inheritance</h3><p>Inheritance in Solidity allows one contract to inherit the properties and methods of another contract. This promotes code reusability and reduces redundancy.</p><p>To illustrate this, let’s consider an example with three contracts: Animal, Dog and Husky.</p><ul><li><strong>Animal</strong>: A base contract with some basic functionality.</li><li><strong>Dog</strong>: A derived contract that inherits from<em> </em><strong>Animal </strong>and overrides some functions.</li><li><strong>Husky</strong>: A further derived contract that inherits from <strong>Dog</strong><em> </em>and customizes it further.</li></ul><p>Here’s how we can achieve this:</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>// Base contract Animal<br>contract Animal {<br>    // A virtual function that can be overridden by derived contracts<br>    function sound() public pure virtual returns (string memory) {<br>        return &quot;Some generic animal sound&quot;;<br>    }<br><br>    // Another virtual function to demonstrate multiple inheritance<br>    function typeOfAnimal() public pure virtual returns (string memory) {<br>        return &quot;Generic Animal&quot;;<br>    }<br>}<br><br>// Derived contract Dog inheriting from Animal<br>contract Dog is Animal {<br>    // Overriding the sound function<br>    function sound() public pure override returns (string memory) {<br>        return &quot;Woof!&quot;;<br>    }<br><br>    // Overriding the typeOfAnimal function<br>    function typeOfAnimal() public pure override returns (string memory) {<br>        return &quot;Dog&quot;;<br>    }<br>}<br><br>// Further derived contract Husky inheriting from Dog<br>contract Husky is Dog {<br>    // Overriding the sound function again<br>    function sound() public pure override returns (string memory) {<br>        return &quot;Husky Woof!&quot;;<br>    }<br><br>    // Adding a new function specific to Husky<br>    function breed() public pure returns (string memory) {<br>        return &quot;Husky&quot;;<br>    }<br>}</pre><h4>How Inheritance Works</h4><ol><li><strong>Base Contract (Animal)</strong>: Contains functions<strong><em> sound </em></strong>and <strong><em>typeOfAnimal</em></strong><em> </em>marked as <em>virtual</em>. This indicates that these functions can be overridden by derived contracts.</li><li><strong>First Derived Contract (Dog)</strong>:</li></ol><ul><li>Inherits from<strong> Animal</strong> and overrides the <strong><em>sound</em></strong><em> </em>and <strong><em>typeOfAnimal</em></strong> functions.</li><li><strong>Dog </strong>provides its own implementation of <strong><em>sound </em></strong>and <strong><em>typeOfAnimal</em>.</strong></li></ul><p><strong>3. Second Derived Contract (Husky)</strong>:</p><ul><li>Inherits from <strong>Dog</strong> and further overrides the <strong><em>sound</em></strong> function to provide a more specific implementation.</li><li>Adds a new function <strong><em>breed</em></strong><em> </em>specific to the <strong>Husky</strong> contract.</li></ul><blockquote>By using the virtual and override keywords, you can extend and customize contract functionality effectively. The example above demonstrates how to build a hierarchy of contracts.</blockquote><p>Here’s how you can interact with the <em>Husky</em> contract:</p><pre>// Deploy Husky contract<br>Husky husky= new Husky();<br><br>// Call the functions<br>string memory sound = husky.sound(); // Returns &quot;Husky Woof!&quot;<br>string memory typeOfAnimal = husky.typeOfAnimal(); // Returns &quot;Dog&quot;<br>string memory breed = husky.breed(); // Returns &quot;Husky&quot;</pre><h3>Error Handling</h3><p>From checking conditions to handling unexpected states, Solidity provides several mechanisms to manage <em>errors </em>and exceptions.</p><p>We will explore four main error-handling techniques in Solidity: <em>require, revert, assert</em>, and <em>custom errors</em>.</p><ol><li><strong>The require statement</strong> is used to validate inputs and conditions at the start of a function. If the condition fails, it throws an <em>error</em> and reverts the state changes made in the function.</li></ol><p>Suppose we have a smart contract that handles a simple auction system. We want to ensure that bids placed are above a minimum value:</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract Auction {<br>    uint256 public minimumBid = 1 ether;<br><br>    function placeBid() external payable {<br>        // Validate the bid amount<br>        require(msg.value &gt;= minimumBid, &quot;Bid amount is too low&quot;);<br><br>        // If the requirement passes, the bid is accepted<br>        // Additional logic for placing a bid can be added here<br>    }<br>}</pre><p>In this example, <em>require</em> ensures that the<em> msg.value</em> is at least <em>1 ether.</em> If not, the transaction is reverted with the error message <em>&quot;Bid amount is too low&quot;.</em></p><p><strong>2. The revert </strong>function is another way to handle conditions, especially when they are nested in complex logic.</p><p>Let’s extend the auction contract to include an auction end function that ensures the auction has ended before accepting bids.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract Auction {<br>    uint256 public minimumBid = 1 ether;<br>    bool public auctionEnded;<br><br>    function endAuction() external {<br>        auctionEnded = true;<br>    }<br><br>    function placeBid() external payable {<br>        // Ensure the auction is still open<br>        if (auctionEnded) {<br>            revert(&quot;Auction has ended&quot;);<br>        }<br><br>        // Validate the bid amount<br>        if (msg.value &lt; minimumBid) {<br>            revert(&quot;Bid amount is too low&quot;);<br>        }<br><br>        // Additional logic for placing a bid can be added here<br>    }<br>}</pre><p>Here, <em>revert</em> is used to check if the auction has ended and to validate the bid amount. The error messages help identify why the transaction failed.</p><p><strong>3. The assert statement</strong> is used to check conditions that should always be true. If an<em> assert</em> fails, it indicates a bug in the contract, and it will revert the transaction while consuming all gas.</p><p>Let’s add a function to finalize the auction and ensure the total funds collected match the expected amount:</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract Auction {<br>    uint256 public minimumBid = 1 ether;<br>    uint256 public totalBids;<br>    bool public auctionEnded;<br><br>    function placeBid() external payable {<br>        // Ensure the auction is still open<br>        require(!auctionEnded, &quot;Auction has ended&quot;);<br><br>        // Validate the bid amount<br>        require(msg.value &gt;= minimumBid, &quot;Bid amount is too low&quot;);<br><br>        // Update total bids<br>        totalBids += msg.value;<br>    }<br><br>    function endAuction() external {<br>        auctionEnded = true;<br>    }<br><br>    function finalizeAuction() external {<br>        // Internal consistency check<br>        assert(totalBids % minimumBid == 0);<br><br>        // Additional logic for finalizing the auction can be added here<br>    }<br>}</pre><p>In this example, <em>assert</em> is used to ensure that <em>totalBids</em> is a multiple of <em>minimumBid</em>, which should always be true if bids are placed correctly.</p><p><strong>4. Using Custom Errors for Gas Efficiency</strong>: Custom errors are introduced in Solidity 0.8 to save gas, especially with complex error messages. They are cheaper than using strings with<em> require</em> or <em>revert</em>.</p><p>They are about 5 ways to declared <em>custom error</em> but we’ll only be discussing 2 in the examples below since they are more gas efficient than the others.</p><p>1. <strong>Standard CamelCase</strong></p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract Auction {<br>    uint256 public minimumBid = 1 ether;<br>    bool public auctionEnded;<br><br>    // Declare a custom error<br>    error AuctionError(string reason);<br><br>    function endAuction() external {<br>        auctionEnded = true;<br>    }<br><br>    function placeBid() external payable {<br>        // Ensure the auction is still open<br>        if (auctionEnded) {<br>            revert AuctionError(&quot;Auction has ended&quot;);<br>        }<br><br>        // Validate the bid amount<br>        if (msg.value &lt; minimumBid) {<br>            revert AuctionError(&quot;Bid amount is too low&quot;);<br>        }<br><br>        // Additional logic for placing a bid can be added here<br>    }<br>}</pre><p>In this example, the <strong><em>AuctionError</em></strong> custom error is defined to replace string-based error messages. This approach reduces gas costs associated with error handling.</p><h4>2. Double Underscore</h4><p>You can also use a double underscores to separate the<em> error </em>name and the <em>error</em> message. No string message is needed to be passed.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract Auction {<br>    uint256 public minimumBid = 1 ether;<br>    bool public auctionEnded;<br><br>    // Declare a custom error with double underscore, both methods can be used depending on your preference <br>    error AUCTION__ENDED();<br>    error Bid__EnterMore();<br><br>    function endAuction() external {<br>        auctionEnded = true;<br>    }<br><br>    function placeBid() external payable {<br>        // Ensure the auction is still open<br>        if (auctionEnded) {<br>            revert AUCTION__ENDED();<br>        }<br><br>        // Validate the bid amount<br>        if (msg.value &lt; minimumBid) {<br>            revert Bid__EnterMore();<br>        }<br><br>        // Additional logic for placing a bid can be added here<br>    }<br>}</pre><p>In this implementation:</p><ul><li><strong>AUCTION__ENDED()</strong> is used for signaling that the auction has ended.</li><li><strong>Bid__EnterMore()</strong> is used for signaling that the bid amount is too low.</li></ul><blockquote>These naming conventions can help make your code more consistent and easier to read, especially in larger projects.</blockquote><h3>Interface</h3><p>An <em>interface</em> in Solidity is like a blueprint. It defines the functions you want to interact with in another contract but doesn’t contain any implementation.</p><p><em>Interfaces</em> are commonly used to interact with external contracts, allowing your contract to call functions on them without needing to know how those functions are implemented.</p><h4>Example: Interacting with a Simple Wallet Contract</h4><p>Let’s consider an example where we interact with a simple wallet contract that allows users to deposit and withdraw Ether. We’ll create an interface to interact with this wallet contract.</p><h4>Step 1: Define the Wallet Contract</h4><p>First, let’s assume the wallet contract is already deployed on the Ethereum network. The contract allows deposits and withdrawals, and it keeps track of each user’s balance.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract SimpleWallet {<br>    mapping(address =&gt; uint) public balances;<br><br>    function deposit() public payable {<br>        balances[msg.sender] += msg.value;<br>    }<br><br>    function withdraw(uint _amount) public {<br>        require(balances[msg.sender] &gt;= _amount, &quot;Insufficient balance&quot;);<br>        balances[msg.sender] -= _amount;<br>        payable(msg.sender).transfer(_amount);<br>    }<br><br>    function getBalance() public view returns (uint) {<br>        return balances[msg.sender];<br>    }<br>}</pre><h4>Step 2: Create an Interface to Interact with the Wallet</h4><p>Now, let’s assume we don’t have access to the code of<strong> SimpleWallet</strong> and only know its deployed address. We want to interact with this contract by creating an interface.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>interface ISimpleWallet {<br>    function deposit() external payable;<br>    function withdraw(uint _amount) external;<br>    function getBalance() external view returns (uint);<br>}</pre><h4>Step 3: Use the Interface in Another Contract</h4><p>Next, we’ll create a contract that uses this interface to interact with the deployed <strong>SimpleWallet</strong> contract.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract WalletInteractor {<br>    ISimpleWallet public wallet;<br><br>    constructor(address _walletAddress) {<br>        wallet = ISimpleWallet(_walletAddress);<br>    }<br><br>    function depositToWallet() public payable {<br>        wallet.deposit{value: msg.value}();<br>    }<br><br>    function withdrawFromWallet(uint _amount) public {<br>        wallet.withdraw(_amount);<br>    }<br><br>    function checkWalletBalance() public view returns (uint) {<br>        return wallet.getBalance();<br>    }<br>}</pre><p>To deploy and interact with these contracts:</p><ol><li>Deploy the SimpleWallet Contract: Assume this is already deployed, and you have its address.</li><li>Deploy the WalletInteractor Contract: Pass the address of the deployed <strong>SimpleWallet</strong> contract to the constructor of <strong>WalletInteractor</strong>.</li><li>Interact with SimpleWallet via WalletInteractor: You can now deposit Ether, withdraw Ether, and check your balance in the wallet, all through the <strong>WalletInteractor </strong>contract.</li></ol><h4>Why Are Interfaces Important?</h4><ul><li><strong>Interoperability:</strong> Interfaces enable your contract to interact with external contracts without needing their source code, essential in decentralized ecosystems.</li><li><strong>Modularity:</strong> They promote clean, maintainable code by reducing redundancy and allowing interaction with external contracts without copying large amounts of code.</li><li><strong>Upgradability:</strong> Contracts can still function with updated external contracts as long as the interface remains unchanged, making your code more robust.</li><li><strong>Security:</strong> Interfaces minimize security risks by only requiring function signatures, not the internal logic, reducing potential vulnerabilities.</li><li><strong>Gas Efficiency:</strong> They help optimize gas usage by allowing interaction with large contracts without including unnecessary code.</li></ul><h4>Example in Practice:</h4><p>Imagine you’re building a decentralized finance (DeFi) application that needs to interact with a stablecoin contract (like USDC or DAI).</p><p>You don’t need the entire implementation of the stablecoin contract in your code; you only need to interact with a few key functions, such as <strong><em>transfer</em></strong> and <strong><em>balanceOf</em></strong>.</p><p>Using an interface, you can define these functions without importing the entire stablecoin contract code:</p><pre>interface IStablecoin {<br>    function transfer(address recipient, uint256 amount) external returns (bool);<br>    function balanceOf(address account) external view returns (uint256);<br>}</pre><p>Now, your DeFi application can interact with any stablecoin that adheres to this interface, regardless of its internal implementation.</p><h3>Event</h3><p>An <em>event </em>in Solidity is like a loudspeaker announcement that records specific actions in a smart contract, making them visible on the blockchain.</p><p>It’s mainly used to log information that off-chain applications can easily read. Events help track important activities without storing extra data on the blockchain.</p><p><em>Events </em>can also be used to store data at a lower cost compared to state variables.</p><p><strong>Example: </strong>Let’s create a simple auction contract to demonstrate the use of events. This contract will allow users to place bids, and an event will be emitted each time a new bid is placed.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract Auction {<br>    // Define the event<br>    event NewBid(address indexed bidder, uint256 amount, string message);<br><br>    // State variables<br>    address public highestBidder;<br>    uint256 public highestBid;<br><br>    // Function to place a bid<br>    function placeBid() public payable {<br>        require(msg.value &gt; highestBid, &quot;Bid amount is too low&quot;);<br><br>        // Update the highest bid and bidder<br>        highestBidder = msg.sender;<br>        highestBid = msg.value;<br><br>        // Emit the NewBid event<br>        emit NewBid(msg.sender, msg.value, &quot;New highest bid placed!&quot;);<br><br>        // More logic can be added here<br>    }<br><br>    // Function to get the highest bid details<br>    function getHighestBid() public view returns (address, uint256) {<br>        return (highestBidder, highestBid);<br>    }<br>}</pre><h4>Breaking down the code</h4><ol><li><strong>Defining the event:</strong></li></ol><pre>event NewBid(address indexed bidder, uint256 amount, string message);</pre><p>Here, we’ve defined an event<strong><em> NewBid</em></strong> that logs the address of the bidder, the bid amount, and a custom message.</p><p>The <em>indexed</em> keyword allows us to filter logs by the bidder&#39;s address, making it easier to search through event logs.</p><p><strong>2. Emitting the code:</strong></p><pre>emit NewBid(msg.sender, msg.value, &quot;New highest bid placed!&quot;);</pre><p>The <em>emit </em>keyword is used to trigger the event, logging the relevant information whenever a new bid is placed.</p><p><strong>3. Placing a Bid:</strong></p><pre>function placeBid() public payable {<br>    require(msg.value &gt; highestBid, &quot;Bid amount is too low&quot;);<br><br>    // Update the highest bid and bidder<br>    highestBidder = msg.sender;<br>    highestBid = msg.value;<br><br>    // Emit the NewBid event<br>    emit NewBid(msg.sender, msg.value, &quot;New highest bid placed!&quot;);<br>}</pre><p>The <strong><em>placeBid</em></strong> function allows users to place bids on the auction. If the bid is higher than the current highest bid, the function updates the highest bid and bidder, and then emits the <strong><em>NewBid</em></strong> event.</p><p><strong>4. Getting the Highest Bid:</strong></p><pre>function getHighestBid() public view returns (address, uint256) {<br>    return (highestBidder, highestBid);<br>}</pre><p>This function returns the current highest bid and the address of the highest bidder, providing a quick way to access this information.</p><h3>Fallback and Receive</h3><p>Fallback and receive functions help manage how contracts handle incoming Ether. They are crucial for understanding how to interact with contracts that receive Ether.</p><p><strong>The fallback function</strong> is used when:</p><ul><li>A function is called that does not exist in the contract.</li><li>Ether is sent to the contract with data.</li></ul><p>It’s a catch-all function for handling unexpected interactions.</p><p><strong>The receive function</strong> is specifically used when:</p><ul><li>Ether is sent to the contract without any accompanying data.</li></ul><p>It’s a more focused way to handle simple Ether transfers.</p><h4>Imagine Your Contract as a House</h4><p>Think of your smart contract as a house. People can interact with your house by either knocking on the door (calling a function) or by just leaving a gift (sending Ether). But sometimes, things don’t go exactly as planned.</p><h4>The Fallback Function: Your Do-It-All Robot</h4><p>The fallback function is like a robot inside your house. This robot is there to handle unexpected situations:</p><ol><li><strong>When Someone Knocks on the Wrong Door:</strong></li></ol><ul><li>Imagine someone tries to open a door that doesn’t exist in your house. The robot steps in and says, “Hey, that door isn’t here, but I’ll take care of it!”</li><li>In contract terms, if someone calls a function that doesn’t exist, the fallback function gets triggered.</li></ul><p><strong>2. When Someone Leaves a Gift with a Note</strong>:</p><ul><li>If someone leaves money (Ether) at your house with a little note (data), the robot will pick it up and handle it.</li><li>This happens when Ether is sent to the contract with some data attached to it. The fallback function kicks in to handle the situation.</li></ul><h4>The Receive Function: Your Ether-Only Mailbox</h4><p>The receive function is like a special mailbox that only accepts gifts (Ether) and doesn’t care about notes:</p><p><strong>When Someone Leaves a Gift with No Note</strong>:</p><ul><li>If someone drops off money at your house without any note, the mailbox collects it.</li><li>In contract terms, if Ether is sent to your contract without any data, the receive function is triggered.</li></ul><h4>A Simple Example: Your Contract in Action</h4><p>Let’s say you have this simple contract, which is your house:</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract SimpleHouse {<br>    event Received(string message, address sender, uint amount);<br><br>    // Mailbox for Ether with no notes<br>    receive() external payable {<br>        emit Received(&quot;Received Ether with no data&quot;, msg.sender, msg.value);<br>    }<br><br>    // Robot that handles everything else<br>    fallback() external payable {<br>        emit Received(&quot;Fallback function called&quot;, msg.sender, msg.value);<br>    }<br>}</pre><h4>Contract Breakdown</h4><p><strong>Receive Function</strong>:</p><ul><li>This function is executed when Ether is sent without any data.</li><li>It logs a message indicating that Ether was received without data.</li></ul><p><strong>Fallback Function</strong>:</p><ul><li>This function is called when Ether is sent with data or if a function is called that does not exist.</li><li>It logs a message indicating that the fallback function was used.</li></ul><p>If someone sends Ether without any data, your mailbox (receive function) takes it in and says, “Got it!”</p><p>If someone sends Ether with data or tries to use a door that doesn’t exist, the robot (fallback function) steps in and says, “I’ll handle this!”</p><h4>Why Do You Need These?</h4><ul><li><strong>Receive Function</strong>: It’s a simple way to make sure your contract can take in Ether with no fuss.</li><li><strong>Fallback Function</strong>: It’s like a safety net that makes sure your contract doesn’t break if something unexpected happens.</li></ul><h3>Sending Eth</h3><p>Imagine you have a smart contract, like a digital wallet, and you want to send some Ether (a type of cryptocurrency) to another contract.</p><p>In Solidity, there are three main ways to do this: <em>transfer, send </em>and<em> call</em>. Let&#39;s break them down.</p><h4>Setting Up the Contract to Receive Ether</h4><p>Before you can send Ether, your contract needs to be able to receive it. Think of this as opening your wallet so others can send you money.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>// This contract is like a wallet that can receive Ether<br>contract EtherReceiver {<br>    // This event is like a receipt that shows who sent money and how much<br>    event LogReceived(address sender, uint amount);<br><br>    // This function is automatically called when Ether is sent to this contract<br>    receive() external payable {<br>        emit LogReceived(msg.sender, msg.value);<br>    }<br>}</pre><p>This simple contract can receive Ether. Whenever it does, it records who sent it and how much they sent, just like getting a receipt when you make a purchase.</p><h4>Sending Ether: The Three Methods</h4><p>Now, let’s say you have another contract that will send Ether. There are three ways to do this: <em>transfer, send </em>and<em> call</em>.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract EtherSender {<br>    // This function allows this contract to receive Ether<br>    receive() external payable {}<br><br>    // Method 1: Using transfer<br>    function sendByTransfer(address payable _to, uint _amount) public {<br>        _to.transfer(_amount);<br>    }<br><br>    // Method 2: Using send<br>    function sendBySend(address payable _to, uint _amount) public returns (bool) {<br>        bool sent = _to.send(_amount);<br>        require(sent, &quot;Send failed&quot;);<br>        return sent;<br>    }<br><br>    // Method 3: Using call<br>    function sendByCall(address payable _to, uint _amount) public returns (bool) {<br>        (bool success, ) = _to.call{value: _amount}(&quot;&quot;);<br>        require(success, &quot;Call failed&quot;);<br>        return success;<br>    }<br>}</pre><h4>Breaking It Down</h4><ol><li><strong>Transfer Method:</strong></li></ol><ul><li><strong>Simple:</strong> It’s like handing cash to someone and expecting them to accept it without any problems.</li><li><strong>Fixed Gas:</strong> It sends just enough “energy” (2,300 gas) to do simple things, like saying “Thank you!” when they get the cash.</li><li><strong>Guaranteed:</strong> If anything goes wrong, it cancels the whole transaction. No money is lost.</li></ul><pre>function sendByTransfer(address payable _to, uint _amount) public {<br>    _to.transfer(_amount);<br>}</pre><p><strong>2. Send Method:</strong></p><ul><li><strong>Similar to Transfer:</strong> It also sends 2,300 gas, like transfer.</li><li><strong>Returns a Result:</strong> Instead of just hoping it worked, it checks if the transfer succeeded and lets you know with a true/false result.</li><li><strong>Requires a Check:</strong> You should always check if it worked. If it didn’t, you can stop everything to avoid losing money.</li></ul><pre>function sendBySend(address payable _to, uint _amount) public returns (bool) {<br>    bool sent = _to.send(_amount);<br>    require(sent, &quot;Send failed&quot;);<br>    return sent;<br>}</pre><p><strong>3. Call Method:</strong></p><ul><li><strong>Super Flexible:</strong> This one is like giving someone a blank check and trusting them to take what they need. It sends all the gas (energy) they need to do whatever they want.</li><li><strong>Returns More Info:</strong> It not only tells you if it worked, but it can also give you back some data (though you might not always need it).</li><li><strong>Safer in Complex Situations:</strong> It’s now the recommended way to send Ether because it’s better at handling complicated situations.</li></ul><pre>function sendByCall(address payable _to, uint _amount) public returns (bool) {<br>    (bool success, ) = _to.call{value: _amount}(&quot;&quot;);<br>    require(success, &quot;Call failed&quot;);<br>    return success;<br>}</pre><h4>Putting It All Together</h4><p>Imagine you have two wallets: one that sends money (<strong>EtherSender</strong>) and one that receives it <strong>(EtherReceiver</strong>). You can choose how you want to send the money:</p><ul><li><strong>Transfer</strong> is like sending a small amount with a guarantee it will work.</li><li><strong>Send</strong> is like doing the same but checking if it actually worked.</li><li><strong>Call</strong> is like sending a big amount with all the necessary resources to handle it, even if it’s complicated.</li></ul><blockquote>Remember, handling money in smart contracts is serious business, so always double-check your work!</blockquote><h4>Why 2,300 Gas?</h4><p>The gas value of 2,300 units is a well-known figure in Ethereum development and is related to the way the Ethereum Virtual Machine (EVM) handles gas limits for certain operations. Here’s where it comes from:</p><p><strong>transfer Method:</strong></p><ul><li>When you use <em>transfer </em>to send Ether, Solidity automatically forwards 2,300 gas units to the recipient. This gas limit is set by the Solidity compiler to prevent the receiving contract from doing too much work with the gas and potentially causing unexpected behaviors, like reentrancy attacks.</li></ul><p><strong>send Method:</strong></p><ul><li>The <em>send</em> method, like <em>transfer</em>, also forwards exactly 2,300 gas units. The idea behind this is to provide the same safety mechanism, limiting the amount of work the receiving contract can do.</li></ul><p><strong>call Method:</strong></p><ul><li>The <em>call</em> method does not impose a fixed gas limit by default. It forwards all remaining gas to the recipient, making it much more flexible but also potentially more risky if not used correctly. However, you can manually specify a gas limit when using <em>call</em>.</li></ul><blockquote>If you want to dive deeper into this, you can refer to the Solidity documentation or the EVM’s specifics on gas usage, which discuss these values in detail.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75c5afdcae87" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/all-about-solidity-arrays-mapping-error-handling-events-constructors-modifiers-visibility-75c5afdcae87">All about Solidity: arrays, mapping, error handling, events, constructors, modifiers, visibility…</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web3: Revolutionizing the Internet or a Risky Gamble?]]></title>
            <link>https://medium.com/cryptocurrency-scripts/web3-revolutionizing-the-internet-or-a-risky-gamble-be4a45d150a9?source=rss-cb00521e466f------2</link>
            <guid isPermaLink="false">https://medium.com/p/be4a45d150a9</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[crypto]]></category>
            <dc:creator><![CDATA[molaratai]]></dc:creator>
            <pubDate>Sat, 24 Aug 2024 04:05:53 GMT</pubDate>
            <atom:updated>2024-08-24T04:05:53.938Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5bDXliCW3lBJbQQ4" /><figcaption>Photo by <a href="https://unsplash.com/@traxer?utm_source=medium&amp;utm_medium=referral">Traxer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>From Uwulend’s $19.4 million hack to Ronin Network’s $625 million breach, the infamous Onecoin $6 billion scam, and the FTX $8 billion financial fraud, the list of scandals and disasters in the crypto space seems endless.</p><p>Paired with the everyday rug pulls in meme coin trading, it’s easy to conclude that the whole space is a recipe for disaster.</p><h3>The Evolution of the Internet: What is Web3?</h3><p>The evolution from Web 1.0’s “read-only” internet to Web 2.0’s interactive content creation brought significant advancements but also led to concerns over centralized control and data monetization by tech giants.</p><p>This gave rise to the next phase of the internet: Web3.</p><p>Web3, or Web 3.0, represents a transformative shift in the digital landscape, offering a more decentralized, secure, and user-centric internet.</p><p>It aims to give users ownership of their data and a stake in the networks they use, all powered by blockchain technology.</p><p>Moreover, Web3 integrates advanced technologies like smart contracts, which automate agreements without intermediaries. This not only ensures transparency and trust but also reduces costs and inefficiencies.</p><p>The inclusion of cryptocurrencies further supports a new creator economy, enabling direct transactions between users and opening up innovative monetization opportunities.</p><h3>Current Challenges and Criticisms</h3><p>While Web3 has gained significant attention for its promise of a decentralized internet where users reclaim control from tech giants,</p><p>it is not without its detractors.</p><p>Some argue that beneath the idealistic visions,</p><p>Web3 is often little more than a marketing strategy designed to rebrand crypto assets as revolutionary tools poised to disrupt the current tech landscape.</p><p>Web3 faces significant technical and security challenges.</p><p>The <strong>Compute Problem</strong> highlights the inefficiency of blockchain networks, where every node must execute every operation, leading to astronomical costs and limited computational power.</p><p>The <strong>Storage Problem</strong> raises concerns about who controls data in a blockchain-based system, with unresolved issues around privacy and data management.</p><p>The <strong>Bandwidth Problem</strong> reveals that decentralized systems are more expensive and less efficient to maintain than centralized ones, contradicting Web3’s core ethos.</p><p>Additionally, <strong>security</strong> remains a critical issue, as the decentralized nature of Web3 exposes systems to new vulnerabilities, with high-profile hacks and scams highlighting the risks associated with the space.</p><h3>Innovations in Security and Technology</h3><p>Despite these criticisms, Web3’s security challenges are being met with several key innovations.</p><p>Regular smart contract <strong>audits and formal verification </strong>processes ensure code integrity,</p><p>while <strong>bug bounty</strong> programs incentivize ethical hackers to find vulnerabilities early.</p><p>Layer 2 solutions like Rollups enhance <strong>scalability</strong> and security by offloading transactions from the main blockchain.</p><p><strong>Decentralized identity systems </strong>give users control over their digital identities, while zero-knowledge proofs (ZKPs) protect privacy by verifying data without exposure.</p><p>Governance mechanisms, such as<strong> DAOs </strong>(Decentralized Autonomous Organizations), enable community oversight, and advanced encryption methods secure data and communications.</p><p>Continuous <strong>monitoring and updates</strong> address emerging threats, ensuring a robust Web3 environment.</p><p><strong>On the technical front</strong>, significant advancements have been made in computing, bandwidth, and storage solutions.</p><p>Layer 2 technologies, sharding, and optimized virtual machines have improved scalability and efficiency.</p><p>Decentralized Content Delivery Networks <strong>(CDNs)</strong> and <strong>off-chain storage</strong> solutions ensure that data is securely and efficiently managed, overcoming traditional limitations.</p><h3>The Road Ahead</h3><p>Despite the criticisms and challenges, Web3 represents a ground-breaking shift toward a more equitable and decentralized digital future.</p><p>By empowering individuals with greater control over their data and online interactions, Web3 challenges the dominance of centralized entities and fosters innovation.</p><p>The technology is still in its early stages, and while there are hurdles to overcome, the progress being made in addressing these issues is promising.</p><p>As the infrastructure continues to evolve and mature, Web3 has the potential to revolutionize the internet, offering a more secure, transparent, and user-centric experience.</p><h3>Learning More: Resources to Explore Web3</h3><p>For those intrigued by the potential of Web3 and eager to explore it further, here are some valuable free resources to get started:</p><ol><li><a href="https://cryptozombies.io/"><strong>CryptoZombies</strong></a>: A fun, interactive platform that teaches smart contract development through gamified lessons.</li><li><a href="https://cyfinupdraft.com/"><strong>Cyfin Updraft</strong></a>: Provides insightful content and tutorials tailored for both beginners and advanced users interested in the technical aspects of Web3.</li><li><a href="https://solidity-by-example.org/"><strong>Solidity by Example</strong></a>: A hands-on guide to learning Solidity with clear examples and explanations.</li><li><strong>Ethereum’s Official Documentation</strong>: Offers a comprehensive deep dive into smart contracts and decentralized applications.</li><li><a href="https://web3js.readthedocs.io/"><strong>Web3.js</strong></a> and <strong>Ethers.js</strong>: Libraries that are excellent starting points for developers looking to interact with the Ethereum blockchain.</li><li><a href="https://www.youtube.com/watch?v=gyMwXuJrbJQ&amp;t=80s"><strong>FreeCodeCamp Videos</strong></a>: Free educational videos that cover blockchain fundamentals and Web3 development, perfect for both beginners and advanced learners.</li></ol><p>By diving into these resources, anyone can start their journey into the world of Web3 and its possibilities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be4a45d150a9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cryptocurrency-scripts/web3-revolutionizing-the-internet-or-a-risky-gamble-be4a45d150a9">Web3: Revolutionizing the Internet or a Risky Gamble?</a> was originally published in <a href="https://medium.com/cryptocurrency-scripts">Cryptocurrency Scripts</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>