<?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 Ifeoluwaolubo on Medium]]></title>
        <description><![CDATA[Stories by Ifeoluwaolubo on Medium]]></description>
        <link>https://medium.com/@ifeoluwaolubo?source=rss-8e81ec09f3a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*A--iseutVHSDJXmzDTFJhQ.jpeg</url>
            <title>Stories by Ifeoluwaolubo on Medium</title>
            <link>https://medium.com/@ifeoluwaolubo?source=rss-8e81ec09f3a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:49:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ifeoluwaolubo/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[Smart Contract Interaction With The Outside World: Chainlink vs Foundry.]]></title>
            <link>https://medium.com/coinmonks/smart-contract-interaction-with-the-outside-world-chainlink-vs-foundry-73dafe4f653e?source=rss-8e81ec09f3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/73dafe4f653e</guid>
            <category><![CDATA[foundry]]></category>
            <category><![CDATA[ethereum-blockchain]]></category>
            <category><![CDATA[chainlink-vrf-v2]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Ifeoluwaolubo]]></dc:creator>
            <pubDate>Sat, 11 Nov 2023 15:44:18 GMT</pubDate>
            <atom:updated>2023-11-14T17:40:30.408Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FgGFG3YWH-aFkG1a2VTMOQ.png" /></figure><p>Inasmuch as we want to make our applications as decentralized as possible in the sense that there are no “external forces” acting on it (for example a centralized organization trying to force the entire system in their favour), we soon realize that quite often, a lot of what we do in our smart contracts still has to interact with the outside world and in essence, centralized bodies.</p><p>You might be wondering though, <em>what are the cases where our contracts would need this said interactions?<br></em>A lot of real world applications we end up building actually needs us to interact with the outside world. For example, your contract might need to convert some amount of <em>ethers </em>to <em>USD </em>in real time<em>, </em>or maybe you need some sort of automations to trigger some things in your contract, getting a random value, etc. All this requires external interactions with our contracts.</p><blockquote>Randomization on the blockchain is a bit tricky to achieve, which is why we often require external tools to get random values.</blockquote><h4>Where does chainlink come in?</h4><p>According to their official website at <a href="https://chain.link/">chain.link</a>. <em>Chainlink is the decentralized computing platform powering the verifiable web</em>. All the problems listed above and more is what chainlink hopes to solve. So rather than relying on centralized organizations and trusting that they always behave accordingly, chainlink brings the interaction we need from the external world to a more decentralized ecosystem.</p><p>In this article, we’ll see how we can generate random numbers using chainlink VRF (verifiable randomness function) and we would be doing this with our newly found tool “Foundry”. Let’s get started 🚀.</p><h3>Getting started</h3><p>To follow along you can visit the chainlink documentation below</p><p><a href="https://docs.chain.link/">Blockchain Oracles for Connected Smart Contracts | Chainlink Documentation</a></p><p>To get started, we’ll initialize a new foundry project with</p><pre>forge init</pre><p>Then we’ll delete all the dummy counter related contracts in the src, test and script folders. I created a <em>ChainlinkDemo.sol</em> contract in the src folder like below. I’ll be using VsCode for this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*-4U0fj0L3Ldox53guADCyg.png" /></figure><h4>Chainlink VRF</h4><p>The biggest thing to know about VRF is that you are funding a subscription which is like an account to maintain balance from multiple other contracts. To create your own subscription, head over to the random number generation section on the docs <a href="https://docs.chain.link/vrf/v2/subscription/examples/get-a-random-number">here</a> and follow the steps on the “Create and fund subscription section”.</p><p>You need to have some test ETH and link on your chosen testnet. At the time of writing, the docs uses the Sepolia Testnet and that’s what we’ll stick with here. You can get some test ETH and link at <a href="https://faucets.chain.link/">faucets.chain.link</a>.<br>After that, follow the processes involved in creating a subscription and fund it with ETH and link.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gaAkk3Rzhf0G6e4HI0hTwQ.png" /><figcaption>create subscription</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lx49ST-3bmvcCJ5nayncxA.png" /></figure><p>After setting it all up, you should arrive at an <em>add consumer</em> page like below. Keep this open for later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WS8NSpD6hoTdbW_k0XxUMQ.png" /></figure><p>Getting a random number with VRF is a 2 transaction functions, the first requests the random number generator and the second gets the random number. When we scroll down the get a random number documentation, we’ll see a code section for the <em>VRFv2Consumer</em> contract and we’ll use this code to get our random number. In particular with are interested in the code block highlighted in green below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tdRKdZI8nwCGOgIiTUIBjg.png" /></figure><p>So let’s copy this into our contract:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h2ZK3h_fg1eeY_DDsL4UiQ.png" /></figure><p>Of course we’ll get plenty errors, but we’ll sort them out soon. Let’s first understand what that code block is doing.</p><ul><li>The COORDINATOR is the chainlink’s VRF coordinator address that we will be making the request to. This returns a requestId when we call the requestRandomWords function.</li><li>The keyHash is your <em>gas lane. </em>It specifies whether or not you want to spend too much gas. (Same with the callbackGasLimit).</li><li>The s_subscriptionId is the Id of the subscription we’ve funded with link when following the create subscription process from above.</li><li>The requestConfirmations is the number of blocks confirmations for our random number to be considered as good.</li><li>The numWords specifies how many random numbers we want to generate.</li></ul><blockquote>The coordinator address and keyHash is different for whichever chain we are using.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P1cTq507mer-79MvmYvN4g.png" /></figure><p>We created a constructor that accepts a couple of parameters and since they won’t be changing, we set them as either immutable or constant variables. After setting all our variables and passing them to the <em>requestRandomWords</em> function, we then get the error that our <em>i_vrfCoordinator</em> which is an address does not have the <em>requestRandomWords</em> function on it. For this to be resolved, we’ll have to import the <em>VRFCoordinateV2Interface </em>from chainlink like in the documentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TWbPehL-zhSWMvhQcSoxEw.png" /></figure><p>Then the we need to run the install command below to pull what we need from chainlink.</p><pre>forge install smartcontractkit/chainlink --no-commit</pre><p>But the issue with installing this directly from chainlink’s repo is that I found it to be a really big pull (almost about 300mb). Alternatively, we could install a rather simplified version using.</p><pre>forge install smartcontractkit/chainlink-brownie-contracts@0.6.1 --no-commit</pre><blockquote>I’ll be sticking with the first install command.</blockquote><p>In our <em>foundry.toml</em> file, we write the following lines to make our installed package accessible and visible to our contract.</p><pre>remappings = [&#39;@chainlink/contracts/=lib/chainlink/contracts&#39;]<br><br>// if you&#39;re using the minified one, then use<br>remappings = [&#39;@chainlink/contracts/=lib/chainlink-brownie-contracts/contracts&#39;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8F-h2v2U7gPreoEGupgizA.png" /></figure><p>If everything was configured properly, then the error should not show up again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*icuN4xMSnu3IugVA3TCiDA.png" /></figure><p>We changed the type of our <em>i_vrfCoordinator</em> to now be the imported interface, then type cast the <em>vrfCoordinator</em> address passed as a parameter in our constructor also to the imported interface.</p><p>The next thing we need to do is also copy another code from the documentation which chainlink node is going to call to give us back our random number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pYfXXIySA8wndGDFd2YljQ.png" /></figure><p>The override keyword there simply means that we want to override the <em>fulfillRandomWords</em> function that our contract is inheriting from, but since we are not doing any inheritance currently on our contract, we get the error as above. Let’s make our contract inherit from the VRFConsumerBaseV2 as in the documentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2PFKZWD1S0LZ7HB1Nvj9AA.png" /></figure><p>Notice how this gives us a bunch of errors? This is because we need to call the constructor of VRFConsumerBaseV2 we are inheriting from.</p><blockquote>Whenever we are inheriting from a contract that has a constructor, we have to pass this constructor into our own constructor as well.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hoWrT6fCT3sNCRJ3gX6RaQ.png" /></figure><p>Notice how we passed the VRFConsumerBaseV2 constructor into our own constructor by calling it and passing the address of the <em>vrfCoordinator</em>. Now all the errors should go away. To keep track of the requests we have made to get a random number, we create the storage variables as seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fCbvkYb1_Mb244SKuik8TA.png" /></figure><p>Then use it in our randomNumber function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W2FSThbENGqAqHVgivGnPA.png" /></figure><p>As stated earlier, the <em>fulfillRandomWords</em> is what would be called by the chainlink node, passing the requestId and the numbers that were generated. We then store the number in our <em>s_requests</em> variable and make a few updates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hrs1RoHvWpQLa2lT6Xarew.png" /></figure><p>Finally, we’ll create a few getter functions to get some values we might be interested in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RmFmSuwt5BA5V584V98Uyg.png" /></figure><p>We can definitely test this locally using the tools that foundry provides, but just so we test very quickly, I’ll be using remix to test. So copy your code to remix, then in deploy and run transactions section, select <em>injected provider — metamask, </em>this is because we are going to be deploying to the SEPOLIA testnet as opposed to remix’s VM. Then fill out the parameters needed to deploy your contract like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q6dpy4ggZAUNYRkUQmbMmQ.png" /></figure><p>The subscriptionId is the id of the subscription you created earlier. To get the vrfCoordinator address and the key hash for the testnet, in this case Sepolia, go to <a href="https://docs.chain.link/vrf/v2/subscription/supported-networks">supported network</a> section on the docs and you’ll see the different details for your testnet if supported.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gMzhUAhooFfF-StTpLZmsw.png" /></figure><p>Once the contract has deployed, copy the address of the deployed contract and add it as a consumer in the add consumer section from earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TLzKGKMOZpSpzwNSik12hQ.png" /></figure><p>Once you’ve added the consumer, go back to remix and interact with your deployed contract by first clicking on the randomNumber button, then click on the getLastRequestId button to get your requestId, then check that the request has been fulfilled by clicking on the getRequestStatus button. Once this returns true, then click on the getNumber button and this returns the random Number 😋.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*eEPT_ySFgPECcMnirSEHbw.png" /></figure><p>You can find the full code below</p><pre>// SPDX-License-Identifier: MIT<br><br>pragma solidity ^0.8.21;<br><br>import {VRFCoordinatorV2Interface} from &quot;@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol&quot;;<br>import {VRFConsumerBaseV2} from &quot;@chainlink/contracts/src/v0.8/vrf/VRFConsumerBaseV2.sol&quot;;<br><br>contract ChainlinkDemo is VRFConsumerBaseV2 {<br>    uint16 private constant REQUEST_CONFIRMATIONS = 3;<br>    uint32 private constant NUM_WORDS = 1;<br><br>    VRFCoordinatorV2Interface private immutable i_vrfCoordinator;<br>    bytes32 private immutable i_keyHash;<br>    uint64 private immutable i_subscriptionId;<br>    uint32 private immutable i_callbackGasLimit;<br><br>    struct RequestStatus {<br>        bool fulfilled;<br>        bool exists;<br>        uint256[] randomWords;<br>    }<br>    mapping(uint256 =&gt; RequestStatus) private s_requests;<br>    uint256[] private s_requestIds;<br>    uint256 private s_lastRequestId;<br><br>    constructor(<br>        uint64 subscriptionId,<br>        address vrfCoordinator,<br>        bytes32 keyHash,<br>        uint32 callbackGasLimit<br>    ) VRFConsumerBaseV2(vrfCoordinator) {<br>        i_subscriptionId = subscriptionId;<br>        i_vrfCoordinator = VRFCoordinatorV2Interface(vrfCoordinator);<br>        i_keyHash = keyHash;<br>        i_callbackGasLimit = callbackGasLimit;<br>    }<br><br>    function randomNumber() external {<br>        uint256 requestId = i_vrfCoordinator.requestRandomWords(<br>            i_keyHash,<br>            i_subscriptionId,<br>            REQUEST_CONFIRMATIONS,<br>            i_callbackGasLimit,<br>            NUM_WORDS<br>        );<br>        s_requests[requestId] = RequestStatus({<br>            fulfilled: false,<br>            exists: true,<br>            randomWords: new uint256[](0)<br>        });<br>        s_requestIds.push(requestId);<br>        s_lastRequestId = requestId;<br>    }<br><br>    function fulfillRandomWords(<br>        uint256 _requestId,<br>        uint256[] memory _randomWords<br>    ) internal override {<br>        require(s_requests[_requestId].exists, &quot;request not found&quot;);<br>        s_requests[_requestId].fulfilled = true;<br>        s_requests[_requestId].randomWords = _randomWords;<br>    }<br><br>    function getLastRequestId() public view returns (uint256) {<br>        return s_lastRequestId;<br>    }<br><br>    function getRequestStatus(uint256 requestId) public view returns (bool) {<br>        return s_requests[requestId].fulfilled;<br>    }<br><br>    function getNumber(<br>        uint256 requestId<br>    ) public view returns (uint256[] memory) {<br>        return s_requests[requestId].randomWords;<br>    }<br><br>    function getRequestIds() public view returns (uint256[] memory) {<br>        return s_requestIds;<br>    }<br>}</pre><p>Alright then, in this article we’ve talked about the fact that generating random numbers on the blockchain can be very tricky and we can leverage chainlink VRF to help us generate a random number following the steps outlined on the documentation. Please feel free to still dive into the docs to better understand what is going on and building upon what we have done in this article.</p><p>In the next article, we’ll also be looking at another of chainlink’s wonderful tool that helps us to get real time data feeds, specifically the real time equivalent of <em>ethers</em> to <em>USD.</em></p><p>I hope you found this article useful, please give a clap, follow, and comment. I’ll see you in the next one. 🚀🤩</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73dafe4f653e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/smart-contract-interaction-with-the-outside-world-chainlink-vs-foundry-73dafe4f653e">Smart Contract Interaction With The Outside World: Chainlink vs Foundry.</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Smart Contract Testing: The Foundry Way]]></title>
            <link>https://medium.com/web-3-digitals/smart-contract-testing-the-foundry-way-d86fcc5ca33e?source=rss-8e81ec09f3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d86fcc5ca33e</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[foundry]]></category>
            <dc:creator><![CDATA[Ifeoluwaolubo]]></dc:creator>
            <pubDate>Sat, 04 Nov 2023 10:17:39 GMT</pubDate>
            <atom:updated>2023-11-12T05:59:29.901Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o_b4XxxhOZ0Aj3SDiyHpkg.jpeg" /></figure><p>In the previous article, we started out with a new tool called <em>Foundry </em>to aid our smart contract development life cycle. We wrote a Kickstarter smart contract that “sort of” solves the issue the current kickstarter project faces by moving it into a rather decentralized system. You can find the link to article below ⬇️:</p><p><a href="https://medium.com/coinmonks/intro-to-foundry-the-kickstarter-smart-contract-888a534be0b0">Intro To Foundry: The Kickstarter Smart Contract</a></p><p>Since the blockchain is designed to be immutable, it is very important that we thoroughly test the behaviour of our smart contract to see if it does as intended before we actually deploy it on the blockchain. Please note that, the fact that we need to do thorough testing on our smart contracts cannot be over emphasized. In fact, this is so important that companies hire smart contract security engineers and auditors to run through their software for potential bugs and necessary optimizations.</p><p>Foundry is a very beautiful tool when it comes to smart contract testing. We not only have the ability to write tests in our beloved solidity, but it also come packed with some cheat codes that makes writing tests much easier. With foundry, we can see how much tests we’ve written and the different areas of our code the test covers very easily. Although writing test that has a 100% test coverage is rather infeasible, we should at least try to make it a very high percentage.</p><p>In this article, we build upon our preexisting knowledge of foundry by extending our kickstarter smart contract from the previous article and writing extensive tests for it. I’ll be using VsCode as my editor. Let’s get right into it 🚀</p><h4>Basic testing</h4><p>In my test folder, I’ll create a new file called <em>KickstarterTest.t.sol </em>with the following code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*ZDMem1Ly5aRWF2pfIzXyWQ.png" /></figure><p>Like all the smart contracts we’ve previously worked on, we have our usual declarations and version. On line 5 we are importing a <em>Base </em>contract called <em>Test</em> from forge. Then our KickstarterTest contract now “Inherits” From this test contract and that’s exactly what the code on line 7 is doing, we’re simply just inheriting from forge’s base Test contract so all the testing tools would be readily available to us.</p><p>Quite often, we’ll need to do some initial setup (like funding an account with some ethers) before we run our tests. In foundry, we can do this by using the <em>setUp</em> function as seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*S4HPF3yMwnGv78niq_nfYA.png" /><figcaption>setUp function</figcaption></figure><blockquote>The setup function runs each time before any of our tests runs. Eg if we have a test to check the balance of an account and another test to transfer ethers, then our test suite would run something like this:</blockquote><blockquote>setUp() -&gt; testBalance() -&gt; setUp() -&gt; testTransfer()</blockquote><p>For demo purposes, let’s just write a simple test to get familiar with how we actually run tests in foundry.<br>NB: I’ll be removing this test once I’m done, it’s only for demo purposes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*sNCkblfmIWR13SWLRxvjSg.png" /><figcaption>assertion test</figcaption></figure><p>Here we are just testing that the amount is indeed 20 using the assertEq function. Run the test using this command</p><pre>forge test</pre><p>You should see an output like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wxAGrgBZdedoJky1jtgJoQ.png" /></figure><h4>What to test..</h4><p>Now that we’ve seen some basic testing, we have to test our actual kickstarter contract. One thing to know before writing good tests for our contract (or any software really) is, <em>what aspects of our code are we very interested in </em>and whether or not these aspects should always behave appropriately.</p><p>So really, what are the aspects of our contract that we are so interested in? I’ve noted a few things that we might absolutely need to write test for, which includes (but not limited to):</p><ul><li>The manager’s address is the right thing</li><li>The minimum contribution set by the manager upon contract creation is actually the right thing.</li><li>Users that are funding must not provide an amount less than the minimum contribution amount.</li><li>We are keeping track of the funders and how much they have funded so far.</li><li>Manager can create <em>spend requests</em></li><li>Funders cannot create <em>spend requests</em></li><li>Funders can approve spend requests</li><li>Manager cannot finalize the movement of money without the majority of the funders approving the spend request.</li><li>Manager can move money if majority of the funders has approved the spend request</li></ul><p>By no means is this all we need to test for, this is just sufficient as of right now. Also to fully grasp what it is we’re planning to test, I’ll suggest you quickly have a refresher on the previous article where we worked on the kickstarter contract just in case you haven’t done that yet, again link is below ⬇</p><p><a href="https://medium.com/coinmonks/intro-to-foundry-the-kickstarter-smart-contract-888a534be0b0">Intro To Foundry: The Kickstarter Smart Contract</a></p><h4>A little code refactor…</h4><p>Before writing our test, there is a little modification we’ll need to do to our previous implementation. Foundry provides us with a way to write deployment script and these scripts simulates deployment to various blockchain network. So you guessed right, we’ll be creating our own deployment script. 😋</p><p>First let’s delete the <em>Deploy.sol </em>file that contains our <em>DeployCampaign </em>factory from the last article, then change the constructor of the Campaign contract to only accept the minimum contribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*j1eluZ-iLLh_Weo3zxKA0Q.png" /></figure><p>In the script folder, create a <em>DeployKickstarter.s.sol</em> file with the following content:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JrXvPBwlZuKnM5pxpfxNsA.png" /></figure><p>We imported our campaign, then created a <em>DeployCampaign </em>contract that inherits from the base <em>Script </em>from forge. We then created a <em>run</em> function that returns a campaign. The run function is the entry point of our deployment script. The <em>vm.startBroadcast() </em>and <em>vm.stopBroadcast() </em>are cheatcodes that comes with forge scripts, basically it broadcasts the transaction to deploy the contract on a blockchain.</p><p>We use the setAmount function to set the minimum amount then in between the start and stop broadcast we created our campaign and passed the minimum amount. Again this deploys the contract on-chain. Run the command:</p><pre>forge script script/DeployKickstarter.s.sol</pre><p>You should see outputs like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JoQu1-z7eChy-SlOEujXcA.png" /></figure><p>The good thing about creating deployment scripts like this is that we not only use it for deployment but also for testing and we are sure that we have the same deployment configured in both scenarios.</p><p>We can now use this deployment script in our test setUp function like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xkdZ9JquBMkk0EXda40YAg.png" /><figcaption>test setUp</figcaption></figure><p>Nothing much here, we just created a constant to store the minimum amount that would be used during our test. In the setUp function, we created a <em>deployCampiagn</em>, set the amount to the minimum amount then ran the deployment and saved the returned campaign in our campaign storage.</p><h4>Actual testing</h4><p>Alright, we’ve finally reached the point where we can start writing tests for our campaign. First let’s test that our manager is the right thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*uGlmsMoBujeiW6n05c5oIw.png" /></figure><blockquote>You’re probably wondering why the address being used is the msg.sender and not the deployCampaign address. Another thing the start and stop broadcast does is that it sets the actual sender of the transaction as the sender and not the deployCampaign.</blockquote><p>If all was done correctly, then you should see that the test passes like so</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w1dKRyhJRaEo0BYALOdomg.png" /></figure><p>Great, so far so good. Lets move on to the next test 🚀</p><p>Next we test that the minimum amount is the correct value</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*brdRJhKqN3cA2AFgdOILAQ.png" /></figure><p>Then run forge test again. You should see 2 tests passing.</p><p>Next we test a funder cannot contribute less than the minimum amount</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gVPEw3ONqMOlps4tmTjplg.png" /></figure><p>The <em>vm.expectRevert() </em>means that the code below it is supposed to revert. Since we are passing an amount that is less than the minimum contribution amount we are simply just saying that we expect the lines below it to fail. Run the tests again and it should be passing as well.</p><p>We then test that we keep track of the funders and the amount they funded.</p><blockquote>When writing tests, it can be quite difficult sometimes to know who’s sending a particular transaction, which is why foundry provides a cheatcode that lets us explicitly declare who it is that would be sending the transactions.</blockquote><p>Before continuing with our tests, lets create a user that would be sending all of our transactions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*zWzYt3IESzI1V3xBut-80g.png" /></figure><p>Forge provides us with a <em>makeAddr</em> function that accepts a name and returns an address. This would be the address of the user sending our transactions.</p><p>I added a function to our campaign contract in the Kickstarter.sol file to get the amount funded by a funder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Foc2FBkCXDAhYx1f0iWfXQ.png" /></figure><p>We can then use this function in our test like so</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*cfNfqap0Lfo9CrmwhCBvyQ.png" /></figure><p>Run this test with a <em>-vvvv </em>flag. You should see your tests failing 😅</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rw8P7ke9-7kUQoZ2hgDaSA.png" /></figure><p>Notice the EvmError at the bottom to be “Out of fund”. Meaning the user does not have enough ethers for the transaction and specifically has zero ethers. Now this is expected since we only created the user without actually providing some initial balance to their account. Luckily for us, forge also provides another cheatcode that gives our user some ethers. Now let’s magically produce ethers out of thin air 😎.</p><blockquote>The -vvvv flag used is sort of a log level where the number of v’s ranges from 1 to 5 and each shows more logs for your test. The more the v, the more comprehensive logs you see.</blockquote><p>In our setUp function, let’s give our user 50 ether.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p8gXJlfLnuWtGiVJcrp5LQ.png" /><figcaption>vm.deal() cheatcode</figcaption></figure><p>Modify your test again like below, run it and they should now be passing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*crM6a8jrQQ8U-yRGGJ_g6A.png" /><figcaption>vm.prank() cheatcode</figcaption></figure><p>The <em>vm.prank(USER)</em> means that the next immediate transaction is to be sent by the <em>USER.</em></p><p>That was a lot of cheat codes I know 😂, but let’s continue with our test. Next we are to test that a manager can create spend request. I added the following code to the campaign contract, then used it in our test below.</p><pre>function getSpendRequestCount() public view returns (uint) {<br>        return s_numRequests;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NuaF_lTU2xPF0b5g2b8y0A.png" /></figure><p>We created a recipient and prefunded with 5 ether. This is the address the manager is trying to send the money for the spend request to. We added a user to the Campaign then created the spend request stating explicitly that the msg.sender (manager) is the sender of the transaction and asserted that we now have 1 spendRequest created.</p><blockquote>Note that the vm.startPrank used above is essentially the same thing with vm.prank. vm.prank only specifies the next immediate transaction while vm.startPrank specifies everything in between the start and stop as being sent by the user.</blockquote><p>We then test that manager cannot finalize a spend request if majority of the funders has not approved it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fdjL7R24t3G7DizF9H0z7w.png" /></figure><p>We expect a revert when we call the <em>finalizeRequest</em> function for the first spend request created when it has not been approved.</p><p>Finally, we’ll test that a spend request that has been approved by majority can be finalized by the manager. I added another getter function to the Campaign contract that looks like below and used in my test</p><pre>function getSpendRequestCompletedStatus(<br>  uint index<br>) public view returns (bool) {<br>  return s_spendRequests[index].complete;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i88u1edATLhyTwK3TyF3nA.png" /></figure><p>We once again create a campaign, asserted that it has not been completed, then our funder approved it, the manager finalized it which sent the ethers to the desired address, then we asserted that the spend request has been completed and that the recipient balance has increased.</p><p>Great, so far we’ve written very extensive tests for our kickstarter contract, and there are still some areas to test, but I’ll leave that up to you to extend the existing test suites. We can actually see how much of our code the test covers by running the command</p><pre>forge coverage</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1KTg5MYBcJ_W9pArp-cwaQ.png" /></figure><p>Wow, we were able to write test that covers about 96% of our Kickstarter contract 🤩🥳. That’s quite good for right now.</p><p>You can find the code for the complete test suite below</p><pre>// SPDX-License-Identifier: MIT<br><br>pragma solidity ^0.8.21;<br><br>import {Test, console} from &quot;forge-std/Test.sol&quot;;<br>import {DeployCampaign} from &quot;../script/DeployKickstarter.s.sol&quot;;<br>import {Campaign} from &quot;../src/Kickstarter.sol&quot;;<br><br>contract KickstarterTest is Test {<br>    uint constant MINIMUM_AMOUNT = 50;<br>    Campaign campaign;<br>    address USER = makeAddr(&quot;ifeoluwa&quot;);<br>    uint constant INITIAL_BALANCE = 50 ether;<br><br>    function setUp() external {<br>        DeployCampaign deployCampign = new DeployCampaign();<br>        deployCampign.setAmount(MINIMUM_AMOUNT);<br>        campaign = deployCampign.run();<br>        vm.deal(USER, INITIAL_BALANCE);<br>    }<br><br>    function testManagerAddress() public {<br>        assertEq(campaign.getManager(), msg.sender);<br>    }<br><br>    function testMinimumAmountIs20() public {<br>        assertEq(campaign.getMinimumContribution(), MINIMUM_AMOUNT);<br>    }<br><br>    function testCannotContributeLessThanMinimumAmount() public {<br>        vm.expectRevert();<br>        campaign.contribute{value: 20}();<br>    }<br><br>    function testFundersAndAmountFunded() public {<br>        vm.prank(USER);<br>        campaign.contribute{value: 500}();<br>        assertEq(campaign.getFunderAmount(USER), 500);<br><br>        vm.prank(USER);<br>        campaign.contribute{value: 200}();<br>        assertEq(campaign.getFunderAmount(USER), 700);<br>    }<br><br>    function testManagersCanCreateSpendRequest() public {<br>        address RECIPIENT = makeAddr(&quot;recipient&quot;);<br>        vm.deal(RECIPIENT, 5 ether);<br><br>        assertEq(campaign.getSpendRequestCount(), 0);<br><br>        vm.startPrank(USER);<br>        campaign.contribute{value: 200000}();<br>        vm.stopPrank();<br><br>        vm.prank(msg.sender);<br>        campaign.createSpendRequest(<br>            &quot;some description&quot;,<br>            10000,<br>            payable(RECIPIENT)<br>        );<br>        assertEq(campaign.getSpendRequestCount(), 1);<br>    }<br><br>    function testCannotFinalizeIfNotApproved() public {<br>        address RECIPIENT = makeAddr(&quot;recipient&quot;);<br><br>        vm.startPrank(USER);<br>        campaign.contribute{value: 200000}();<br>        vm.stopPrank();<br><br>        vm.prank(msg.sender);<br>        campaign.createSpendRequest(<br>            &quot;some description&quot;,<br>            10000,<br>            payable(RECIPIENT)<br>        );<br><br>        vm.expectRevert();<br>        vm.prank(msg.sender);<br>        campaign.finalizeRequest(0);<br>    }<br><br>    function testCanFinalizeIfApproved() public {<br>        address RECIPIENT = makeAddr(&quot;recipient&quot;);<br><br>        vm.startPrank(USER);<br>        campaign.contribute{value: 200000}();<br>        vm.stopPrank();<br><br>        vm.startPrank(msg.sender);<br>        campaign.createSpendRequest(<br>            &quot;some description&quot;,<br>            10000,<br>            payable(RECIPIENT)<br>        );<br>        vm.stopPrank();<br><br>        assertEq(campaign.getSpendRequestCompletedStatus(0), false);<br><br>        vm.startPrank(USER);<br>        campaign.approveRequest(0);<br>        vm.stopPrank();<br><br>        vm.prank(msg.sender);<br>        campaign.finalizeRequest(0);<br><br>        assertEq(campaign.getSpendRequestCompletedStatus(0), true);<br>        assertEq(RECIPIENT.balance, 10000);<br>    }<br>}</pre><p>That would be all for this article and I hope you found it helpful as it explains the basics of testing with foundry and some of the tools and cheatcodes that are provided when writing tests. Please like, share, comment and follow. I’ll see you in the next, bye for now.👍</p><p>You can find the next step below.</p><p><a href="https://medium.com/@ifeoluwaolubo/smart-contract-interaction-with-the-outside-world-chainlink-vs-foundry-73dafe4f653e">Smart Contract Interaction With The Outside World: Chainlink vs Foundry.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d86fcc5ca33e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/web-3-digitals/smart-contract-testing-the-foundry-way-d86fcc5ca33e">Smart Contract Testing: The Foundry Way</a> was originally published in <a href="https://medium.com/web-3-digitals">Web 3 Digitals</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intro To Foundry: The Kickstarter Smart Contract]]></title>
            <link>https://medium.com/coinmonks/intro-to-foundry-the-kickstarter-smart-contract-888a534be0b0?source=rss-8e81ec09f3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/888a534be0b0</guid>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[kickstarter]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[foundry]]></category>
            <dc:creator><![CDATA[Ifeoluwaolubo]]></dc:creator>
            <pubDate>Wed, 25 Oct 2023 22:32:04 GMT</pubDate>
            <atom:updated>2023-11-04T11:03:43.910Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X5JnJUzf0bkUAxxkB0MZ6g.png" /></figure><p>According to their official documentation <a href="https://book.getfoundry.sh/">here</a>, <em>Foundry is a smart contract development toolchain.</em> This simply means that with foundry we can manage our dependencies, compile our projects, run extensive testing, carry out deployments and interact with the blockchain from the Command Line, and all of these is done with Solidity Scripts 😋. Interesting right? Wait till you hear the best part.</p><blockquote>Foundry is blazingly fast (probably the most fastest smart contract development tool right now), written in <em>Rust</em> and is also the framework of choice for smart contract security engineers and auditors.</blockquote><p>In previous articles we’ve written some very basic smart contracts to help us understand Solidity, but from here on, we’re going to be solving real problems and also solve it like its done in the real world using standard tools and technologies. Writing our contracts in remix is great since we can easily test and deploy the contracts, but remix has its limitations when it comes to developing production grade applications which is why we’re using a more suitable tool called foundry. I’ll also be using VS Code as my text editor.</p><h4>Project idea</h4><p>So what are we building? In this article, we’ll be solving the main issue that’s plagued the kickstarter application. For those that are not familiar with what kickstarter is, it’s a place where people who have ideas for building some products but needs funding goes to and some other people funds those ideas and take shares from the proceedings of the product (In a nutshell 😅). You can find more details on the website <a href="https://www.kickstarter.com/">here</a>.</p><p>I believe we can already perceive the problems that this would potentially bring. People with evil intents can actually just go to the platform claiming to have some product idea, gather fundings and then just take flight with all the money ☹️. Now how can we solve this issue? We know (without a doubt) that the blockchain solves the problem of trust, in the sense that we don’t need to trust a third party before we can make transactions with them or expect them to behave appropriately. Hence the blockchain technology would be a very good way to actually solve the issue of trust that’s plagued the kickstarter application and that’s exactly what this article aims to achieve.</p><h4>Getting started.</h4><p>Now that we’ve gotten the administrative stuff out of the way, let’s actually look at how we would go about installing foundry and getting started with writing our smart contracts. <br>Installing foundry is not overly complicated, the installation process together with the documentation can be found <a href="https://book.getfoundry.sh/">here</a>. Windows users might need to consider using WSL for the installation, but the command to run is</p><pre>curl -L https://foundry.paradigm.xyz | bash</pre><p>This would install <em>foundryup, </em>then running <em>foundryup</em> would install <em>forge, cast, anvil </em>and <em>chisel, </em>which are the tools we would use for our entire application development lifecycle<em>.</em></p><p>I’ve installed foundry and ran the <em>foundryup command as below</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7lnT0A-K052aV7y0ubjvyw.png" /><figcaption>foundryup command</figcaption></figure><p>I’ll be working in an empty directory called kickstarter.</p><p>Like I said initially, the foundryup command installed 4 tools that have different purposes when working with foundry. The first one we would be working with is <em>forge. </em>We can run the command below to initialise a bare bones foundry project.</p><pre>forge init</pre><p>This creates a few folders and files as seen below in VS Code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*w9gTkAaeAl3yqH78wse8cw.png" /><figcaption>forge init command</figcaption></figure><p>By default, we have the <em>src</em>, <em>script</em> and <em>test</em> folders each containing a counter related smart contract. Go ahead to delete these 3 files and create a new solidity file in the src folder called <em>kickstarter.sol.</em> We won’t be doing any testing in this article as that would be covered extensively in my next article. The only content in the kickstarter file is just the SPDF configuration, solidity version and our actual contract declaration called <em>Campaign.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*01cypfCNGtFJCAknc528eQ.png" /></figure><p>By default VSCode does not provide intellisense to our solidity files, for this we’ll have to install an extension from the market place. I prefer the one by Nomic Foundation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VZ9i5X4I3vSO9DKuNhsNxw.png" /></figure><h3>Our Contract Logic</h3><p>The specifications for our contract would be as follows:</p><ul><li>A <em>manager</em> who is the one looking for funding would be able to specify the minimum contribution for anyone wanting to fund their idea.</li><li>Other users can contribute to the idea if they do meet the required amount specified by the <em>manager.</em></li><li>Managers won’t get the money paid to them directly, instead it’s stored on the blockchain.</li><li>Whenever the manager needs some money to fund a specific part of the project, they’ll create a spending request (eg. If the project idea is a car, then the manager might need to buy engines, hence they create spend request for it).</li><li>The spending request would undergo approval by the funders of the ideas.</li><li>If most funders approves the spend request, then the amount is sent to the account of whoever needs to receive the payment (eg whoever sells the car engines).</li><li>A funder that does not partake in the approval process is taken as false. <em>ie they do not approve the spend request</em>.</li></ul><blockquote>Note: At no point is the money being sent directly to the manager. This way the funders can also have a clear overview and track how their moneys were spent.</blockquote><h3>Actual contract code</h3><p>Now that we’ve understood the clear picture for our contract, let’s get to the actual implementation. Obviously, the first thing to do would be to handle the logic that happens when the contract is created by the manager (emphasis on “created by the manager”).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K3_RR9iPVvTbOccvqAYebQ.png" /></figure><p>We created a constructor function which takes in a uint for the minimum amount needed to join the campaign. We created 2 immutable variables called <em>i_manager </em>and <em>i_minimum_contribution, </em>then set the i_manager variable to whoever created the contract and set the i_minimum_contribution to whatever they passed in. <br>By convention I set the 2 variables as private (this helps to save more gas) and created getter functions for whenever I might need to read the values they stored.</p><p>The <em>immutable</em> keyword might be new to us as of now, but it just simply means that the value stored in that variable would not mutated (changed). It is similar to the <em>constant </em>keyword as well except that we have to set the value for a constant variable immediately it is initialised.</p><p>From my previous article, I stated that any variable declared in the top level of the contract is a <em>storage </em>variable, but this is not the case for immutable and constant variables.</p><blockquote>immutable and constant variables are stored in the bytecode of the contract itself and not on the blockchain. This way, they greatly reduce gas spent from reading their values.</blockquote><p>Alright, moving on we’ll need a way for other people to join the campaign and make their different contributions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jxH1fQ3nRca12SmAIPljgg.png" /></figure><p>We created 2 new storage variables <em>s_funders </em>and <em>s_fundersCount </em>to keep track of the funders of the campaign with their contribution amount. The function is marked as payable. This means that it can accept payment (in this case ethers) and we access the value using the <em>msg.value </em>global variable.</p><p>Next we’ll work on the create spend request function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hd1qvRV1UNIxW2mcU0E3bw.png" /></figure><p>We have quite some things going on here. First we created a struct for our request type, then created a function for a manager to create the spend request, we require that only the manager can create requests. The recipient passed as the function parameter in the <em>createSpendRequest </em>function is set to payable since we intend to send money to this address if the spend request is approved by the funders.</p><blockquote>Notice how the <em>spendRequest </em>variable is set to storage? This indicates that we are trying to mutate the actual value at the specified index stored in the s_spendRequests<em> </em>variable.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*fjBvK2f9LjArw9ZW9-VeqA.png" /></figure><p>In our approve function, we pass in the index of the spend request as a parameter and get the request at that index storing it in a storage variable (again, indicating that it would mutate the value at that index). We then require that the user calling the approval function has actually contributed a valid amount to the campaign and also that they had not voted initially for the spend request.<br>We then increase the approvalCount variable and set the address of the funder as true to show they have voted.</p><p>Since we need a way to track the funders that has approved a spend request, we modified our request struct to include an approvals mapping as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*dnOdDN6YHSdKvTlOvyuZGg.png" /></figure><p>The final thing to do would be to finalise the spend request and this would be done only by the manager depending on whether or not the request has been approved by the funders of course.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yChPCNILJRscA0Hkqh5zzA.png" /></figure><p>Here we also require that only the manager can call this function (a little modification to this soon), get the spend request, then require that more than half of the funders of the campaign has actually voted and also require that the spend request has not been completed initially.</p><p>Once all the checks above passes, we then transfer the money (ethers in this case) to the recipient and complete the spend request.</p><p>Now the modification we can make is to remove the <em>require(msg.sender == i_manager) </em>and put it inside a <em>modifier</em> which we can then use wherever it’s needed. This helps us to reduce repetition since we are doing exactly the same thing in the <em>createRequest</em> and the <em>finalizeRequest</em> function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*uWlWwBnuXv1Nql2MuLsyCg.png" /></figure><p>We create our modifier as above and then use them in the <em>createRequest</em> and <em>finalizeRequest</em> like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hcstN8jjHqGhX4P9PYzi_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*iUVqabEGEOAS5Fx_u5Z3yA.png" /></figure><p>Great, now our campaign contract has all the requirements we need. One thing to note though is that the entire contract we’ve written so far only applies to a single campaign. So in essence, anytime someone has an idea that needs funding and decides to use our application, we’ll have to manually deploy another campaign.</p><h4>Importing files</h4><p>So far we’ve been working with just one solidity file that contains all of our codes, but usually, we’ll be needing to import some other contract into our application and we can do that by using the <em>import </em>keyword in solidity.</p><p>To solve the manual deployment issue stated earlier, one way to go about it is to create another contract that would be responsible for deploying our campaign contract (Yes, a contract can deploy another contract 😅). So we’ll just deploy that single contract and anytime someone wants to use our application, this contract deploys a campaign contract for them.</p><p>Inside our src folder, lets create a <em>Deploy.sol </em>file with the following content:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jhSFGt3Mn1ocHRDfwVYvYA.png" /></figure><blockquote>A contract that creates other contract is called a factory. Hence our DeployCampaign contract above is a factory.</blockquote><p>This contract is fairly simple, as we only have 2 functions. The first creates the campaign and passes the minimum value specified, we <em>cast</em> the campaign with the <em>address </em>keyword and this returns the address of where the contract was deployed. We then save this in a storage variable for the array of addresses of all the deployed campaigns.<br>The second function simply just returns all the deployed contracts.</p><blockquote>Notice the syntax used to import the campaign from the Kickstarter.sol file since they are in the same directory.</blockquote><p>Now we have an issue. In the campaign contract, we are storing the address of whoever creates the contract in the <em>i_manager</em> variable. The issue with our current setup is that now, the <em>DeployCampaign</em> contract is actually what is creating the campaign contract so the address stored in the <em>i_manager</em> variable won’t be the address of the manager but instead it’ll be the address of the <em>DeployCampaign</em> contract. Whew 😮‍💨. <br>When we get to testing, we’ll see more about this.</p><p>Let’s modify our campaign contract so that it now accepts not just the minimum contribution, but the address of who creates the contract as well.<br>The updated campaign constructor looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*o9lObxzKZFt_-_oQFsHtJA.png" /></figure><p>while the DeployCampaign contract now looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7jot_WAv4gapE2XVHLQqZA.png" /></figure><p>Now we’re all set. Complete code for the kickstarter and deploy files are now:</p><pre>// SPDX-License-Identifier: MIT<br><br>pragma solidity ^0.8.21;<br><br>contract Campaign {<br>    address private immutable i_manager;<br>    uint private immutable i_minimum_contribution;<br>    mapping(address funder =&gt; uint amount) private s_funders;<br>    uint private s_fundersCount;<br><br>    struct Request {<br>        string description;<br>        uint value;<br>        address payable recipient;<br>        bool complete;<br>        uint approvalCount;<br>        mapping(address funder =&gt; bool approval) approvals;<br>    }<br><br>    uint private s_numRequests;<br>    mapping(uint index =&gt; Request spendRequest) private s_spendRequests;<br><br>    modifier require_owner() {<br>        require(msg.sender == i_manager);<br>        _;<br>    }<br><br>    constructor(uint minimum, address manager) {<br>        i_manager = manager;<br>        i_minimum_contribution = minimum;<br>    }<br><br>    function contribute() public payable {<br>        require(msg.value &gt;= i_minimum_contribution);<br>        s_funders[msg.sender] += msg.value;<br>        s_fundersCount++;<br>    }<br><br>    function createSpendRequest(<br>        string memory description,<br>        uint value,<br>        address payable recipient<br>    ) public require_owner {<br>        Request storage spendRequest = s_spendRequests[s_numRequests++];<br>        spendRequest.description = description;<br>        spendRequest.value = value;<br>        spendRequest.recipient = recipient;<br>        spendRequest.complete = false;<br>        spendRequest.approvalCount = 0;<br>    }<br><br>    function approveRequest(uint index) public {<br>        Request storage request = s_spendRequests[index];<br><br>        require(s_funders[msg.sender] &gt; 0);<br>        require(!request.approvals[msg.sender]);<br><br>        request.approvalCount++;<br>        request.approvals[msg.sender] = true;<br>    }<br><br>    function finalizeRequest(uint index) public require_owner {<br>        Request storage request = s_spendRequests[index];<br><br>        require(request.approvalCount &gt; (s_fundersCount / 2));<br>        require(!request.complete);<br><br>        request.recipient.transfer(request.value);<br>        request.complete = true;<br>    }<br><br>    function getManager() public view returns (address) {<br>        return i_manager;<br>    }<br><br>    function getMinimumContribution() public view returns (uint) {<br>        return i_minimum_contribution;<br>    }<br><br>    function getfundersCount() public view returns (uint) {<br>        return s_fundersCount;<br>    }<br>}</pre><pre>// SPDX-License-Identifier: MIT<br><br>pragma solidity ^0.8.21;<br><br>import {Campaign} from &quot;./Kickstarter.sol&quot;;<br><br>contract DeployCampaign {<br>    address[] private s_deployedCampaigns;<br><br>    function createCampaign(uint minimum) public {<br>        address campaign = address(new Campaign(minimum, msg.sender));<br>        s_deployedCampaigns.push(campaign);<br>    }<br><br>    function getDeployedCampaigns() public view returns (address[] memory) {<br>        return s_deployedCampaigns;<br>    }<br>}</pre><h3>Compiling and Deploying our contracts</h3><p>Deploying our contract locally is very easy once we have foundry setup. <br>We’ve briefly seen how to run a command with <em>forge, </em>and there are still a few others, but for now we are going to spin up a local blockchain. We can do that by just running the <em>anvil </em>command like so</p><pre>anvil</pre><p>This should print out the following on your terminal</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L5d7AVWtaraaJYHmTEdTbA.png" /></figure><p>By default (and similar to remix) anvil has some accounts created for us to use and these accounts has all been pre-funded, in this case 10,000 ethers each. We also see our private keys and our account Mnemonic.</p><blockquote>Note: The private key at index 0 corresponds to the account at index 0 and so on.</blockquote><p>We also see that our local blockchain network is running on port 8545<br>To compile and deploy our contract using the private key at index 0, the command to run is</p><pre> forge create DeployCampaign --rpc-url http://localhost:8545 --private-key 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80</pre><p>The <em>rpc-url</em> specifies where we want to deploy our contract to, in this case it’s our locally running anvil chain and the <em>private-key</em> specifies the account (at index 0) that is actually making the deployment. We should get the output as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*15EbjVqbxNgK2PD2z6QhEg.png" /></figure><blockquote>Notice how the deployer corresponds to the account at index 0</blockquote><p>Ideally, the way we’ll want to deploy our contracts using foundry would be to write deployment scripts, but we’ll talk more about that in the next article.</p><p>Alright then, we’ve definitely covered quite a lot in this article and got our hands dirty with working with foundry and the tools it provides, but there are still more that needs to be covered in terms of deployment and testing, all of which would be covered in the next article.</p><p>If you enjoy this article please give a clap, share, comment and follow. I’ll see you in the next. 🚀🤩</p><p>You can find the next article here ⬇️</p><p><a href="https://medium.com/@ifeoluwaolubo/smart-contract-testing-the-foundry-way-d86fcc5ca33e">Smart Contract Testing: The Foundry Way</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=888a534be0b0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/intro-to-foundry-the-kickstarter-smart-contract-888a534be0b0">Intro To Foundry: The Kickstarter Smart Contract</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Diving Deeper Into Solidity]]></title>
            <link>https://medium.com/coinmonks/diving-deeper-into-solidity-aeb0259232ec?source=rss-8e81ec09f3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/aeb0259232ec</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Ifeoluwaolubo]]></dc:creator>
            <pubDate>Sat, 14 Oct 2023 17:09:39 GMT</pubDate>
            <atom:updated>2023-10-27T08:22:41.155Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l56VdSlO1uF6nOpqa0yOpw.jpeg" /><figcaption>Deeper into solidity</figcaption></figure><p>Before we actually start writing smart contracts that simulates the different applications we might want to build in the real world, there are still some fundamental ideas in solidity that we’ll be needing to understand.</p><p>In my previous article, we started from having no knowledge of solidity whatsoever, to actually writing some solidity codes, understanding some basic types in solidity, using an online editor (remix) to quickly and easily write and test our solidity codes and then ultimately deploying our smart contracts and interacting with them, but there are still some concepts we need to know before we start working with solidity in the real world. You can find the link to the previous article here ⬇️:</p><p><a href="https://medium.com/coinmonks/solidity-for-dummies-736312af0dfe">Solidity For Dummies.</a></p><p>We’ll still stick to using remix editor in this article cause I’ll prefer us understanding just the new concepts rather than trying to grasp a new environment, and with that said, Let’s get started.</p><h3>More solidity types</h3><p>We are already familiar with some solidity types (eg uint, bool, string and addresses) but there are some more advanced types that we must know and what other way to learn new things than building an application with it. Thats what we intend to do, we’ll be building a SimpleStorage contract to get us familiar with these advanced types.</p><p>Once again head over to your remix editor at <a href="https://remix.ethereum.org/">https://remix.ethereum.org/</a> if you want to follow along, then create a new file called SimpleStorage.sol inside of your contracts folder. You can create a new file by clicking on the contracts folder and clicking the create new file icon like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*uapzVM3Ql9DCUuNkGnTURQ.png" /><figcaption>Create a new solidity file</figcaption></figure><p>Inside the file, we would just have some boiler plate code for our Simple Storage contract. We created a contract called SimpleStorage and it currently has one public variable which stores whatever number was inputted by whoever deployed the contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_bMKloSLVraa7j7AtzCaPQ.png" /><figcaption>Simple storage boiler plate</figcaption></figure><p><strong>Arrays:</strong><br>Supposed our contract was opened to the outside world in the sense that other people can change the value stored in the owner number and lets say we want to have a way to store the addresses of people that have changed the owner number, then one way to do that is by creating a store function which takes a number as an argument, sets it to our ownerNumber variable and then we also store the address of whoever called the function in a type called an Array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vE9BmDCJHii_5eRjIJI2sA.png" /></figure><p>Here we created a dynamic array called storedAddresses that adds the address of the user calling the store function into it. Like Javascript, we can add elements into solidity dynamic arrays using the push method like we see in the code above. There are 2 types of arrays in solidity, the dynamic array and the static arrays. The number of elements in a static array is fixed while there is no limit to the number of elements we can add into the dynamic array. Arrays can be used to store a collection of elements that are of the same type. In our case, we’re storing a collection of addresses.</p><blockquote>In Solidity, you cannot push or add elements to a static array because a static array has a fixed size defined at compile time, and this size cannot be changed. Static arrays are meant to have a fixed, predetermined number of elements that you specify at the time of declaration, and you cannot modify this size after deployment.</blockquote><p>Let’s test our contract. Click on the deploy and run transactions button and pass an initial value of 675 as the _ownerNumber</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*YrgPgIcB5BuSolr-lAky9A.png" /></figure><p>Once our contract is deployed, we can see that the value of our _ownerNumber is 675</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*RazmbMzOExOQUYRkauMb-Q.png" /></figure><p>Select a different account and call the store function with this account. This should store the address and change the value of _ownerNumber variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*ngQL_Q7D8x69nxntY9ktMQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*wSa7f3Rlkt18GPr36AKvwQ.png" /></figure><p>As you can see above, we can access the elements in an array by using its index. Just like Javascript, the indexing starts at 0.</p><p><strong>Maps:<br></strong>Our contract isn’t doing much right now cause it doesn’t really make sense that anyone should have the ability to change the number set by whoever deployed the contract. Let’s modify our contract so each user has their own number stored. We could create a new array that stores their numbers, then whenever we want to find the number for a particular address we’ll have to loop through the array and get the value.</p><p>Although this could potential work, it’s a really bad idea because of the gas that would be spent for processing that transaction and we’ll talk more about this soon, but for right now, we want to try as much as possible to avoid an computationally heavy transactions, hence “a for” is a <strong><em>very bad approach.</em></strong></p><blockquote>Time complexity for searching in an array is O(n)<br>What this means is for the worst case, we’ll have to loop through every element in the array before finding the value we’re interested in.</blockquote><p>This problem is easily solved by another data type called the <em>Map. </em>A map is basically a key value store (similar to javascript), but solidity maps uses the hashmap datatype. What this means is that we cannot get all the keys of a Map and we cannot get all the values of a map. A key only points to the value stored and that’s it.</p><blockquote>Time complexity for searching in a map is O(1) or constant time</blockquote><p>Let’s now change our code to use maps instead</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sRSgHV7KEez5VheRddFZNw.png" /><figcaption>Mapping in solidity‘</figcaption></figure><p>We create maps by using the <em>mapping </em>keyword. Notice the 2 variations of maps in the code. Essentially they do the same thing, but the second variation is what I prefer since it gives me more details on what the type holds (address stores the user’s address and the uint stores the user’s number). Lets deploy our contract again</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*drX79Enceczpj0wZAOsncw.png" /></figure><p>We set the value of 89766 to the ownerNumber when deploying the contract, then stored a new number into the addressToNumber variable. We get the user’s address then use it to find their number.</p><p><strong>Structs:<br></strong>What if we want to make our contract more robust so that instead of storing just the user’s address, we would store their name, number and address. Solidity provides a way for us to define custom types and use in our contract, so that’s exactly what we’ll be doing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ARSN3xzFiPSrP5mYXrQRjQ.png" /><figcaption>Struct type definition</figcaption></figure><p>Here we created our custom type called <em>Person</em> using the <em>struct </em>keyword. Our Person type has a name, number and _address. Then on line 16, we are basically saying we want an array of elements called people where each element is a person type. Let’s see how we would go about using this new type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ma6fpWbDVrTLVG6MbhiGQ.png" /></figure><p>We created a public addPerson function that takes two arguments, name and number, creates the <em>person </em>using these arguments (with the address) then pushes them to the people array. We might be unfamiliar with the memory keyword as of now, but we’ll get to that in a bit. Once again, lets test our code. Deploy your contract and set any number to the ownerNumber variable, I’ll be using 123.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*wAb5eSx4BJNsMkn061Uziw.png" /></figure><p>After deploying the contract, I added a new person with the name <em>Ifeoluwa </em>(in quotes) and a number 43, then the people array at index 0 now returns the appropriate results as expected.</p><p>We’re about done with the basic functionalities of our contract, but there are still a few concepts I want to talk about.</p><h3>Memory, Storage and Calldata</h3><p>Earlier in our addPerson function, we used the memory keyword in the string name and in the Person type. Just what exactly is this doing?</p><p>First let’s talk about the <em>storage</em> keyword. A storage variable is a variable that’s stored on the blockchain itself (they cause the state of the blockchain to change). Every variable defined in the top level of our contract is a storage variable, so in essence ownerNumber, storedAddresses, addressToNumbers and people variables are all storage variables.</p><p>The <em>memory</em> and <em>calldata</em> keyword works almost the same way. The big difference between them and the <em>storage</em> keyword is that, they are used as a short term storage and only exist for the duration of a function call, <em>ie</em> they only store data temporarily. Inside a function, most variables are memory variables.</p><p>In Solidity, when passing array or struct types as function parameters, you need to specify the data location as either “memory” or “calldata” to indicate where the data is stored. Under the hood, string variables uses array of bytes (byte is another data type) to store its values, which is why we specified the data location as memory. We could have equally specified it as <em>calldata </em>and it would have worked fine like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wxU3RQiTFEK3fc2R_BzSsg.png" /></figure><p>The major difference between calldata and memory is that calldata is only used when we pass parameters to a function.</p><blockquote>Storage variables are stored on the blockchain.<br>Memory and calldata variables are stored temporarily.<br>Calldata is only used when passing parameters.<br>We need to specify the data location when passing parameters of type Array or Struct to a function.</blockquote><p>I hope we can now easily differentiate the different use cases for <em>storage, memory </em>and <em>calldata </em>variables<em>.</em></p><h3>Gas and Transactions</h3><p>Transactions are exactly what they are in the crypto world, processing some sort of payments. When we deploy our contracts, or call some function that changes the state of some storage variable, we are submitting a transaction. If we look closely at the 2 functions <em>store </em>and <em>addPerson </em>that we have in our contract, we’ll realise that they both mutate (change the state) of some storage variable, hence a transaction is submitted for them to be mutated.</p><p>For transaction to be processed, it has to be mined (I talked about this in my earlier article) and that is where the concept of gas comes about. For our transaction to be mined by the miners, we need to pay gas (think of it as a transaction fee) so that our transaction can be processed. The amount of gas that’s paid depends on the computation that the function computes. The more the computation, the more the gas. This was the reason why we changed our data type to a mapping when working on our contract because to read a value for a mapping is less expensive than looping through an array to find a value.</p><h3>View vs Pure functions</h3><p>A function that only reads values does not involve a transaction hence no gas is needed to be paid. A function that reads the value of a storage variable is specified as <em>view </em>and a function that reads some constant (for instance) is specified as <em>pure. </em>Lets take a look at the code below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xoCbkd-o1cFKvO4wKrJ12w.png" /><figcaption>View and Pure functions</figcaption></figure><blockquote>Notice how we specified memory as the data location to the returned person array in the getPeople function?</blockquote><p>In the code above, the getPeople function reads the value of our people storage variable, while the getNumber just returns some constant. Suppose we mark the function as pure and still try to return a storage variable, we get the error like below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CA2-JenoRwiMdgj4frg2kQ.png" /></figure><p>Also if we try to mutate the values of a storage variable in a function that is marked as pure or view, we get errors</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RXdQm0QTgpMok5RTFbdoNQ.png" /></figure><blockquote>So we use view and pure functions for only reading values.<br>A pure function cannot be used to read a storage variable.</blockquote><p>Alright guys, that would be about it for now. In this article, we have been able to dive deeper into solidity to understand some more advanced types, some concepts like gas and transactions, memory, calldata and storage, view and pure functions etc. In upcoming articles, we’ll take what we’ve learnt so far and start applying them to building some real world applications.</p><p>I hope you found this article helpful in some way. Please give a clap, comment and follow, and I’ll see you in the next article. 🚀🚀🤩</p><blockquote>Find the next step below 👇🏻👇🏻</blockquote><p><a href="https://medium.com/@ifeoluwaolubo/intro-to-foundry-the-kickstarter-smart-contract-888a534be0b0">Intro To Foundry: The Kickstarter Smart Contract</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aeb0259232ec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/diving-deeper-into-solidity-aeb0259232ec">Diving Deeper Into Solidity</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solidity For Dummies.]]></title>
            <link>https://medium.com/coinmonks/solidity-for-dummies-736312af0dfe?source=rss-8e81ec09f3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/736312af0dfe</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[remix]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Ifeoluwaolubo]]></dc:creator>
            <pubDate>Sat, 07 Oct 2023 13:08:17 GMT</pubDate>
            <atom:updated>2023-10-27T08:24:14.990Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*JToinc3s6bIPwx0C.png" /></figure><p>In my previous article, I talked about how I journeyed into the new tech space of web3 and gave some details from my findings on the blockchain technology, a little background on Bitcoin itself, the Ethereum network, transactions etc. You can find the article here ⬇️:</p><p><a href="https://medium.com/coinmonks/journey-into-web3-4f4a1ddd9a5d">Journey Into Web3</a></p><p>I noted that the main difference between Bitcoin and Ethereum is that Bitcoin was only used for the transfer of monetary values from peer to peer while Ethereum broadens the scope for the different applications we can apply the blockchain technology to build.</p><p>The main thing that makes this possible is the idea of S<strong><em>mart Contracts </em></strong>which are just a piece of code that lives on the Ethereum blockchain. The smart contract is what instructs the blockchain on how to behave with respect to the application or project it has been written for. Think of it as an account thats being controlled by code. There are many smart contract languages out there but the most popular by far and most widely used (and the one I used) is called <strong>Solidity. </strong>This article intends to introduce you to the most basic underlying concepts for understanding and writing solidity codes. Let dive right into it 🚀.</p><blockquote>Although I try to make the article quite simple and easy to understand, having the basic knowledge of at least one programming language would be very beneficial.</blockquote><h3><strong><em>Solidity vs JavaScript…</em></strong></h3><p>A lot of us are familiar with JavaScript but if you’re not, that’s fine as well. JavaScript is a language for the web especially for building the frontend of applications. I consider Solidity to be very dis-similar to JavaScript (based on some underlying implementations) and still very similar to JavaScript (based on syntax), except for the fact that solidity is a statically typed language.</p><h3>Remix Editor</h3><p>The quickest way to get to writing solidity codes is by using an online editor called <em>remix </em>which makes it very easy to write and quickly test out solidity codes. Go to <a href="https://remix.ethereum.org/">https://remix.ethereum.org/</a> to get started, you should arrive at an editor that looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-zB_5CO3sjJbUVAw_DLC4A.png" /></figure><p>Remix comes with a test Ethereum network which we can easily use to deploy and test out our written smart contract codes. It also has some accounts that has been pre-funded with 100 ethers each which we can use while testing. For this article, all our codes would be written in the 3_Ballot.sol file that’s located in the contracts folder. Clear out what is in the file and write the 2 lines you see in the code below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QmQnJPJIVKL5OYco9AnAmQ.png" /></figure><p>The .sol in the file extension is the extension for solidity files. Inside this file, we added the <em>// SPDX-License-Identifier: MIT, </em>to ignore whatever warning the editor might be giving.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*R--gDM9d6l-eQPRRsJDcRA.png" /></figure><p>On the left menu select the S shaped icon and make sure to select the same compiler version as you have set in your code. In this case, it is 0.8.21. Also make sure that you select the auto compile check box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*ZpPeZrXXIWowZCbnjNZV_g.png" /></figure><p>Under the S shaped icon we have the debug and run transactions icon. This is where we’ll come to deploy and test our codes. You can verify that you have multiple accounts in the <em>accounts </em>dropdown and they each have 100 ethers in them. Also make sure you have a Remix VM selected, in our case its Shanghai.</p><h3>The Solidity Compiler</h3><p>Our solidity code is not being executed directly on the blockchain. Instead something called the <strong>solidity compiler</strong> compiles the source code and spits out a Bytecode and an ABI (Application Binary Interface). The bytecode is what is then deployed on the blockchain, while the ABI is what we use to communicate or interact with what has been deployed on the blockchain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ncndxcaxEKlSygae3mc68Q.png" /><figcaption>Solidity compiles to a bytecode and an ABI</figcaption></figure><p>When building full featured Web3 projects, we would often need a frontend (eg JavaScript code) that interacts with the blockchain and the only way this said interaction can occur is by using our ABI. Without it, we can’t possibly communicate with what was deployed on the blockchain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*IcBZHYbAZvd2Z08F9wiiKg.png" /><figcaption>JavaScript can’t understand the bytecode</figcaption></figure><h3>Writing Solidity Codes</h3><p>Now that we’ve gotten some administrative stuff out of the way, we’ve finally reached the point where we can actually start writing some solidity code. Consider the code below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*tffBR6NaapxGrJsDftasAw.png" /><figcaption>Solidity Contract declaration</figcaption></figure><p>The code on line 3 tells the solidity compiler that we are about to write solidity code and the version it should use for compiling. The code on line 5 is where the fun starts, this is where we declare our smart contract, giving it a name of MailBox. We are attempting to build a sort of email application, but on the blockchain of course 😁. Our contract would be able to create a mail and set a default message to it, we can chose to set a new mail and even retrieve what the current mail is. Nothing crazy for now, just enough to get our hands dirty while understanding some basic fundamentals of solidity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*9Penk5Xsebp-PdKwgplmEw.png" /><figcaption>Some basic types.</figcaption></figure><p>In the code above, we are creating 4 variables that would be used in our email application. The first variable is a string type and this holds the actual message of the mail. The public keywords means that the variable should be exposed and seen outside of our contract. We’ll see more details on this soon.</p><blockquote>Note that the senderAddress variable has no public keyword attached to it. This is intensional and is used for demonstration purposes.</blockquote><p>For now, we are only using the basic variable types similar to other programming languages like <em>string</em>, <em>uint</em> (or <em>number</em> type in JavaScript), <em>boolean </em>(true or false) and <em>address </em>type which is one we’re probably new to cause it’s specifically used in solidity. The address type holds addresses to different accounts. Examples of what the address type looks like are</p><blockquote>0x5B38Da6a701c568545dCfcB03FcB875f56beddC4<br>0x4B20993Bc481177ec7E8f571ceCaE8A9e22C02db</blockquote><p>The <em>uint</em> type has other variations which stores different sizes of numbers (uint8, uint16, uint32, uint256 etc).</p><blockquote>The default uint type refers to uint256.<br>The 4 variables are set to their default types by default, which is<br>“” for string<br><em>false </em>for bool<br>0 for uint<br>0x0000000000000000000000000000000000000000 for address</blockquote><p>Now let’s look at the full code for our email contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uP-5FFrju054LuLQ7ivNrg.png" /><figcaption>Full Email Code</figcaption></figure><p>On line 11, we are creating a constructor which basically creates and set the initial states of our MailBox contract. It takes in initialMail variable as argument which we then set to the public mail variable. We are setting the isInitialMail to true cause this is the first message set upon contract creation, increasing the mail count by 1 and setting the senderAddress variable to the address of the user initiating the contract creation.</p><blockquote>Note that the msg variable is a global variable and would be discussed more in later articles.</blockquote><p>The setMail function takes a string newMail as argument, sets it to the mail variable, sets initialMail to false (since this is no longer the initial mail) and increases the mailCount by 1. It is set to public so we can access it from the outside world, and by outside world I mean outside the contract itself.</p><p>Initially, the senderAddress was not set to public and this means that we have no way of accessing it outside the contract. Hence, we created the getAddress function which gets the value stored in the senderAddress variable and returns it to us. Let’s break the getAddress function down a little bit</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*02jtytIZ0PsQ4jxis_zDgw.png" /></figure><p>We already know that the <strong><em>public</em></strong> keyword exposes the function, the <strong><em>view</em></strong> keyword means that the function’s only purpose is to get the value of some variable that was stored and not to initiate a transaction on the blockchain (more on this in later article as well) and the <strong><em>returns </em></strong>keyword tells us that we want to return some value of a specific type in this case an address type which is why we have the <em>(address).</em></p><p>Alright, now that we are done with our MailBox contract, let’s test it out. Click on the debug and run transactions button from earlier and beside your deploy button, set intialMail to “Hello World” (in quotes) then click on the deploy button.</p><blockquote>Notice how the amount of ethers you have reduces, this is because of the gas used in the contract deployment. More of this in later article as well. 😁</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*c4nT91utagSJPDxUzEvcGw.png" /><figcaption>Deployed Contract</figcaption></figure><p>Click on the deployed contracts at the bottom and start interacting with your contract live on a test Ethereum network (Congratulations btw 🥳).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*mI1ER4ENgTuHTjlRZMAiyw.png" /></figure><p>Notice that the <strong><em>isInitialMail</em></strong>, <strong><em>mail</em></strong> and <strong><em>mailCount</em></strong> variables are all exposed and we can see the values set on each of them, except the senderAddress variable. Once again, this is because we did not make it public and the only way we can get it’s value is by clicking on the getAddress button which runs the getAddress function to return the value of the <strong><em>senderAddress </em></strong>variable.</p><p>Now let’s try to set the mail to a new value and see how it affects our contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*kb_vckGRBRHfF84doj886Q.png" /><figcaption>set a new mail</figcaption></figure><p>After setting the mail to “Hello, Contract”, notice how the value of the mail changes, the mail count increases to 2 and the isInitialMail is now false since this is no longer the initial mail.</p><p>That’s it guys, in this article, we have gone through the basics of solidity while creating a simple MailBox Contract, deployed it to a test Ethereum network on remix while also familiarizing ourselves with the new remix editor. In the next article, we’ll dive even deeper into solidity exploring some new data types and other concepts like gas price, transactions, etc.</p><p>I hope you liked this article and find it useful. Do give a like, comment and follow for more on the Web3 technology.</p><blockquote>Find the next step below 👇🏻👇🏻</blockquote><p><a href="https://medium.com/coinmonks/diving-deeper-into-solidity-aeb0259232ec">Diving Deeper Into Solidity</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=736312af0dfe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/solidity-for-dummies-736312af0dfe">Solidity For Dummies.</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Journey Into Web3]]></title>
            <link>https://medium.com/coinmonks/journey-into-web3-4f4a1ddd9a5d?source=rss-8e81ec09f3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f4a1ddd9a5d</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[transactions]]></category>
            <dc:creator><![CDATA[Ifeoluwaolubo]]></dc:creator>
            <pubDate>Mon, 02 Oct 2023 15:06:09 GMT</pubDate>
            <atom:updated>2023-10-27T08:26:28.171Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HA-2BifBA2tY1RiV" /><figcaption>Photo by <a href="https://unsplash.com/@jonathanborba?utm_source=medium&amp;utm_medium=referral">Jonathan Borba</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>About a week ago, I started into a new tech journey of the Web3 space and I must say it’s been a very interesting one. The more I work and make more research on it, the more intrigued I am about the entire concept. In this article I intend on writing about the experience so far, what I’ve learnt and what I’ve worked on as well. Lego 🤩</p><p><strong>A quick history…</strong></p><p>Since a huge part of Web3 revolves around Etheruem and the Ethereum network, the first thing I read about was the reason why Ethereum came about. To talk about Ethereum, we must first talk about Bitcoin itself. Bitcoin is the first of what we’ll like to call a digital money and was invented by an anonymous Satoshi Nakamoto who released the Bitcoin white paper in October 31 2008. In the white paper he described a system to allow peer to peer payments without a financial intermediary (like a bank).</p><p>One of the key characteristics of the bitcoin network was the Idea of a blockchain. The Bitcoin blockchain is basically a tool to store a list of monetary transactions between different people. The issue with bitcoin however was that it was used just for sending of money between different people.</p><p>After a little while, people began to see that they can take some concepts from the Bitcoin technology and apply it to not only handle the transfer of currency but other types of exchanges as well. One of those who felt strongly about this was Vitalik Buterin who authored his own white paper in the late 2013. He envisioned using the technology to create sub cryptocurrencies, domain name registrations and gambling applications amongst many others. So his ideal world was beyond using blockchain to transfer money but creating much more robust and advanced applications.</p><p>In Vitalik’s white paper, he went to discuss an important part of the Ethereum network, something called a <em>Smart Contract. </em>A Smart contract is a piece of code that lives in the Ethereum blockchain and these contracts are the absolute core of what Ethereum is. The Ethereum system went online on July 30th of 2015.</p><p>Ethereum networks are formed by one or more nodes where each node is a machine running an Ethereum client. Each node can contain a full copy of the blockchain and also anyone can run a node.</p><p><strong><em>Further away from history lessons…</em></strong></p><p>I saw that I could use and test Ethereum with a tool called Metamask, so I went on to create my own Metamask account and I was given some 12 words phrases called <em>Mnemonics</em>. The account Mnemonics can be used to generate different accounts in your Metamask account. I know you’re probably confused about the fact that an account is being created inside an account and I was too, but the simple way to think about it is that the different accounts that are created by your Mnemonics are just different wallets (for example savings wallet, investment wallet, housing wallet, etc) then your Metamask account is what you use to access those different wallets.</p><p>I saw that we have the testnet and the mainnet. The mainnet is the main Ethereum network itself used for transferring actual ether while the testnets are used for testing purposes. There are a few testnets, but I connected to the Sepolia testnet then received 0.5 ether into my first wallet by following a blog I saw.</p><p>I went on to learn about what a transaction is. A transaction is basically an object which contains a bunch of information about the actual transaction that occurred on the blockchain. Some of the fields on the transaction object are <em>nonce, to, value, gasPrice, startGas/gasLimit, etc. </em>The transaction object also includes some cryptographic pieces of data that can be used to generate the senders account address, generated from the sender’s private key.</p><p>I saw that when a transaction is made to the Ethereum network, it is sent to a single node in the network which then communicates with the other nodes in the network. Since there are other people making a transactions as the same time to a particular node, the node assembles all these transactions into a single block and runs some validation logic which takes about 30–15 seconds (averagely) to complete.</p><p>The validation logic that’s being run is what we like to call <em>mining. </em>So the node runs some calculations on the block through a process called mining. The mining process is involves finding some number called the nonce that satisfies some cryptographic conditions. This process is very computationally expensive and takes time to find hence the delay in transactions of about 15–30 seconds.</p><p>The time it takes to calculate the block is what we call the block time, where a node is charged to find an ideal number called the nonce that meets the cryptographic requirements. The Ethereum network adjusts the requirements for finding the nonce based on how long it takes to find the previous block hash.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LnShNjVMTFHF-tl1G3kAow.png" /><figcaption>Example for block hashing.</figcaption></figure><p>In the image above, let’s say the target block time is 15 and for the first block, the Ethereum network requires a node to find a number less than 1000 and let’s say that takes about 20 seconds to find. In the next block, the network increases the number to 10,000 since it took way too long to get the right number that satisfies the cryptographic hashing condition of the initial block. Supposed this now takes 5 seconds, then the number is gradually reduced again for the next block and the process continues.</p><p>After my blockchain and Ethereum research, I moved on the writing my first smart contracts using a language called <em>solidity</em> and that is another adventure on its own so I’ll have to leave that for my next article.</p><p>Alright then, although there’s a lot more about the Ethereum network and the blockchain I’ve learnt about, I’ll just keep it real simple for now. In my next article I’ll be writing about what I’ve learnt about solidity.</p><p>I hope you enjoyed this one, and I’ll see you in the next.</p><blockquote>Find the next step below 👇🏻👇🏻</blockquote><p><a href="https://medium.com/coinmonks/solidity-for-dummies-736312af0dfe">Solidity For Dummies.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f4a1ddd9a5d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/journey-into-web3-4f4a1ddd9a5d">Journey Into Web3</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What I want to achieve in this HNG internship]]></title>
            <link>https://medium.com/@ifeoluwaolubo/what-i-want-to-achieve-in-this-hng-internship-8826df03658d?source=rss-8e81ec09f3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8826df03658d</guid>
            <category><![CDATA[hnginternship5]]></category>
            <dc:creator><![CDATA[Ifeoluwaolubo]]></dc:creator>
            <pubDate>Sun, 15 Aug 2021 19:34:01 GMT</pubDate>
            <atom:updated>2021-08-15T19:34:01.364Z</atom:updated>
            <content:encoded><![CDATA[<p>My name is Ifeoluwa Olubo, and to today, I am writing this article stating my goal for the current HNG internship and what I hope to achieve in this 8 weeks of work.</p><p>Firstly, the fact that there are enough resources out there that can guide you towards becoming a programmer should not be disputed, but it is to my believe that finding the projects that sort of makes you go beyond your limit and exploring different possibilities associated to the web and programming in general can’t be easily found.</p><p>Me (for one) have always wanted to do projects that are portfolio worthy but the idea (am afraid) is what I lack and is something I am hoping to find here in this HNG internship. I’ve heard of how challenging it is and how difficult it can get, but I’ve also heard of how much impact the so called challenging internship has made in the lives of those who survives to the end.</p><p>Apart from the fact that I want to build real world apps that are beneficial to the society, I also want to use this Internship as a point of connection to those of like minds and most importantly those who are even better than I am in my field. I hope to learn from those who are advanced than I am in the tech Journey. For more information about the internship can be found in this link</p><p><a href="https://internship.zuri.team/">Zuri Internship</a></p><p>Web development is a broad technology that involves people in different fields to work together. From the UI/UX designer to the frontend, backend, each one of them working on different parts of a web application.</p><p>The YouTube tutorial that helped me in learning figma is</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPLFW6ct83_wC-2m1zPcJr6NBaH-7WVC87G&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fplaylist%3Flist%3DPLFW6ct83_wC-2m1zPcJr6NBaH-7WVC87G&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FcENTgSxUIcA%2Fhqdefault.jpg%3Fsqp%3D-oaymwEWCKgBEF5IWvKriqkDCQgBFQAAiEIYAQ%3D%3D%26rs%3DAOn4CLAdgzb2EWWkzm0swcb0KYB8n1_KIQ%26days_since_epoch%3D18854&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="853" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6a7457c859c790f01ed3da1905cf4c0/href">https://medium.com/media/b6a7457c859c790f01ed3da1905cf4c0/href</a></iframe><p>The tutorial that helped me in learning modern HTML and CSS is</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F-8ORfgUa8ow%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D-8ORfgUa8ow&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F-8ORfgUa8ow%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6f075f098e8cd2ed8cea4085fdb30b0/href">https://medium.com/media/c6f075f098e8cd2ed8cea4085fdb30b0/href</a></iframe><p>For node backend development</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FTNV0_7QRDwY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DTNV0_7QRDwY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FTNV0_7QRDwY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f32c94e079c8361ab1cff7cdcf4be62a/href">https://medium.com/media/f32c94e079c8361ab1cff7cdcf4be62a/href</a></iframe><p>And then for Git and Github which is crusial part of web developers, what helped me in learning was</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FSWYqp7iY_Tc%3Fstart%3D294%26feature%3Doembed%26start%3D294&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DSWYqp7iY_Tc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FSWYqp7iY_Tc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3740857268350b5d8e42f2d67b78074/href">https://medium.com/media/d3740857268350b5d8e42f2d67b78074/href</a></iframe><p>Happy hacking!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8826df03658d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>