<?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 Ryan O&#39;Toole on Medium]]></title>
        <description><![CDATA[Stories by Ryan O&#39;Toole on Medium]]></description>
        <link>https://medium.com/@otoolerj_42923?source=rss-4dd6de0955ba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IdOr89WekWQ1QYtAEQL7RQ.jpeg</url>
            <title>Stories by Ryan O&amp;#39;Toole on Medium</title>
            <link>https://medium.com/@otoolerj_42923?source=rss-4dd6de0955ba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 15:02:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@otoolerj_42923/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[Onboarding the next billion users to Web3]]></title>
            <link>https://medium.com/@otoolerj_42923/onboarding-the-next-billion-users-to-web3-e3330cf39562?source=rss-4dd6de0955ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3330cf39562</guid>
            <category><![CDATA[ether-js]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[erc-4337]]></category>
            <dc:creator><![CDATA[Ryan O'Toole]]></dc:creator>
            <pubDate>Thu, 06 Apr 2023 16:17:32 GMT</pubDate>
            <atom:updated>2023-04-06T16:17:32.193Z</atom:updated>
            <content:encoded><![CDATA[<p>I completed the Scaling Ethereum 2023 hackathon this week and worked on a project utilizing ERC-4377 (Ethereum Request for Comment 4377) is an Ethereum upgrade that enables account abstraction. Account abstraction allows ether wallets to act as smart contracts i.e. you can program them. A smart contract (think class in other languages) is code that lives on the Ethereum blockchain. We can program these smart contracts to do many things- for example we could start a fundraiser and once it reaches 1 ether everyone who donated to it can vote on where the money goes. All of the aforementioned logic is controlled by code.</p><p>Traditionally wallets have been EOAs (Externally Owned Accounts) that come with specific capabilities / limitations like being secured by a private key / seed phrase that must be written down and securely stored. With the advent of ERC-4337 ethereum users can have a more traditional bank-like experience because now they can program their wallets to have (1) two factor authentication with biometrics (2) social recovery (3) gasless transactions (sites can cover gas fees for users). Our project for Scaling Ethereum 2023 used AA (account abstraction) to create an ether to token (ERC20) swap that gets initiated by an EOA (traditional ethereum wallet) then gets sent through a mixer (think tornado cash) to a newly created account made using ERC-4337. The gas fees for sending the result of the ether to token swap are covered by a Paymaster which is an optional part of the ERC-4337 flow that enables users to pay gas in ERC20 tokens and in this case keep the origin of the transaction anonymous. We completed the hackathon but were not able to get everything built. I had a ton of fun, learned so much, and met some really cool people from all over the world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ivcDlEDOnZvyNT9C" /><figcaption>Scaling Ethereum 2023 Project flow</figcaption></figure><p>After the hackathon I started thinking about what it is going to take to onboard the next billion users to Web3. There are going to have to be solutions in terms of (1) Scalability (2) Transaction Cost (3) Transaction Speed (4) Decentralization (5) User Experience / Onboarding. For the rest of this article I’m going to focus on user experience / onboarding i.e. making things simple for people who are new to Web3. I made a portfolio showcasing several web3 decentralized applications (Dapps) that I’ve built over the past year. I wanted as many people as possible to use my Dapps because I was really excited about what I built and how it was using the blockchain. So simple enough, eh? I used Vercel to ship my portfolio of Dapps to production then told everyone- my friends, my family- I even shouted from my rooftop to my neighbors that we can play my Web3 game together. I sent them the link to my portfolio and it was an exciting time- after months of hard work people can finally mint NFTs and play an NFT multi-player mini-turn based game.</p><p>It started off well. Please connect to metamask. “What is metamask?” was a common refrain I heard over and over? Metamask is a self-custodial wallet (you control your keys / secret phrase) that has a browser extension or mobile app. My users were all using the browser extension so that simplified things a tad. Metamask allows you to interact with the blockchain through transactions where you spend the native currency (ETH or in this case GoerliETH). Want to mint an NFT? That will cost you ETH- GoerliETH if you are on the testnet. Want to swap one token for another? That will cost you ETH or GoerliETH too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TaBo0fXPFuLFvHVZ" /></figure><p>Ok step 1 explain what Metamask is and why you need it. Reluctantly most of the people interested in giving my Dapp a go download Metamask. I’d estimate about 70% of the people who expressed interest cared enough to download Metamask. Sorry Grandma =( Maybe Web3 isn’t for you.</p><p>So now they say, “Awesome! I got Metamask and that pesky alert message telling me to go get Metamask has gone away”. And I think wow it is working just like in my dreams. Now they want to mint and NFT and see what the hype is all about. The NFT gallery I built is pretty cool- it creates a random NFT everytime so you never know what you’re going to get. Mom is pretty excited to mint her first NFT (she is a little more tech savvy than Gma).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/0*PizLANM0bCGEwo_k" /><figcaption>Random NFTs from the collection Mom is about to mint from</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*JmQEFJ2QXfV7t-SI" /></figure><p>Until she’s not. “What is this?” She asks. The error message at the bottom of the Metamask window reads “You do not have enough GoerlIETH in your account to pay for the transaction fees on the Goerli network. Buy GoerliETH or deposit from another account.” Oh you just need some GoerliETH Mom it is pretty simple just (1) open google and type Goerli faucet (2) go to site (3) copy your wallet address from Metamask and paste it in the input box</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CvenuOpe5i7AlHyB" /></figure><p>At this point Mom says “Wait so am I buying something? Are they going to charge my credit card every month? I really don’t want them to do that…” No Mom, no one is charging you and you didn’t have to enter your credit card so you’re safe. Can we just get on with this? I have another six users to onboard today. Ok she says and enters her address.</p><p>“But what is this Alchemy account? It is saying I need one?” Yes you do unfortunately this is so people don’t spam the faucet and create DoS (Denial of Service) attacks on the test network. Think of Alchemy as a tool set for web3 development. Having an account verifies you a bit and helps them authenticate the transaction. It is cool Mom, it is free to create and you can delete it after you’re done if you want. “Mom?”</p><p>“Sorry honey this is a little much- I’m really excited for your app though. I’m sure it is really awesome.”</p><p>“It’s a Dapp Mom. A Dapp. Not an app.”</p><p>“Ok hun, huggy bear kissy face.”</p><p>And so they go one after the other. Luckily one of my friends, Brad, has some coding experience and enough follow through to download metamask, create an alchemy account, and visit a test faucet. On top of these obstacles faucets aren’t always reliable and some test networks (think Goerli) are heavily congested (high transaction fee) and hard to get a hold of their test ether (GoerliETH). Fun fact there is actually a market for GoerliETH at the moment and it is selling for close to $.25 per 1GoerliETH last time I checked. Goerli test network will be deprecated at the end of the year and Sepolia is where we are migrating to. So high transaction fees and hard to get test ether equals a bad user experience because once Brad finally gets his hands on some GoerliETH he uses it all up creating one NFT and playing two turns in my mini-based NFT game. Brad is pissed! He has to wait till tomorrow to get more GoerliETH to finish playing the NFT game and everyone he was playing with will be done or dead by then.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/0*flLTsU_VvQ0llGzN" /><figcaption>“Thanks for wasting my time Ryan”</figcaption></figure><p>Wow. Things were not going well at this point. I wanted to show everyone how fun and cool NFTs were. Now my friends and family are pissed at me because I wasted everyone’s time =(.</p><p>Then it dawned on me- what if I built my own faucet. I really love Web3 and want other people to love it too. I can visit the faucet I told my friends to use daily and build up my testnet supply then create a Solidity contract that takes in an address and sends it test ether. In Solidity, the language for creating smart contracts in Ethereum, smart contracts have addresses of their own and they can receive Ether aka hold money. This is useful for many things like storing the funds for a fundraiser till it reaches a certain amount then every user who donated gets to vote on how the funds are spent. It is also useful for making a faucet- I can add the test ether I got from being consistent at the faucet to this contract and allow users to withdraw to whatever address they add as input. If I want to avoid individuals draining my faucet i.e. taking all the money I can add logic to allow each wallet / IP address to only withdraw a certain amount per day. Problem solved =)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BncmYdCH3HEnblDm" /><figcaption>Basic faucet contract written in Solidity</figcaption></figure><p>There are great comments above each line of code to describe what is going on. A contract in Solidity is closest to a class in other languages. There first function in the contract is a receive function that allows the contract to receive any incoming ether payment. The next function (withdraw) takes in an unsigned integer (positive number), has public visibility meaning it can be called from anywhere (inside contract, outside contract, from contract that inherits from it), checks that the withdraw_amount is less than .1 ether (*Ether measured in WEI here*- there are several sub units of Ether and the smallest one is WEI which equals 10¹⁸ ETH), then transfers the checked withdraw_amount to msg.sender. Msg.sender in this example is whoever called the function. Let’s see it in work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*giStagshqAsde_aT" /></figure><p>I compile and deploy this contract to the Goerli Testnet using Remix IDE (Integrated Development Environment). Remix is a great tool for acclimating to Solidity.</p><p>The contract was deployed to this address: 0x97c026c332dD9b12B4BE758E05058F0F389dC10e</p><p>The address of the EOA (externally owned account i.e. Metamask) that deployed it is: 0xA08f0B070486074B8cc3bf6dEbD588a7b2e46561</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/0*1MjBqoKXomPudyfL" /><figcaption>Sending contract address .2 GoerliETH with Metamask</figcaption></figure><p>Great! Did it work? I go to <a href="https://goerli.etherscan.io/"><strong>https://goerli.etherscan.io/</strong></a><strong> </strong>and plug in the contract address and I see that it has .2 ether locked inside.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/0*MJrT7_BgLrKaZ_mN" /></figure><p>Great! Almost there. So now I will use the Solidity faucet contract to send GoerliETH back to the address that sent it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7BJLF4GIEdjyekDpSlFtyQ.png" /><figcaption>Notice in left hand corner contract balance is .2 ETH</figcaption></figure><p>I have to initiate a Metamask transaction from the account I want to send ether to because anytime I change the state of the blockchain I need to pay gas fees. So I confirm the transaction and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JcFzTchq5XXQTNmXCz7RDQ.png" /><figcaption>Notice the contract balance is down .1 ETH</figcaption></figure><p>The balance of the Metamask wallet that initiated the transaction went up and the contract address went down. We did it! Now our friends can enjoy all the wonders Web3 has to offer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-jP6h0kUz1XgS6vHzROSpA.png" /><figcaption>Etherscan page for this transaction</figcaption></figure><p>Ok so I’ve to be a little paranoid over five years of software engineering and I like to really be sure my solution is working before I piss Brad off again. So like how can I be sure? Well I like to think about edge cases and situations that might break our code or at least cause it not to work. So one more transaction just to be sure. This time let’s mimic the experience of a new user i.e. one that has 0 GoerliETH in their wallet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6LyIiJbWhYheCmsgooLT5Q.png" /><figcaption>User has 0 GoerliETH like one of our new users will have</figcaption></figure><p>Let’s initiate the transaction and see what happens</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l1lrvHzDIXPn6Wp7BnqvEg.png" /><figcaption>Read your error messages</figcaption></figure><p>Five years of software engineering has also bestowed upon me the importance of reading error messages. Seasoned software engineers will glance over error messages at times and cause themselves to do extra work because the don’t go to the source of their problem. Notice towards the end of the message it says “Insufficient funds for transfer” and before that it says “The Transaction will likely fail.” So we just saved ourselves another major eye roll from Brad. We can’t initiate a transaction that sends us money if we don’t have money to cover the gas fees. The old “need money to make money” adage hard at work. Gas fees incentivize minors to validate transactions on the network and they go up during times of high traffic. Gas fees are necessary to the ecosystem and aren’t going anywhere anytime soon so we need to find a way. What if the contract could cover the gas fees for the user? How would that work? I spent a lot of time and energy researching and thinking about this topic and while I think it might be possible to execute this logic in a Solidity contract it is unnecessary because third party libraries i.e. Ethers.js allow us to accomplish this logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xFQb7IwFw3U2nhgvoDPMgQ.png" /><figcaption>Javascript code using Ethers.js library to create transaction</figcaption></figure><p>In the requestFunds function I am validating the address the user entered, connecting to the Goerli network through my Infura endpoint, creating a wallet through ethers that takes in the provider (connection to goerli) and my Metamask private key which gives this wallet access to my funds. This access mechanism is what allows me to cover the gas fees for this transaction and send the requested ether with the funds in my wallet. So if this code works we don’t need a faucet contract because our Metamask wallet (EOA / Externally Owned Account) is acting like one through use of the ether.js library.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3330cf39562" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VRN That’s so random. Mmmm. Actually it’s not.]]></title>
            <link>https://medium.com/coinmonks/vrn-thats-so-random-mmmm-actually-it-s-not-b404605cc0b5?source=rss-4dd6de0955ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/b404605cc0b5</guid>
            <category><![CDATA[vrf]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[nft]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[chain-link]]></category>
            <dc:creator><![CDATA[Ryan O'Toole]]></dc:creator>
            <pubDate>Tue, 27 Sep 2022 19:41:12 GMT</pubDate>
            <atom:updated>2022-09-28T22:58:58.569Z</atom:updated>
            <content:encoded><![CDATA[<p>I built this really cool game and now I’m adding some additional features to make the game more interactive. It is a mini-turn based NFT (non-fungible token) game where you can mint an NFT of your favorite character and battle the boss. Each NFT has attributes associated with it like health points, attack damage, damage done. When they go into battle the attributes of the NFT change which means we must create a transaction to the ethereum blockchain (Goerli Testnet to be specific) to accomplish this. Why? Anytime you change the state of the blockchain you need to pay a transaction fee for the transaction to be validated by the network and added to the blockchain. Luckily we are on the Goerli Testnet so we pay GoerliETH which you can get for free from a faucet like this: <a href="https://goerlifaucet.com/">https://goerlifaucet.com/</a> or this: <a href="https://faucets.chain.link/">https://faucets.chain.link/</a></p><p>If you’re into web3 and its ethos try the Goerli Proof of Work faucet where you do some mining and really earn your GoerliETH: <a href="https://goerli-faucet.pk910.de/">https://goerli-faucet.pk910.de/</a> I really like the PoW faucet because the only limit to how much GoerliETH you get per day is how long you’re willing to mine. Plus it makes me feel like a Web3 badass =)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vWeEhSYTFW_F__f8" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3sAJcuVutqq2hQnY" /></figure><p>I added multiplayer functionality to really make the game pop. If two players are playing simultaneously they will be able to see each other’s NFTs as well as their attributes change when they attack. There wasn’t any UX/UI to let the user know that their NFT has died, if another user’s NFT has died, or if they killed the boss. I added all three of these to help navigate the user. The game was feeling much better at this point in terms of functionality and more like something I could show off to friends and potential employers. Since the attack damage and health points of each character as well as the boss are hardwired the game can get a little monotonous. There was no chance element to the game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aKvGuKnMmhkUblS0.png" /><figcaption>PoodleMoth and DogSquirrelMan a match made in Heaven =)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mC7E2tN8QLppMTb5.png" /><figcaption>At least it wasn’t us…</figcaption></figure><p>Enter Chainlink and the VRF. Chainlink VRF (Verifiable Random Function) is a provably fair and verifiable number generator (RNG) that enables smart contracts to access random values without compromising security and usability. Chainlink VRF generates one or more random values and cryptographic proof of how those values were determined then the proof is published and verified on-chain before any consuming application can use it. This process ensures the results cannot be tampered with by any single entity i.e. oracle operators, miners, smart contract developers.</p><p>What is Chainlink? Blockchain oracles for hybrid smart contracts: <a href="https://chain.link/">https://chain.link/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TW8-jNVLAj556swK" /></figure><p>In English, please? Blockchains are deterministic by nature, meaning the transactions produce the same results every time they are executed regardless of who and where the transaction is executed. This simplicity is key to the security and reliability of blockchains as the network only needs to form consensus on a very basic set of binary (true/false) questions using data already stored inside its ledger. These questions include: did the public key holder sign the transaction with their corresponding private key, does the public address have enough funds to cover its transaction, and is the type of transaction valid within the particular smart contract. Solidity smart contracts (think class in coding) execute exactly as written with a much higher degree of certainty than traditional systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/0*8UmmylIOVYGAWrGI" /></figure><p>If there was a native random number generator in Solidity, the language used to implement smart contracts, every miner would come up with their random number for the same code execution, and the execution result would be different for everybody making it impossible ever to reach a consensus. For this reason, the nature of blockchains dictate that there will not be native random number generators in smart contracts.</p><p>Due to the deterministic nature of blockchains bringing real world data like price information poses a huge problem because the value will vary depending on the source of your data. Given this feature of blockchains we need to be certain the information the oracle is returning is trustworthy because transactions cannot be undone. For example if I made a bet on an Ethereum gambling dapp (decentralized app) that Joe Biden would win the 2020 election for President of the United States I would want to make sure I trusted the source of this information. Regardless of your political outlook it is problematic if we relied on one news agency or API as the source for the answer that will determine the outcome of this bet. Why? Because once that off-chain information (who won the election?) comes on-chain the smart contract will execute its logic in a deterministic manner. So if the source we are relying on says Donald Trump won then the associated logic would immediately fire i.e. the person who bet on Donald Trump would be paid. This transaction would not be able to be undone given the way blockchains function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*4Z2-KHoRoU6KtgZq" /></figure><p>This example is helpful because there was uncertainty for some time in regards to who won the election. If an oracle service was relied on to provide this information we would have a much higher degree of certainty that the correct person would be paid. Why? And How? Because Oracles act as on-chain APIs you can query to get information into your smart contracts (anything from price info to weather reports). Different oracles have different approaches to ensuring accurate data but most aggregate the data from multiple reliable sources and have a financial incentive to provide accurate information. LINK is the native token of Chainlink and how we pay for their oracle services. If Chainlink started providing unreliable or dishonest information their token’s value would plummet. The LINK token follows an ERC-677 token standard that is backward compatible with the popular ERC-20 token and contains some improvements that make working with oracles cheaper, easier, and much more efficient. Check out my older blog posts if that was over your head.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z5ohAWes6oEcMHls" /></figure><p>Ok so back to the Chainlink, the VRF (Verifiable Random Function), and a slightly different gambling dapp. If I had a simple gambling dapp where you can play roulette (casio game where you can bet on which number a ball will land on) I would need to use a random number each time the player “spins the wheel.” Because the blockchain is a public ledger that anyone can view, the smart contract that holds the logic for your random number function would be visible to the world so someone will hack your game and always win. Enter Chainlink VRF- because the random number is coming from an off-chain oracle in real-time our gambling dapp cannot be hacked. This works because we trust Chainlink. Why do we trust Chainlink? Well for one they’re financially incentivized to provide accurate information. Think about it- we pay for their Oracle services in LINK which is trading at $7.06 USD today. If Chainlink oracles provided bad or malicious information the price of LINK would be zero. Furthermore Chainlink uses some cryptographic magic to prove that the number you requested is truly random. Put simply oracles are a bridge between the blockchain and the real world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/0*MVm4c8tL59-HQQhR" /></figure><p>Ok so a few questions I’m sure. First we are using the random number we generate to give the NFT characters in my game the ability to have a critical hit 20% of the time. Second, yes Chainlink VRF might be a little excessive for a game that doesn’t have any stakes i.e. you can’t win anything let alone anything of value. So I could have used something simpler given that reality but I didn’t because I wanted to get practice with Chainlink VRF implementation. Furthermore if I build any game involving real money it is extremely important I use Chainlink VRF because as you remember the blockchain is a public ledger anyone can read. If I used some clever hashing algorithm and randomness function some malicious actor could read my code, do the calculations, and exploit my game for real money.</p><p>Chainlink VRF has other utility besides gambling apps and blockchain games. Chainlink VRF has been used to assign randomized attributes to NFTs, providing the owner access to suitable evidence that their NFT assets are created using tamper-proof randomness. Chainlink VRF can also be used to ensure fairness when doing randomized NFT drops to community members. In addition it can be used for random assignment of duties and resources (assigning judges to a case) and choosing a representative sample for consensus mechanisms.</p><p>I’m going to nerd out a bit on randomness. True randomness is impossible (sorry Chainlink). If you ask your computer for a random number it will do something like add the times you pressed ‘F’ on the keyboard at 1:50pm everyday since you bought it, to the temperature in Fiji, times the speed of the computer fan etc. The number your computer generates is scientifically called pseudo-random. Why? Because it is not random…</p><p>What about you? Come up with a random number. I bet you $100 bucks it was smaller than this:</p><p>115792089237316195423570985008687907853269984665640564039457584007913129639935</p><p>If you’re curious that is the largest number Solidity can handle and it looks like this in digestible form: 2**256–1</p><p>Quick thought experiment what if the roulette wheel is broken at a casino and you need to be the source of randomness for the night all you have to do is pick a number between 1–36 (there are two more # in roulette 0 and 00 but let’s keep it simple) all night long. There are lots of high stake gamblers at the table and you can’t favor a number or neglect one. Could you do it?</p><p>Zero chance. A computer might be able to have a statically random distribution picking 1–36 (think gambling machine) in a way that is fair but it is following an algorithm and this “randomness” only works because the gamblers aren’t privy to the algorithm. The gambling machine is owned, maintained, and operated by centralized authorities (Gambling Commision, Harrah’s Casino) that have oversight and regulation. We the gamblers trust the authorities. That is how it works.</p><p>With oracles and blockchain it is we the people trust the code! And we the people trust the incentive mechanisms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*MXmtqrJuBm_eBNk2" /></figure><p>There’s this incredible book Incognito: The Secret Lives of the Brain by David Eagleman and he writes in detail from a scientific background about consciousness and the brain. One of the major takeaways of the book is we are not as in charge of our decision making as we think we are. There are experiments where you are asked to pick a number and your brain has already decided the number before you “decided” which number to pick.</p><p>Then where can randomness come from? Think about the universe. The weight of iron in our solar system, times the number of planes in the sky at this moment, divided by the number of kittens that died before one month of age, times the amount of times you brushed your teeth. What part is random? Say we did have access to all those numbers and every time we played a gambling game something yelled out a bunch of nonsense and some program added it all up. That would be pretty random but we would favor what “random” things we say. Furthermore if we were omnipotent and had access to the all of the past things that ever happened (think instead of recording your favorite show you could record eternity) we would see that the weight of iron in our universe reached its current level because of the deterministic forces of physics and the starting position of all matter. The kittens that didn’t make it past one month were actually pretty easy to pick out too. No cats were hurt in the making of this blog =)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/0*socg9d3pCQ2wIHiR" /></figure><p>The world is deterministic. With needle-like precision we know where a specific planet will be two hundred and seven years in the future. Everything in the physical universe follows laws and patterns. We might not be able to predict how a thousand marbles collide and interact but it doesn’t mean they do anything random but rather our observational abilities are limited. The closest thing I’ve read about that resembles randomness is quantum theory and (1) I don’t fully understand it (2) I think in the future we will realize it is not random but was beyond our understanding at this time.</p><p>So Chainlink VRF gives us a verifiable random number for all intensive purposes. This means it cannot be hacked or gamed. Think of fair and unbiased randomness when you think of Chainlink VRF.</p><p>Ok awesome! Got it! But how does Chainlink VRF calculate a random number? Inputs for the VRF typically include a public/private key pair (my public key looks like this 0x1ce750e83B91D00b6cCe3ae6feBe71420feAa5FF and my private key is not for sharing but it looks similar) and a seed (think anything from the number 224 to the string CatwalkerForLife).</p><p>Those values are passed into the VRF where the private key and seed are used to generate a random number. Critically, the generation of a proof makes the function verifiable, while keeping the private key hidden ensures the number is unpredictable. I used VRF version 2 and didn’t need to enter a seed phrase so I think version 2 uses the block hash and nonce of the block that gets added to the blockchain while the request for randomness is being fulfilled.</p><p>The service might seem trivial, but having a fair and verifiable source of randomness is especially important for tasks that rely on unpredictable outcomes, such as NFTs, DeFi, blockchain games, or choosing a representative sample for consensus mechanisms. Thanks for reading! If you have any questions please post them in the comments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*_huldCfjddYl9jZp" /></figure><blockquote>New to trading? Try <a href="https://medium.com/coinmonks/crypto-trading-bot-c2ffce8acb2a">crypto trading bots</a> or <a href="https://medium.com/coinmonks/top-10-crypto-copy-trading-platforms-for-beginners-d0c37c7d698c">copy trading</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b404605cc0b5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/vrn-thats-so-random-mmmm-actually-it-s-not-b404605cc0b5">VRN That’s so random. Mmmm. Actually it’s not.</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[Mini-Turn NFT game with Solidity and Javascript]]></title>
            <link>https://medium.com/coinmonks/mini-turn-nft-game-with-solidity-and-javascript-ccb156058058?source=rss-4dd6de0955ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccb156058058</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[blokchain]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nft]]></category>
            <dc:creator><![CDATA[Ryan O'Toole]]></dc:creator>
            <pubDate>Tue, 13 Sep 2022 03:09:29 GMT</pubDate>
            <atom:updated>2022-09-20T13:41:10.192Z</atom:updated>
            <content:encoded><![CDATA[<p>The best way I know how to learn is through building. In turn the best way I know how to teach is showcasing something I built. This blog post is going to cover an dapp (decentralized app) that I built with the help of buildspace. If you haven’t heard of them, they’re a must if you’re looking to get into web3 / blockchain. They’ve got great tutorials, an active telegram channel for help, and the projects are challenging from a technical standpoint so you will learn a ton! Plus the projects are great to build top of and add additional features. I added multi-player functionality, a total damageDone attribute for each player, additional UI to communicate next steps when a character dies, and hosted the images on IPFS (InterPlanatery File System).</p><p>The first thing I’m going to do is run this script in my terminal to deploy my Solidity smart contract to the Rinkeby test network: npx hardhat run scripts/deploy.js — network Rinkeby</p><p>I am using hardhat which is an ethereum development environment. I ran a hardhat script to create this project and that comes with tons of built in features including a local testing environment which is super helpful when building your contracts. More info on hardhat here: <a href="https://hardhat.org/">https://hardhat.org/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AB7hi3M0RyIPb2c_" /><figcaption>My deploy script</figcaption></figure><p>The first line of my code will actually compile our contract and generate the necessary files we need to work with our contract. It uses The Hardhat Runtime Environment, or hre for short, which is an object that hardhat exposes when running a task, test, or script. Then we deploy the contract to the rinkeby test network, which is an actual external blockchain, and send in the arguments to the constructor function to initialize our characters for the game. We console log the address of the contract because we will need that and something called an ABI (application binary interface) to communicate with our contract from our frontend later. The ABI is found in the artifacts directory of our hardhat project after we deploy our script in a file called “YourContractName.json”. ABI is essentially the communication layer between the Solidity world and the Javascript world. The ABI Specifies the our contract’s different methods and their format of inputs and outputs.</p><p>Contract deployed to: 0x0046c78EC1987244c01C64203065874aAdBB3647</p><p>Now I add the contract address and ABI to my frontend and start my server to begin the game. Think of each contract as a new game that lives on the blockchain and our frontend is our way to communicate with and experience the game. This is the first page of the website where the user is welcomed to the game and prompted to connect their wallet to play. In web3 your wallet is the way you login to decentralized applications, it acts like your username and password in addition to your wallet. This app is expecting a specific browser wallet, Metamask, which allows us to buy, store, and send cryptocurrency. In addition Metamask has support for Ethereum test networks like Rinkeby which is what we will be using today. Why the test network? Because I’d rather not pay real ETH. This app will work exactly the same on the mainnet (the network with real ETH) you just need to change a few lines of code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PL40tKw5687wRT1Z" /><figcaption>Things are looking Epic!</figcaption></figure><p>The user clicks the button and is either brought to their Metamask login or they are told to install Metamask:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/0*O-5eRHjo2ymM6nms" /></figure><p>Once the user logs into Metamask they will be brought to the SelectCharacter page of the dapp:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RyvUJ9E9lEMlD4YC" /><figcaption>They feel very me =)</figcaption></figure><p>Here the user can mint an NFT (non-fungible token) of their preferred character. What is an NFT? Well a fungible token is like a United States dollar, one dollar equals one dollar. Further one dollar also equals 100 cents. Whereas one DogSquirrelMan NFT is not interchangeable with one Batman NFT. I created these tokens using OpenZeppelin which is a library for secure smart contract development. These tokens follow the erc-721 standard: <a href="https://ethereum.org/en/developers/docs/standards/tokens/erc-721/">https://ethereum.org/en/developers/docs/standards/tokens/erc-721/</a></p><p>These images are not NFTs yet, but the image you are seeing for each character is hosted on a decentralized storage network called IPFS (Interplanetary File System) and this same image will be used to create your NFT. I am fond of PoodleMoth so I’m going to click “Mint PoodleMoth” which brings me to this screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*jiOLoOh39ximAqQBQus9Xw.png" /></figure><p>This is a pop-up from my Metamask wallet that is asking me to confirm the transaction. I am paying with RinkebyETH which you can find get from a faucet like this: <a href="https://rinkebyfaucet.com/">https://rinkebyfaucet.com/</a></p><p>Gas is a unit of computation. Gas fees are what allow the Ethereum blockchain to run. Gas fees are what incentive people to run nodes which come together to form the Ethereum blockchain. Gas prices follow the laws of supply and demand becoming more expensive during peak network usage hours. Gas fees prevent many types of malicious attacks because it makes it too expensive for malicious users to spam the network. A user can pay higher gas fees to have a transaction validated faster.</p><p>I am going to confirm the transaction and strangely we are brought to this screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4-hI54vih-egIQEL" /><figcaption>Where my NFT =(</figcaption></figure><p>What the heck? Where is our NFT? Being made =) When I clicked confirm on the MetaMask transaction this function was run which is what actually mints our NFT. In simple terms minting an NFT refers to the process of turning a digital file into a digital asset on the Ethereum blockchain. Once on the blockchain this digital file is now a NFT and it will be stored here forever.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3cFFFDLPAculM2qS" /><figcaption>My Solidity code to mint an NFT</figcaption></figure><p>Ok so why the wait? When we execute this function we send a transaction to the Ethereum blockchain and cryptography generates a transaction hash like this: 0x97d99bc7729211111a21b12c933c949d4f31684f1d6954ff477d0477538ff017</p><p>The transaction is then broadcast to the network and included in a pool with lots of other transactions. A miner must pick your transaction and include it in a block in order to verify the transaction and consider it successful. This process takes time and the amount of time is directly correlated with how much you’re willing to pay i.e. gas price. Gas refers to the unit that measures the amount of computation effort required to execute specific operations on the Ethereum blockchain. The gas price is how much you’re willing to pay per unit of gas to have your transaction verified.</p><p>Ok so we are waiting for a good reason and if we can afford it we can wait less. Cool!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PHQwY-7ChQjgkSjMrnnLzQ.png" /><figcaption>Enter PoodleMoth!</figcaption></figure><p>Epic!!! Our NFT is here. Right? Yeah kind of. lol. Ok so lets be specific. Your NFT is made and is now living on the Rinkeby blockchain. All of the Poodle’s stats- attack damage, damage done to boss, health- they all are coming directly from the blockchain then being parsed into a format Javascript can read and then shown on the frontend. The image like I said earlier is being stored on a decentralized file storage system called IPFS. So we are calling a function on our contract that lives on the blockchain and this function is returning our NFT. So our NFT actually lives on the blockchain! Opensea the popular NFT marketplace: <a href="https://opensea.io/">https://opensea.io/</a> renders NFTs on their site in this same way. Just go to their site (i’m using their testnet here <a href="https://testnets.opensea.io/">https://testnets.opensea.io/</a>) and enter the address of the Solidity smart contract: 0x0046c78EC1987244c01C64203065874aAdBB3647 or go here for ease: <a href="https://testnets.opensea.io/assets/rinkeby/0x0046c78ec1987244c01c64203065874aadbb3647/1">https://testnets.opensea.io/assets/rinkeby/0x0046c78ec1987244c01c64203065874aadbb3647/1</a></p><p>And wham. The NFT =)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nxrlpDoKcqpJNC6XjbgMgw.png" /><figcaption>Check out Attack Damage and Health Points!</figcaption></figure><p>What’s up with the levels? Attack damage and health points are attributes of each character and the villain in my game. You get to decide what attributes your NFT has. Attributes aren’t only for playing games with NFTs, they are also important to collectors. For instance your NFT from the Bored Ape Yacht Club has certain attributes (short mohawk, hawaiian, crazy) that make it unique and a more interactive ownership experience. Check out this snippet of Solidity code where I override OpenZeppelin’s tokenURI function to set the data I want to the NFT that will be created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VAexzomMGkPY9JJn" /><figcaption>Overiding OpenZeppelins tokenURI function</figcaption></figure><p>Ok cool. So can we play this friggin’ game? Yes, let’s do it! You might be asking yourself why DogSquirrelMan is in the game because we didn’t mint him. Some other wallet minted him and is playing the game with us at the same time. You can see their wallet address and the attributes of their NFT as well as the damage done to the boss so far. A fun next feature I intend to build is setting up a wallet to wallet messaging service so players can coordinate attacks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EIuq5z4icOM0ooLcDQHOFw.png" /><figcaption>yo DogSquirrelMan go for his knees</figcaption></figure><p>Ok so I just pressed the attack button then my MetaMask wallet pops up asking me to confirm the transaction (not going to show it for redundancy sake). Because I am changing the state of the blockchain this transaction will cost money if we were live but we’re on the test network so I pay RinkebyETH. Then we wait for the transaction to be verified for the blockchain and once it is we see a visual effect (some advanced CSS) on the Joker character and then we see both his and our attributes updated. Awesome! We just sent a transaction to the blockchain to change the attributes of an NFT on the blockchain then rendered that information to our frontend. If you’re savvy you might be thinking but wait, how did our Javascript / React frontend know that this specific transaction has been completed on the blockchain? And furthermore how did we grab the updated values then refresh our frontend UI (User Interface) with them? Events! In this case we “emit” an event named AttackComplete in a function called attackBoss that lives in our Solidity contract on Yes! The blockchain =) You’re getting it! If you’re curious, CharacterNftMinted was the event that fired when we minted our NFT and wanted to tell our frontend about it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5f2Yf6Qb3dvA1849" /><figcaption>events are super helpful =)</figcaption></figure><p>Once our event listener picks up the event our frontend shows Joker and PoodleMoth with their updated health points. When a player attacks the Joker he of course deals some back damage too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0TVQkaBEuliwUOGUEJUlmQ.png" /></figure><p>Below is the code for the attackBoss function in our Solidity contract. Notice our logic that only lets NFT’s with hp &gt; 0 play. Also notice at the bottom of this function is where we fire our AttackComplete event.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_UM1z7lwP0pHcKxy" /></figure><p>The next snippet is the code for our React frontend that turns the event listener on in our useEffect lifecycle function to listen for the event AttackComplete to be emitted from the blockchain and when it is we fire onAttackComplete which is a function in our React frontend to update our UI to reflect the changes that happened on the blockchain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kb4fk3REOA6Y26Xs3P_cEQ.png" /></figure><p>The onAttackComplete function receives the inputs from our emitted event in Solidity and updates the right characters. Remember we have DogSqurirelMan playing our game too and since there are multiple players we need to tell our frontend which player is us and which players are not. We accomplish this through the use of a public wallet address which is a unique identifier that we assign to our NFTs on the Solidity side of the code by making use of a built-in function called msg.sender which returns to us the wallet address of the person interacting with our contract. Cool bean salad! Speaking of DogSquirrelMan, let’s see what he’s made of. DogSquirrelMan attacks and:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sv4arpfCW_rSG2WK" /><figcaption>DogSquirrelMan has Bark!</figcaption></figure><p>Just like we expected we see DogSquirrelMan update. Remember we are playing as PoodleMoth so we see DogSquirrelMan update as the other player. Nice! Let’s take it to a logical extreme and watch DogSquirrelMan meet his untimely demise. DogSquirrelMan valiantly attacks again and sacrifices himself for the the good of the Darkwing Nights. I listen for the Solidity event NftDeath in my JS code and when it is emitted I do some conditional rendering using state and the setTimeout function to communicate what happened through the UI to my user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8nYvmfZNhus7eWlS0j7J_Q.png" /><figcaption>Nothing like death laughing at you</figcaption></figure><p>So what happened to the other player’s NFT? Great question! It is still in existence on the Rinkeby blockchain floating around the ether (no pun intended) with 0 health points. You can destroy an NFT through a process called burning: <a href="https://postergrind.com/is-it-possible-for-an-nft-to-be-destroyed/">https://postergrind.com/is-it-possible-for-an-nft-to-be-destroyed/</a> but this would cost money because it changes the state of the blockchain. In addition the NFT can still serve as a collectible or souvenir even though it no longer has utility in the game. So what I did was add an event in my Solidity code to fire if any of the players I keep in this allPlayersInGame array have their health equal to zero.I check for this in the attackBoss function in the Solidity code. If they do have health equal to 0 I delete the struct (https://solidity-by-example.org/structs/) representing that player from allPlayersInGame array I was keeping it in on the Solidity side of the code. I also fire an event NftDeath which takes two arguments namely msg.sender and the allPlayersInGame array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_U-5yHP859m52qTO" /></figure><p>The emitted NftDeath event is going to fire a function on the frontend called nftDeath. There is other frontend code that already removes the dead character and this is found in a function onAttackComplete which listens when the Solidity event “AttackComplete” is emitted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/0*LmTNLeQZHaGx2KvU" /></figure><p>Remember that struct I deleted from the allPlayersInGame array (two images up). You’re probably asking yourself why we had to do that on the backend if we were already accounting for this behavior on the frontend. Yes it is a little redundant but there was a bug I was getting when a new character would enter the game of the same type as the character who just died. Basically two characters of the same type would appear with full stats. So now I delete the struct on the Solidity side of the code which sets the struct to its default values. The struct has looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/0*p2E5rvG-rmYiTcKp" /></figure><p>The default value for an address variable is what I’m checking against in the code below this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-6zecsL2t2K8kayA" /><figcaption>default Solidity address</figcaption></figure><p>So I use this default behavior to my advantage and rely on it to keep those nasty bugs out of my dapp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*8ICuGRat9G6QrEmCxImB_g.png" /></figure><p>PoodleMooth fights a valiant fight but eventually meets his end:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*igonktyzzJOlE0orDnlQgA.png" /></figure><p>After this conditional rendering letting you know your character has died you are brought back to the mint character screen. I’ve been wanting to try Batboy and look by the luck of the draw we got the perfect duo (Batman is playing too). I was thinking a cool stretch feature would be to code in functionality to give Batboy double attack power if Batman is in the game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HSXK3q4YiGdBwViDLhKd2A.png" /></figure><p>After a long and arduous battle the Joker was vanquished and Batman and Batboy will go on forever living happily on the chain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uCBX3n1NpL5JH6Rdet6Tnw.png" /></figure><p>But hey don’t take my word for it. Go see for yourself the contract lives here: 0x0046c78EC1987244c01C64203065874aAdBB3647 and the link to the collection on Opensea is here: <a href="https://testnets.opensea.io/collection/darkwing-nights-xxt6tzayou">https://testnets.opensea.io/collection/darkwing-nights-xxt6tzayou</a></p><p>So you may be asking yourself what next? I will put this contract inside another contract called a contract factory. I will deploy the contract factory to allow users to deploy a new contract with the click of a button. The contract factory will also keep track of all instances of the contract (game). I will also add a random number generator to add a critical strike feature that triples the strike power 10% of the time. I really like the idea of certain players have synergistic relationships so I will explore that as well. Follow me on <a href="https://twitter.com/web3ForToday">https://twitter.com/web3ForToday</a> or <a href="https://www.linkedin.com/in/ryanjohnotoole/">https://www.linkedin.com/in/ryanjohnotoole/</a> if you like this content. Thanks for reading have a great week.</p><blockquote>New to trading? Try <a href="https://medium.com/coinmonks/crypto-trading-bot-c2ffce8acb2a">crypto trading bots</a> or <a href="https://medium.com/coinmonks/top-10-crypto-copy-trading-platforms-for-beginners-d0c37c7d698c">copy trading</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccb156058058" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/mini-turn-nft-game-with-solidity-and-javascript-ccb156058058">Mini-Turn NFT game with Solidity and Javascript</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[Things I wish I knew 8 months ago…]]></title>
            <link>https://medium.com/coinmonks/things-i-wish-i-knew-8-months-ago-7928cfa0fa9b?source=rss-4dd6de0955ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/7928cfa0fa9b</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[erc20]]></category>
            <category><![CDATA[nft]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Ryan O'Toole]]></dc:creator>
            <pubDate>Thu, 28 Jul 2022 20:45:26 GMT</pubDate>
            <atom:updated>2022-09-16T05:26:11.886Z</atom:updated>
            <content:encoded><![CDATA[<p>This is meant to be a basic guide for the curious about the world of blockchains, web3, ethereum, and NFTs. I will go into some technical detail but this is mostly meant to serve as a gateway into this world and answer hard to phrase questions google can’t translate for you.</p><p>What is a blockchain?</p><p>Think of a public ledger when you hear the word blockchain. It keeps track of all transactions within a network. The bitcoin blockchain is secured by a network of computers (nodes) who are financially incentivized (via a process called mining) to validate transactions on the network. Each node has a complete copy of the blockchain (public ledger) — which is a record of every Bitcoin transaction ever- all the way back to the very beginning of Bitcoin. As of today, the public ledger contains more than 30 million transactions and requires 13 GB of disk space. A full node is basically an electronic bookkeeper, and anybody in the world can set up and run one (i.e. anyone who runs a node is a miner). Security of the network is ensured through energy intensive processes (mining) that financially incentivize (miners) by rewarding them Bitcoin to validate transactions thus ensuring the network runs and is secure. Due to the energy intensive processes required for mining and the financial incentives that good behavior creates it is highly unlikely for the blockchain to be corrupted (It would require more than 50% of nodes to be malicious and coordinate an attack (extremely challenging to orchestrate in the real world).</p><figure><img alt="Bitcoin mining rigs i.e. lots of energy consumption and hardware" src="https://cdn-images-1.medium.com/max/1024/0*-e7PovSjgXYLOO8l" /><figcaption>Bitcoin Mining rigs i.e. enormous energy consumption and expensive specialized hardware</figcaption></figure><p>But what is Bitcoin? What is a Bitcoin? What does it look like? Is it an object in coding terms? Or a string? Or a number?</p><p>Bitcoin is a value that looks like this:</p><p>1,02930291</p><p>*Bitcoin is digital not physical i.e. a number. It has 8 decimal places. When you own bitcoin it means you own the rights to access a specific bitcoin address record in the ledger and send funds from it to a different address. The value is stored in an online or offline wallet address that looks like this: 3J98t1WpEZ73CNmQvlecrnylWrnqRhWNLy</p><p>Bitcoin is only intended to ever be a store of value and a medium of exchange. The important takeaway is Bitcoin can be possessed, transferred, and it is impossible to copy.</p><p>Unlike Bitcoin (BTC), Ethereum (ETH) is intended to be much more than just a medium of exchange or a store of value. Instead, Ethereum is a decentralized computing network built on blockchain technology. In the crypto’s own words, Ethereum is “a global, decentralized platform for money and new kinds of applications,” with thousands of games and financial apps running on top of the Ethereum blockchain. This type of cryptocurrency (ETH) is so popular that even other crypto coins run on its network.Ethereum’s native currency is ETHER (ETH) and it can be used to pay block rewards (mining), pay transaction fees (gas), and can be transferred between accounts. Gas is a unit of computation and the gas price determines how much ETH is needed per unit of gas to have the network validate a transaction (a transaction changes the state of the blockchain). Gas price depends on network activity and congestion so if your transaction isn’t time-sensitive you can pay lower gas gees if you’re willing to wait longer to have that transaction validated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/0*Xxlk3BZSmV27ncO1" /></figure><p>Ok cool. A lot but digestible. But what the heck is an ERC20 vs. ERC721? And which is Bitcoin? And which is Ethereum?</p><p>Bitcoin and Ethereum are not ERC20 or ERC721 tokens.</p><p>The ERC-20 (Ethereum Request for Comments 20) is a token standard that implements an API for tokens within Smart Contracts. Smart Contracts are simply programs stored on a blockchain that run when predetermined conditions are met. Example functionalities of ERC-20 tokens include: transfer tokens from one account to another, get the current token balance of an account, get the total supply of the token available on the network, and approve whether an amount of token for an account can be spent by a third-party account. The ERC-20 token standard is composed of specific functions and events (https://ethereum.org/en/developers/docs/standards/tokens/erc-20/) that allow developers to build token applications that are interoperable with other products and services.</p><p>ERC-20 is a fungible token standard, which means that each individual token (or fraction) is equivalent to and indistinguishable from the next. United States dollars are fungible: $1 = $1 and $1 = 100 cents. This will always be true. Bitcoin and Ethereum are fungible cryptocurrencies but they are not ERC-20 tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0RSZo8AUQm1i6XnW" /><figcaption>ERC-20 (fungible) vs. ERC-721 (non-fungible)</figcaption></figure><p>A token has 0 inherent value. And when I say 0 I mean zero, zip, zilch, nada. I can make a token out of thin air. I did this last week, actually I made three different tokens (see image below). Token value comes from its utility. What can I do with it? Ether has value because it allows me to update state in the EVM i.e. make transactions on the network. Ether is the gas that makes the network run. For example Chainlink (<a href="https://chain.link/">https://chain.link/</a>) has an ERC-20 token LINK and it is valued at $7.11 as of July 28th 2022. LINK has value because it is the gas that runs Chainlink, which is a decentralized oracle network.</p><p>A decentralized oracle is a group of independent blockchain oracles that provide data to a blockchain. Every independent node or oracle in the decentralized oracle network independently retrieves data from an off-chain source and brings it on-chain. The data is aggregated so the system can come to a deterministic value of truth for that data point. If there is uncertainty as to the veracity of this data a human element comes into play and that human is financially disincentivized to provide inaccurate data.</p><p>A simple example to showcase the utility of oracles is if I made a betting dapp (decentralized app) and you and I bet each other on the results of a baseball game. We both send 1 ETH into a smart contract and when the game is over whoever wins gets the money, right? Wrong! Without oracles a betting application like this would need to get the verified data (who won?) from one source? Or maybe aggregate several sources to be more sure? Smart contracts hold and distribute large amounts of money so making sure the data is correct and the right person gets paid is paramount. Oracles through financial incentivization and disincentivization provide verifiable real world data to smart contracts and the ethereum blockchain so two people betting on a sports game can be sure the right person will get paid out when the game is over. Chainlinks gas, LINK, which is an ERC-20 token has value because it is the currency with which you pay oracles to verify data is accurate. My ERC-20 tokens (Ry and RYO) have 0 value because they have no utility i.e. you cannot buy anything with them because I didn’t build a network for them to do anything on (I just minted the coins). On the other hand if I built a complex decentralized oracle network (technically challenging) and used the tokens I made as the gas that runs this network they would have value as long as people used that network and in turn paid for these tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/0*UCWgskP-kya1aaZz" /><figcaption>My worthless ERC-20 tokens fun to create but worthless</figcaption></figure><p>ERC-20 VS ERC-721</p><p>In contrast to ERC-20 for fungible token standard, ERC-721 is a token standard that defines non-fungible tokens (NFTs) on the Ethereum blockchain. Non-fungible tokens, or NFTs, are a special type of cryptographic token: they are not mutually interchangeable by their individual specification. NFTs have individual characteristics that set them apart from one another, making them a medium to represent collectibles, game items, digital art, event tickets, domain names, and ownership records for physical assets (think title for car).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/0*eWXRL-Eg1kn2CWz6" /><figcaption>Six figure NFT from “Bored Ape Yacht Club” collection</figcaption></figure><p><strong>What NFTs are made of</strong></p><p>There are a few key features that define an NFT, regardless of platform.</p><p>First, each token has a unique id that distinguishes it from all other tokens. This is in contrast to a fungible token like Ether ETH, which exists as a quantity attached to an account or wallet. There is no way to tell one ETH from another. Because each NFT is unique, they’re owned and traded individually, with the smart contract keeping track of who owns what.</p><p>Another key feature of an NFT is the ability to link to data that is stored outside of a smart contract. Storing or processing data outside of a smart-contract is known as being <em>off-chain</em>. Because data that’s stored <em>on-chain</em> needs to be processed, verified, and replicated across the entire blockchain network, it can be very expensive to store large amounts of data. This is a problem for many NFT use cases, especially tokens that represent digital collectibles or artwork, where storing the entire work could cost the equivalent of millions of US Dollars.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8uUZ_eR5-O0dXPMfDCDKQQ.png" /><figcaption>NFT in code form</figcaption></figure><p>As you can see from above when you own an NFT of a piece of art you own the token that has a reference to the URI of where that image lives. This brings up issues of ownership. If I can visit your URI using any web browser and view your NFT what is the meaning of your NFT? What is it that you own? What if the URI goes down? Do you own anything? An NFT only proves ownership of the token — not copyrights of the image. You own a unique and unchangeable reference to some data. An artist could give the NFT buyer copyrights of the image but those rights don’t come with most NFTs. Seth Green recently had a “Bored Ape” NFT stolen via a phishing scam and ended up having to buy it back for $100k more than he paid because the NFT bestowed the owner with copyrights of the image. Since Green planned on using the “Bored Ape” image on an upcoming television show he had to buy it back to legally be able to do this. Check out this article on it: <a href="https://news.bloomberglaw.com/ip-law/seth-greens-stolen-bored-ape-muddles-nft-legal-ownership">https://news.bloomberglaw.com/ip-law/seth-greens-stolen-bored-ape-muddles-nft-legal-ownership</a></p><p>Thanks for reading y’all more blockchain stories to come =)</p><blockquote>New to trading? Try <a href="https://medium.com/coinmonks/crypto-trading-bot-c2ffce8acb2a">crypto trading bots</a> or <a href="https://medium.com/coinmonks/top-10-crypto-copy-trading-platforms-for-beginners-d0c37c7d698c">copy trading</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7928cfa0fa9b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/things-i-wish-i-knew-8-months-ago-7928cfa0fa9b">Things I wish I knew 8 months ago…</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[My first Hackathon: HackMoney 2022]]></title>
            <link>https://medium.com/@otoolerj_42923/my-first-hackathon-hackmoney-2022-9ff3167e868f?source=rss-4dd6de0955ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ff3167e868f</guid>
            <category><![CDATA[hackathons]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[coinbase-wallet]]></category>
            <category><![CDATA[walletconnect]]></category>
            <category><![CDATA[web3modal]]></category>
            <dc:creator><![CDATA[Ryan O'Toole]]></dc:creator>
            <pubDate>Tue, 17 May 2022 14:49:22 GMT</pubDate>
            <atom:updated>2022-05-17T14:49:22.727Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m currently participating in ETHGlobal’s HackMoney 2022 (May6–27)and it’s been intense to say the least. I have four years of coding experience- two and a half years working professionally- and have transitioned into the world of blockchains, crypto, and web3. I’ve built an NFT, finished “Ethereum and Solidity: The Complete Developer’s Guide”, and built a complex dapp (decentralized app) that solves a real world problem the company Kickstarter faces. The past ten days I’ve experienced the full range of emotions- from uncontainable excitement to utter frustration to nagging doubt. The technologies are fairly new, the networks are vast, documentation can be hit or miss, and there isn’t as large of a community of developers documenting use cases compared to the traditional web. As much as this amalgamation of challenges has worn me down I’ve felt empowered by my resiliency to keep pushing forward- and it’s been a testament to my having made the right pivot in my career.</p><p>The first day of the Hackathon I searched through slides of other developers and tried to find people with similar experience levels that had exciting project ideas. I reached out to several people- one of which was this guy Vansh who had Hackathon experience, cool past projects (my favorite being a web3 drag queen game), and a great idea for HackMoney 2022. Vansh and I jumped on a zoom chat and over the next few hours some other people Vansh had been networking with joined the call and 4 hours later we had a team and a vision.</p><p>I jumped right into the code because I wanted to see what wallets I could connect with and what data I had access to during the transactions. I won’t give too much away but our project idea revolves around building software for a wearable hardware device with an embedded QR code that streamlines the payment process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q8cw3NTpX583fRyHxKDGcg.png" /></figure><p>I began recreating prototypes of pages in CSS our design person mocked up. During this time I was feeling great about my progress and growth. This was my second time using next.js and React hooks so I had a lot of reading to do- both in React and web3. This was about three to four days into the Hackathon and I felt great but realized I needed to take greater advantage of the resources available. There is $300,000+ in prizes being given by 30+ companies and they’re all offering mentorship and help with trouble-shooting. Once I had some confidence I began to dig into the lectures (live and archived) to see what we could integrate into our project, the prizes those companies were offering, and the conditions for qualifying. Once I began looking into all the resources and possibilities I immediately regretted not doing it sooner. My advice would be jump into the lectures and resources immediately to open your mind to the technologies and let the creative juices begin to flow.</p><p>At this point I wasn’t going to make the same mistake twice so I thought about what else I wasn’t doing. I got organized- <a href="https://trello.com/">trello boards</a> are an incredible free resource and help me a ton. They’re lists with notes that you can drag and drop- I keep several lists- doing, to do today, to do, done, and a list of HackMoney companies and their technologies. Then I got organized with my code- I brushed up on my git protocols especially branching and merging.</p><p>The following are things I have learned or in some cases been reminded of: Don’t do two things at once.I know this sounds simple but it’s easy to blur the lines when trying to diagnose what is wrong. I found myself using ethers.js because I wanted the experience but I was more comfortable using web3 (a similar library). When I was trying to get Web3Modal working I was following the ether.js examples and when I got frustrated I began trying web3 without following proper git protocol. This wouldn’t really be an issue because it is only a few lines of code, doesn’t conflict with ethers.js, and I commented out the other code- but sometimes I would try to change another thing too, maybe try to subscribe to the event via the provider (hey you never know). I found myself adding and removing more packages than I needed and at times going down a rabbit hole with two meshed examples from the docs. The feature I was having the most trouble with was Web3Modal which shouldn’t have been that difficult to install and I believe this in conjunction with coming really close to full functionality several times led me to be sloppy with my git protocol (I was sooo damn close).</p><p>I eventually abandoned following Web3Modal’s docs and instead used Coinbase Wallet’s Web3Modal docs (they’re a sponsor $16K in prizes). I was able to get the Web3Modal mostly working with Coinbase Wallet’s documentation but it wasn’t responding to click events for some wallets. I took advantage of the resources at my disposal and reached out to some of the sponsors from Coinbase Wallet. I reached out to another sponsor earlier to no avail but didn’t realize directing questions to @ExampleUser was what other people were doing and it seemed to be working for them. I found two active sponsors in the chat and used the @ feature to get a detailed response within a few hours. The below picture is what the Web3Modal looks like and when a user clicks on any wallet link the wallet should pop-up or lead you to a link to download it. My Web3Modal looked right but most of the links weren’t working properly at this point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AnuxEhD5_sjIdqoS" /></figure><p>During the time I was waiting for a response I hated myself for being so lax with version control. I had deleted so many node_modules and package.lock.json files and married so much code I forced out of that branch and reverted back to an earlier branch. Then I got a ton of errors about ‘polyfill-node-core-modules’ and spent way too much time looking on Stack Overflow. Stack Overflow is great but again I’d try something- it wouldn’t work- then I’d try something else but the file I added from the other Stackoverflow suggestion conflicted eventually. I advise looking for blogs because if they wrote a post they most likely solved the issue and are willing to go into detail. Here is the post on solving the ‘polyfill-node-core-modules’ problem: <a href="https://www.alchemy.com/blog/how-to-polyfill-node-core-modules-in-webpack-5"><strong>https://www.alchemy.com/blog/how-to-polyfill-node-core-modules-in-webpack-5</strong></a></p><p>At this point the wonderful sponsor at Coinbase Wallet messaged me and said my code looked good and she put it in a codesandbox and it worked: <a href="https://codesandbox.io/s/busy-goodall-tdmejq?file=/src/App.js:419-451">CodeSandbox</a>. I tested it and it was unexpectedly working like it should all except for coinbase wallet ironically. My browser was the issue because I tried the Web3Modal in other browsers and the Coinbase Wallet option was working along with everything else. The lack of code cleanliness didn’t help my environment in terms of libraries so I should have thought of CodeSandbox earlier to cut out those variables. More importantly I should have been using version control to keep only the packages I needed for what I was trying to do at the time with the corresponding code. I think conflicting libraries that I had removed by the time I reran my code in my dapp were the cause for the change in behavior of the other wallet links. Removing Coinbase Wallet from google chrome and reinstalling it didn’t work but it was something I should have tried sooner. Sometimes software can be weird and removing something and reinstalling it can fix anything from a bug to an older version causing an extension to not compile.</p><p>A helpful resource I found for git branching commands along with detailed explanations and diagrams to help you understand the git flow: <a href="https://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging">https://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging</a></p><p>I suggest if you’re testing wallets and experiencing problems you should use multiple browsers and have the different wallets installed on each of them. Before serious package integration / library attempts (1) commit (2) branch (3) follow git protocols. Thanks for reading!!! More Web3 posts coming soon…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ff3167e868f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building applications to scale]]></title>
            <link>https://medium.com/@otoolerj_42923/building-applications-to-scale-15f740d57f32?source=rss-4dd6de0955ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/15f740d57f32</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Ryan O'Toole]]></dc:creator>
            <pubDate>Tue, 11 Dec 2018 20:08:36 GMT</pubDate>
            <atom:updated>2018-12-11T22:48:24.273Z</atom:updated>
            <content:encoded><![CDATA[<p>An issue most nascent developers don’t have to deal with while building their first couple of applications is building to scale. The reason for this is your first application most likely won’t attract more than a few dozen users, unless your Mark Zuckerberg of course. The first time you’ll likely hear about building applications to scale is on one of your first interviews when the questions are asked of you, and instead of being a deer in headlight hopefully you’ll be more like a deer in a forest, intuitively making your way back through this article and into your first developer job. This article is not meant to be an exhaustive resource on building applications to scale, but a substantial introduction.</p><p>There are many things to consider when building applications to scale, and there’s not necessarily a predefined order of what to consider first, second, all the way to last. A logical place to start is by asking yourself if my app becomes insanely popular, what will be the first thing to break?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*akCKGL_Eva7llRMR" /></figure><p>Exactly! The database! Your database will eventually becomes inundated with requests, and even with a moderately popular app this will happen faster than you think. So what’s the work around? On my first interview I was asked this question and answered the database, then I confidently continued and said the workaround is to increase bandwidth. My interviewer gave me a stern no, that won’t work. I grew apprehensive, crossed my fingers and said i’d get a bigger CPU (Central Processing Unit). He was not impressed. Luckily he was really kind and explained to me you can get around this by making many copies of the database, creating a loop to send requests to each copy of the database. So if you had a million users per hour, but 20 databases fetching data on a loop, you’d only be dealing with 50,000 requests per hour in each database. This concept is known as load balancing; load balancing is a general concept that has applications beyond databases, it improves the distribution of workloads across multiple computing resources, such as computers, a computer cluster, network links, central processing units, or disk drives. Load balancing aims to optimize resource use, maximize throughput (the maximum rate something can be processed), minimize response time, and avoid the overload of any particular resource.</p><p>Same scenario, you app makes it big and you have a million users, If you pay for API calls, how can you avoid paying exorbitant amounts of money? My response to this was uhhh. Don’t be like me, learn from me! You could make key value pairs of the search and the result- stored in a database you create. When a request goes through on your app, you would send it to your database and retrieve the value with the corresponding key search term, if key/value is not in your database, send a request to the API and save that in your database. Doing this you’d only make an API request if that search term had never been searched before. This will save you a tremendous amount of money if your API charges per API call, or cost you no money if you’re allotted a certain number of API calls per hour/day and you’re able to not exceed this limit. This concept is known as caching, a cache is a hardware or software component that stores</p><p>In addition to the cost saving aspect of caching there are performance benefits as well. Caching enables future requests for data to be served faster; the data stored in a cache might be the result of an earlier computation or a copy of a fetch request to an external API. In either case caching will enable the data to be retrieved faster than when your program originally needed to make the computation or fetch request, and fetch requests are at the mercy of external factors like the API you are accessing so caching has the added benefit of circumventing an API that isn’t functioning properly. The more requests that can be served by the cache, the faster the system performs.</p><p>Thus far we’ve discussed how database issues are paramount to cost, efficiency, and building applications that don’t break as they grow. Performance issues are tied into this, but now we are going to really focus on performance, this is how to get your programming operating at the fastest possible speed. If there are database queries with long response times which could be bottlenecks to the application, it makes sense to improve them by indexing tables, refactoring code to reduce iteration, and optimizing the query itself. If you’re able to reduce the number of queries,then you’ll increase your application’s performance. Avoiding N+1 queries is a great way to optimize the query itself, although most people have no idea what N+1 queries are. N+1 queries happen when the code needs to load the children of a parent-child relationship (the “many” in the “one-to-many”). Most ORMs (Object-relational-mapping) have lazy-loading enabled by default, so queries are issued for the parent record then one for <strong>each</strong> child record. I’m sure you being the wise programmer that you are can clearly see that doing one query is better than doing N+1 queries because N+1 will flood the database with unnecessary queries.</p><p>To illustrate this consider a poetry app that has many poems written by different poets. We are using Ruby on Rails in this example:</p><p>#Poems model<br>class Poem &lt; ActiveRecord::Base<br> belongs_to :poet<br>end</p><p>#Authors model<br>class Poet &lt; ActiveRecord::Base<br> has_many :poems<br>end</p><p>If we wanted to list the five most recent poems on the sidebar of the homepage, along with the title and poet’s name we could accomplish the with the following code.</p><p>#In our controller<br>@recent_poems = Poems.order(published_at: :desc).limit(5)</p><p>#in our view file<br>@recent_poems.each do |poem|<br> Title: &lt;%= poem.title %&gt; <br> Author:&lt;%= poem.poet.name %&gt;<br>End</p><p>The above code will send six queries to the database. One to to fetch the five recent articles and then five for their corresponding poets. Since we are dealing with such a small number of additional queries we won’t notice the performance depreciate in any significant way, but when this is done on a large scale this can be disastrous.</p><p>The work-around to lazy loading is eager loading, which is a mechanism for loading the associated records of the objects returned by Model.find using the least amount of queries possible. In the previous example, if we use eager loading to fetch the data, the details of the poet will be loaded along with the articles. In Rails, ActiveRecord has a method called includes, which ensures that all the associated datas specified are loaded with the minimum number of queries. Let’s refactor our code to eager load associations.:</p><p>#In our controller<br>#Using includes(:poets) will include poets model.<br>@recent_poems = Article.order(published_at: :desc).includes(:poets).limit(5)</p><p>#in our view file<br>@recent_poems.each do |poem|<br> Title: &lt;%= poem.title %&gt; <br> Author:&lt;%= poem.poet.name %&gt;<br>end</p><p>There are a few more areas I want to touch upon, albeit in less detail as the earlier topics. As a developer you need to understand building applications to scale as the potential of an application to grow in time, being able to efficiently handle more and more requests per minute (RPM). It’s not just a simple tweak you can turn on/off, it’s a long-time process that touches almost every single item in your stack, including both hardware and software sides of the system. As applications begin to really grow you as a developer need to embody this holistic approach in every decision you make.</p><p>Choosing the right hosting is paramount to having your code run as efficiently as possible. It’s very important to have proper server infrastructure and configuration because no matter how clean and thoughtful your code is it can never reach its full potential without proper hosting. You can save yourself a lot of time and headache by selecting proper tools and providers. Amazon EC2 provides auto-scaling features and Docker offers docker-compose scale.</p><p>An incredibly simple way to maintain an efficient codebase is to update on a regular basis. Keep all of your dependencies, libraries, and programs up to date by checking for updates several times a month. This may seem peripheral but you’d be amazed how several outdated versions of programs and dependencies can affect performance.</p><p>Thanks for taking the time to read my article, if you found it helpful go ahead and give me some claps, and be sure to check back next week for my next blog post. Take it away Napoleon:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*zxwEUyeV1iwSgFQz.jpg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15f740d57f32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL]]></title>
            <link>https://medium.com/@otoolerj_42923/sql-f470aeb37243?source=rss-4dd6de0955ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/f470aeb37243</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Ryan O'Toole]]></dc:creator>
            <pubDate>Wed, 28 Nov 2018 15:35:55 GMT</pubDate>
            <atom:updated>2018-11-29T15:53:49.842Z</atom:updated>
            <content:encoded><![CDATA[<h3>SQL- Not Some Quasi Language</h3><p>I recently began reviewing SQL — Structured (or Standard) Query Language in preparation for an interview I had. During my time in coding bootcamp we learned about SQL for several days, but after a relentless wave of new material I forgot many of the main features of SQL and just how powerful it is. SQL (Structured Query Language) is a language for managing data in a database. The sole purpose of SQL is talking to databases, thus your might hear it referred to as a “special purpose”, or “domain specific” programming language. You won’t be using SQL to write the your next app, but you will probably use it to interact with the database that powers it. Some of my forgetfulness was not entirely my own fault, soon after learning SQL we began using Ruby on Rails, and Rails automates the SQL commands you send to your database with Ruby code.</p><p>SQL is used by many different database systems such as MYSQL, PostgreSQL, SQLite and many more. During my studies we used SQLite because it has a low barrier to entry, and is simple to get up and running, but each database system has its own strength and weaknesses to consider when deciding which to use for what purpose. For this article we are going to focus on SQLite.</p><p>Relational Databases like SQLite store data in a structure we refer to as a table. You can think of a table in a database a lot like you would a spreadsheet, we define specific columns in our table, and then we store any number of what we refer to as ‘records’ as rows in our database. A record is just information referring to one specific entry. Column names follow the convention of lowercase letters written in snack_case, thus a column name of first_name would be written just like that. Tables should always have a Primary Key column, which will act as an unique identifier for that record. Primary Keys allow for easy access to your table, and later on when your database grows in complexity Primary Keys will become the Foreign Keys of another table which will allow you to join tables and bring your search queries to the next level.</p><p>If you are using a Mac and are on OSX version of 10.4 or greater, you probably already have SQLite installed, open up your terminal and paste, which sqlite3, if you get back usr/bin/sqlite3 then you have a working version of sqlite already installed on your system. If you don’t go here, <a href="https://www.sqlite.org/download.html">https://www.sqlite.org/download.html</a>, and look for your operating system and download and install the appropriate binary. Create a database with the, sqlite3 database_name.db, command. We will call ours pet_database so run, sqlite3 pet_database.db, then we can create a table with the following statement:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*xZp60R1GtnPciEH0ScUPrg.png" /></figure><p>We are creating a table named cats. As discussed earlier every table we create should have a Primary Key column, which is auto-incrementing in SQLite and will enable us to reference and easily access information. We are also initializing this table with two columns, name and age, and these columns have a data type associated with them to tell SQLite what type of data will be stored in these columns. Text is storing plain old text and integer is storing a number. There is also a real data type that stores plain old decimals up to 15 characters long. Why data types? This makes it easy for SQLite to perform operations on data in the tables because it knows what type of data it is working with. You can alter the table with commands like: <strong>ALTER</strong> <strong>TABLE</strong> cats <strong>ADD</strong> <strong>COLUMN</strong> breed TEXT; To check that these alterations worked we can use the .schema command that will show us our current table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*WgfhA8ajaCyCAEv5R7CBag.png" /></figure><p>The Alter statement isn’t here, instead SQLite has update our original create statement. The schema reflects the current structure of the database, which is reflected as the CREATE statement necessary to create that structure.</p><p>To delete a table use the: <strong>DROP</strong> <strong>TABLE</strong> cats; Let’s not do that now I just wanted to make you aware. You can execute these commands in a text editor, for time’s sake I’m not going to go into that, but I wanted to make you aware that this would be the norm and it is very simple to implement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/0*1MyMZaVuTis1aK4C" /><figcaption>Ok let’s get this party started</figcaption></figure><p>To insert data into the cats table, type the following command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uKSz83rapewiI8djkoB0IA.png" /></figure><p>To make this article concise let’s assume we added several cats using this same syntax. Now if we want to select cats we can do it using a SELECT statement:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*0VfsmpEow7s_AGt3VltKtA.png" /></figure><p>Which will return:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*9mACRlaPbkaeBM5VsRuMww.png" /></figure><p>A faster way to get data from every column in our database is to use the ‘wildcard’ selector: <strong>SELECT</strong> <strong>*</strong> <strong>FROM</strong> cats; This would return the same information in the image above. We can also select the values from a single column by simply specifying only that column in the SELECT statement: <strong>SELECT</strong> name <strong>FROM</strong> cats; Cool beans. This is all cute and stuff, but this doesn’t seem so special.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LFjRFboLxlZ2ir4g" /></figure><p>The power of the SELECT statement really becomes evident when used in conjunction with the WHERE clause. Using the WHERE statement we can select specific cats we are looking for according to their values. So we can select all cats where name equals Hannah or all cats with an age greater than 4 like this: <strong>SELECT</strong> <strong>*</strong> <strong>FROM</strong> cats <strong>WHERE</strong> age &gt; 4;</p><p>We can use update statements to update a specific value, the boilerplate syntax looks like this: <strong>UPDATE</strong> [<strong>table</strong> name] <strong>SET</strong> [<strong>column</strong> name] <strong>=</strong> [<strong>new</strong> value] <strong>WHERE</strong> [<strong>column</strong> name] <strong>=</strong> [value];</p><p>And of course there is a delete statement: <strong>DELETE</strong> <strong>FROM</strong> [<strong>table</strong> name] <strong>WHERE</strong> [<strong>column</strong> name] <strong>=</strong> [value];</p><p>Which would look something like in our example: <strong>DELETE</strong> <strong>FROM</strong> cats <strong>WHERE</strong> id <strong>=</strong> 2;</p><p>This delete statement uses the Primary Key to delete the record with the corresponding id of 2. That’s it? Pretty simple eh?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*e8eB5hZd2fiEsZ7n" /></figure><p>Ok that’s not even close to the half of SQL, but rest assured we are getting close to the end of this article. There is one more important concept I want to discuss with you, which is table relations. This is where you’ll be able to see the true power of SQL and understand why it is such a powerful language. Let’s keep things simple and continue along with our cats example. Cats usually have owners, and a veterinarian for example, would need to know which cats belong to which owners. So to relate a cat to it’s owner, we would create an Owners table: <strong>CREATE</strong> <strong>TABLE</strong> owners (id INTEGER <strong>PRIMARY</strong> <strong>KEY</strong>, name TEXT); then we would ass a owner_id column to the cats table: <strong>ALTER</strong> <strong>TABLE</strong> cats <strong>ADD</strong> <strong>COLUMN</strong> owner_id INTEGER;</p><p>Now we’d make an owner: <strong>INSERT</strong> <strong>INTO</strong> owners (name) <strong>VALUES</strong> (“mugumogu”); then we’d fill in the owner_id column in the cats table (which is the foreign key in the cats table) to reflect that mugumogu has two cats: <strong>UPDATE</strong> cats <strong>SET</strong> owner_id <strong>=</strong> 1 <strong>WHERE</strong> name <strong>=</strong> “Maru”; <strong>UPDATE</strong> cats <strong>SET</strong> owner_id <strong>=</strong> 1 <strong>WHERE</strong> name <strong>=</strong> “Hana”;</p><p>The reason we put the owner_id on the cats table, and not the cat_id on the owners table is because of the relationship between owners and cats. In this example a cat belongs to an owner, and an owner can have many cats. Since a cat belongs to an owner, the cat table gets the owner_id column (known as the foreign key here since it is the primary key of the owners table). This is not arbitrary; think about if an owner had multiple cats. We’d have to grow the owner’s table out horizontally. And since crazy cat ladies are a thing, this table could become unmanageable quickly. On the other hand each cat only has one owner (at least in this example) so it makes sense to put the owner_id in the cats table so we don’t have to deal with unmanageable tables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*65eTkZwXasuqNn6oBc9ydA.png" /></figure><p>We could execute a simple SELECT statement to grab all the cats with owner_id equal to 1, but what if we wanted information about both the cats and owners. Long and behold, Join statements!</p><p>There are four types of Join statements: Inner Join, Left Join, Right Join, Full Join. An inner join returns all the rows where there is at least one match in BOTH tables, a left join returns all the rows from the left table, and the matched rows from the right table, a right join returns all the rows from the right table, and the matched rows from the left table, and an outer join returns all rows when there is a match in one of the tables. All of the aforementioned JOIN keywords can be crafted into SELECT statements to achieve the described return values.</p><p>Let’s walk through each type of Join statement, then we are DONE! For time and space sake, I added a bunch of data into our tables so just follow along and you’ll get the idea.</p><p><strong>Inner Join statement</strong>-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0F0l72JEEbnFZtvPEo9tvw.png" /></figure><p>Here we are selecting the name and breed from the Cats table, and the corresponding name from the owner’s table. We use the Table_name.Column_name notation. Then we join the two tables together using the INNER JOIN keyword, and finally we tell our query how to join the tables by telling it which column in each table function as the primary/foreign keys. And boom goes the dynamite:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yfkBU2I-39aRvmyOq5gjmQ.png" /></figure><p>Note that this INNER JOIN will only return cats that have an owner!</p><p><strong>Left Join Statement</strong>-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DjA6hSuKRntoISW_S9wsVg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RH2byfJGcXMP94Cu8jqD0w.png" /></figure><p>Like i said earlier a LEFT OUTER JOIN will return all the rows from the left table (cats in this example) and the matched right rows.</p><p>RIGHT OUTER JOIN and FULL OUTER JOIN aren’t currently supported by SQLite but we will go over them because other databases like Postgres do support these types of joins.</p><p><strong>Right Join Statement</strong>-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z-JgYKpvSEguHcAo-Osv9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hG2cn0Jw4jV9kSnOPFZhSQ.png" /></figure><p>Notice Lil’ Bub is gone, but the owner Penny with no cats is here. This is because a RIGHT OUTER JOIN will select all of the data from the right (second table) and only the matched data from the first table.</p><p>Drum Roll Please:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/0*w8YcxMg1nLkC_cPG" /></figure><p>And finally finally finally last but not least:</p><p><strong>FULL OUTER JOINS</strong>-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FAKJpUwbNNPMPuU7m1I37Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bgh-xPSUD2EBEuWRjmeiOw.png" /></figure><p>Our result includes cats without owners and owners without cats AKA all of our data. I hope this was helpful, drop a comment if there is anything that needs clarification and I will get back to you as soon as I can. If you enjoyed this please clap and bookmark my blog, I try to write a new post each week. Cheers!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*Ym7awkLlZ_4Yh0Lx" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f470aeb37243" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Don’t feel DOM! Let me do it for you…]]></title>
            <link>https://medium.com/@otoolerj_42923/dont-feel-dom-let-me-do-it-for-you-36d916cdb232?source=rss-4dd6de0955ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/36d916cdb232</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[document-object-model]]></category>
            <category><![CDATA[xml]]></category>
            <dc:creator><![CDATA[Ryan O'Toole]]></dc:creator>
            <pubDate>Mon, 05 Nov 2018 17:41:02 GMT</pubDate>
            <atom:updated>2018-11-05T20:18:39.959Z</atom:updated>
            <content:encoded><![CDATA[<h3>Don’t feel DOM! Let me do that for you…</h3><p>I had a first-round interview this week, it was mostly HR questions but my interviewer asked one technical question: What is the DOM? Easy enough, I use the DOM almost everyday, it’s what I manipulate when I’m in the console in my Google developer tools. My answer was something like this: The DOM, the document object model, is the conjunction of HTML, CSS, and Javascript that you interact with in your browser. Not the worst answer, but I’ve since learned there’s much more to it than that. My interviewer asked if i could elaborate, which I attempted to do but ended up simply rephrasing what I had already said. The interview continued and went back to HR style questions mostly focused on my transition from a MFA in Poetry to software development and why I think I would be a good fit with the company. I never made it to the next round of interviews, I was naturally frustrated because I use the DOM, I’m incredibly familiar with it, but why can’t I explain it?</p><p>Me, being the inquisitive and determined programmer that I am, decided to embark on a journey to not only understand what the DOM is on a complex level but to be able to explain it concisely in very simple layman terms. In addition I wanted to be able to do the same for any terms that came up in the definition of the DOM i.e. API(Application Programming Interface), XML, HTML(Hyper-Text Markup Language).</p><p>I read through many definitions of the DOM, but ended up more confused than when i started, each definition seemed to emphasize some different feature or nuance of the DOM. I decided to change my search from “What is the DOM?” to “What is the DOM in layman terms?” Eureka! I found this site, <a href="https://www.quora.com/What-is-meant-by-DOM-in-simple-words">Helpful Site</a>, which I found extremely useful. I read through all the definitions of the DOM in layman terms, and these stripped down definitions that focused solely on the most essential features of the DOM illuminated not just my understanding of the DOM, but also the more complex readings I had at first encountered. Ok. So here it is. The DOM.</p><p>The DOM is nothing but the Document Object Model. It is nothing but the API (Application Programming Interface) in HTML (Hypertext Markup Language) and XML (eXtensible Markup Language) document. It is the specification for how objects in a web page(e.g. Image, text, tag, links, etc. ) are represented. If your like me, you’re still lost here, but there are some important pieces of this definition that will help us get some footing. So the DOM, Document Object Model, is an Application Programming Interface in two types of language documents. It is a <strong>specification</strong> for how objects in a web page are represented.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*T9dBsnRiLJyQ6cEA.jpg" /></figure><p>My Spidey sense are tingling. To get to the next important piece of this definition we need to explore an API, Application Program Interface, which is a set of routines, protocols, and tools for building software applications. Basically, an <strong>API</strong> specifies how software components should interact. Ok so it seems like the DOM, is the Application Programming Interface that specifies how software components should interact in HTML and XML document. So the DOM is a set of routines, protocols, and tools for building software applications in an HTML and XML document. I’m starting to wrap my head around this.</p><p><strong>Ok, so then where does Javascript come into play?</strong></p><p>The definition I gave to my interviewer was: The DOM, the document object model, is the conjunction of HTML, CSS, and Javascript that you interact with in your browser. So your Javascript code is nothing but DOM API calls. It internally uses DOM API’s to traverse the tree and do some operations. So Javascript uses the Document Object Models’ Application Programming Interface to traverse the tree and do some operations. DOM- Allows you to traverse the tree and manipulations. Wait? When did we start talking about trees?</p><ol><li>Documents have a logical structure which is very much like a tree.</li><li>This tree contains the nodes (Which are optional — But must in DOM. Which means even if you don’t write head tag DOM will add it)</li><li>Nodes are nothing but elements in our HTML markup.</li><li>The tree is so arranged that we can easily traverse any node in it</li><li>The traversing and the manipulation part is done using DOM API’s.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IJbD7TNORfiE9qhDCLvjVg.png" /></figure><p>Document Object Model is a in-memory object representation for XML elements loaded into memory. Each element shall have as many children possible, but one child object can have only one parent, hence this forms a Tree hierarchy. When parsing HTML, browser creates DOM structure, that is nothing but object tree structure, HTML element is top most parent called root. You can add/remove HTML elements dynamically into loaded DOM structure to have a more interactive web page.</p><p>With the Document Object Model, programmers can create and build documents, navigate their structure, and add, modify, or delete elements and content. Anything found in an HTML or XML document can be accessed, changed, deleted, or added using the Document Object Model, with a few exceptions — in particular, the DOM interfaces for the internal subset and external subset have not yet been specified.</p><p>Document Object Model, in simple terms, is the HTML code along with the styles associated with that HTML, and some methods which make available this HTML as manipulatable objects. All the HTML elements and all sorts of events come under DOM, and so does some standard properties and methods, as decided by <a href="https://en.wikipedia.org/wiki/World_Wide_Web_Consortium">W3C</a> peeps. These properties and methods are then accessed through JavaScript. Almost any time a website performs an action, such as rotating between a slideshow of images, displaying an error when a user attempts to submit an incomplete form, or toggling a navigation menu, it is the result of Javascript accessing and manipulating the DOM.</p><p>The Document Object Model (DOM) is a programming API for HTML and XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated. In the DOM specification, the term “document” is used in the broad sense — increasingly, XML is being used as a way of representing many different kinds of information that may be stored in diverse systems, and much of this would traditionally be seen as data rather than as documents. Nevertheless, XML presents this data as documents, and the DOM may be used to manage this data.</p><p><strong>How do i interact with the document object model?</strong></p><p>The DOM tree view in the Chrome DevTools Elements panel displays the DOM structure of the current web page. Live-edit the content and structure of your page through DOM updates. The DOM defines your page structure. Each DOM node is a page element, for example, a header node, paragraph node. Live-edit the content and structure of your pages through the rendered DOM. But remember, you can’t modify source files through DOM changes in the Elements panel. Reloading the page erases any DOM tree modifications.</p><p>To access the DOM tree view in Chrome DevTools, simply open any web page on your browser and hold down at the same time: (option, command, J) and you will see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_4lCy17QLy7UwDgrPkg7vg.png" /></figure><p>There are two sides, the browser window(left) and the DOM tree view(right). If you look in the top left corner of the DOM tree view(right side of the screen) you will see a little pointer, and when you click it it will turn blue- now you can select any element in the displayed browser window, see that element’s HTML code, and manipulate it. Here you can see that the heading of my blogpost is simply an h1 tag. If you look at the screenshot below you can see that my profile picture is simply an img tag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XRHUWSwRPfAjYukkH0RoFw.png" /></figure><p>Now if we want to have a little fun we can manipulate the DOM and make the browser reflect those changes. Once again we get into our Chrome DevTools by holding down (command, option, J), then we can select any element in the DOM by clicking the arrow pointer in the top left corner of the right side of the screen, it will turn blue. Once it turns blue you can select any element on the page, I chose to select the title of my blogpost, which then brings you to that element in the DOM tree view, which is an h1 element. By clicking on the text of the title inside the h1 tags you will see a cursor and with it you can edit and manipulate the title.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tvbnGdOY6Uz8FoAEh59zmw.png" /></figure><p>Once it has been manipulated to your standards simply click enter and the browser will update to reflect those changes. The one caveat is these changes are not permanent, you are only manipulating the DOM on your computer, you are not actually changing any source code for my blog, and when you refresh the page your will see the original source code for my blog. That being said it is a lot of fun right meow!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*euC93yhTuQpNzRq7ozMgpw.png" /></figure><p>Almost done, I promise. I began this blog post with a desire to express the DOM, and any and all definitions I encounter along the way in the simplest terms possible.</p><p>So here we go:</p><p>HTML- <strong>Hypertext Markup Language</strong> (<strong>HTML</strong>) is the standard markup language for creating web pages and web applications. HTML provides a means to create structures documents by denoting structural semantics for text such as headings, paragraphs, lists, links, quotes, and other items. HTML can embed programs written in a scripting language such as Javascript, which affect the behavior and content of web pages. With Cascading Style Sheets (CSS) and Javascript, it forms the triad of cornerstone technologies for the World Wide Web.</p><p>XML- <strong>eXtensible Markup Language (XML)</strong> is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. The design goals of XML emphasize simplicity, generality, and usability across the internet. Although the design of XML focuses on documents, the language is widely used for the representation of arbitrary data structures such as those used in web services. Several schema systems exist to aid in the definition of XML-based languages, while programmers have developed many APIs to aid the processing of XML data much like HTML. XML was designed to store and transport data. XML was designed to be self-descriptive.</p><p>API- <strong>Application Program Interface (API)</strong> is a set of routines, protocols, and tools for building software applications. Basically, an <strong>API</strong> specifies how software components should interact.</p><p>DOM- <strong>Document Object Model (DOM)</strong> is an Application Programming Interface in XML and HTML documents. It is a <strong>specification</strong> for how objects in a web page are represented. The DOM is a set of routines, protocols, and tools for building software applications in an HTML and XML document. With the Document Object Model, programmers can create and build documents, navigate their structure, and add, modify, or delete elements and content. Document Object Model is the HTML (or XML) code along with the styles associated with that HTML (or XML), and some methods which make available this HTML (or XML) as manipulatable objects. These properties and methods are then accessed through JavaScript. Almost any time a website performs an action, such as rotating between a slideshow of images, displaying an error when a user attempts to submit an incomplete form, or toggling a navigation menu, it is the result of Javascript accessing and manipulating the DOM.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36d916cdb232" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Do as I say, not as I’ve done]]></title>
            <link>https://medium.com/@otoolerj_42923/do-as-i-say-not-as-ive-done-d9d1ac7bdc3d?source=rss-4dd6de0955ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9d1ac7bdc3d</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ryan O'Toole]]></dc:creator>
            <pubDate>Tue, 23 Oct 2018 20:53:26 GMT</pubDate>
            <atom:updated>2018-10-24T16:14:11.474Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m currently in the process of applying for jobs and interviewing for companies. I received two coding challenges thus far, and this blog post is in regards to the second which was a take home open book challenge. Below i attached the requirements/instructions that i received. Like most recent graduates from bootcamp, i haven’t coded as much as i would like since graduation as i have been preoccupied with getting my resume, linkedIn, project demos, and old projects up to date, as well as applying to jobs, networking, and studying algorithms. Thus when i started this coding challenge it took a little warming up to get back into the swing of things. In this post i will discuss the structure i chose for my files and components, as well as some technologies/libraries i imported to meet the requirements and spruce things up. I will also go into CORS errors and correct version of node.</p><p>Here are the instructions i received:</p><h4><strong><em>Build a simple web page that lets you search for recipes using this simple recipe API: (http://www.recipepuppy.com/about/api/)</em></strong></h4><h4><strong><em>Requirements:</em></strong></h4><h4><strong><em>● A responsive landing page with a search bar. The user should get a list of results as she types (no extra buttons). The page should work on both web and mobile.</em></strong></h4><h4><strong><em>● We don’t want to spam the recipe API, so we should send a request only when the user has stopped typing</em></strong></h4><h4><strong><em>Additional suggestions (pick one or more if you wish):</em></strong></h4><h4><strong><em>● Ability to favorite a recipe and retrieve it later. It does not have to be re-fetched from the API and can be stored locally</em></strong></h4><h4><strong><em>● Ability to filter the search result</em></strong></h4><h4><strong><em>● Additional UI elements (thumbnail, description, pagination, infinite scroll, etc.)</em></strong></h4><h4><strong><em>● Better API handling (cancelling last request if user types extra letters before request finishes, retrying strategy if network connection fails, etc.)</em></strong></h4><p>The company i was interviewing with also gave some suggestions- they said ask questions because it is purposely vague, only spend a few hours working on it, and focus on code organization as opposed to making the UI pretty. The first thing i noticed was the requirements were mutually exclusive. How can a user get a list of results as they type(which would require making fetch requests to the API as they are typing) and also only send a request when the user stops typing. I thought about this for a while, then asked two of my teachers and they confirmed my suspicions. So i sent an email to the company because they told me to ask questions; i basically said there are two options: 1) To set a timer that sends the request to the API once the user has stopped typing for a specific interval (1–2 seconds perhaps). 2) To throttle the API calls, so that a request only gets sent once every (1–2 seconds) so that the user gets a list of results as she types and the request goes through once the user stops typing. The first method wouldn’t get a list of results as the user types (unless they paused mid typing), but would only send the request once the user stops typing for an interval of time. The second method would get a list as the user types, but would not only send the request when the user has stopped typing since it would send a request every (300 milliseconds) in this example. Then i said I believe the number 2 is the best solution, because it won’t spam the recipe API, and will give users a more dynamic experience. More on how i accomplished this throttling later, let’s jump into the meat now.</p><p>For this coding challenge i choose to code in Javascript, and utilized React, which is a Javascript library for building user interfaces. If you don’t have experience with React check out these docs: <a href="https://reactjs.org/">ReactDocs</a> and/or read on- i try my best to be write this post in such a way that you can understand without knowing React. I also utilized Semantic UI for styling, and Lodash, which is a modern JavaScript utility library delivering modularity, performance &amp; extras, for its debounce feature. The debounce feature is how i accomplished throttling that i talked about earlier!</p><p>The first problem i ran into was updating to the correct version of node in order to create my React Frontend. Turns out i had to uninstall NPM, which is the package manager for JavaScript and the world’s largest software registry, so i could install NVM, update to the latest version of node, then reinstall NPM. This took a decent amount of reading to figure out because it was the first time i encountered this problem, here is great article explaining the differences between <a href="https://www.quora.com/What-are-the-difference-between-node-and-nodejs-npm-vs-nvm">NPM vs. NVM</a></p><p>I sent a request to the API i was given for the coding challenge using Postman, which is the only complete API development environment, for API developers, used by more than 5 million developers and 100,000 companies worldwide. I used Postman to test a “GET,” request and the API worked, i was given a response with an array of several recipe objects. Ok now smooth sailing, right? Time to start coding! Think again. I created a search bar component in my react app and then sent a request to the API using the search bar. I received a CORS (Cross Origin Resource Sharing) error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9c8CDIR2ng4jnrR4.jpg" /></figure><p>Naturally Scooby and I were confused, but after consulting one of my former teachers he informed me that Postman isn’t susceptible to CORS errors, but my React app is. More on CORS errors <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">here</a>!</p><p>The ideal remedy for CORS errors is to setup a Proxy Server. If you can’t modify the server, that is to say you don’t control the backend(the API in this instance), you can run your own proxy. <strong>And</strong> this proxy can return the Access-Control-Allow-Origin header if it’s not at the Same Origin as your page. Instead of sending API requests to some remote server, you’ll make requests to your proxy, which will forward them to the remote server. More on that <a href="https://github.com/Rob--W/cors-anywhere">here</a>! The instructions for the project were to not spend too much time on it, and setting up a proxy would require me to have a backend in addition to taking the time to setup the proxy. After much reading and consulting some of my programmer friends i decided to utilize, <a href="https://cors-anywhere.herokuapp.com/">https://cors-anywhere.herokuapp.com</a>, which solves the CORS errors, albeit in a less than ideal way. All you have to do is put the above link before the URL you are fetching from. I chose to go this route because of the time constraints of this coding challenge, i wanted to focus more on the architecture and code of my frontend, as well as gain experience setting up a db.json server on the frontend (which i had never done before) to meet the stretch goal of having the ability to favorite a recipe.</p><p>Ok! Now we are ready to code. I mapped out what my project would look like, known as creating a wireframe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uzPEVqV_Fbos_z135MitSw.jpeg" /></figure><p>This step, which at first glance seems like a waste of time, is paramount to success. By creating a wireframe of your project you will save yourself a lot of time down the road by not having to dig yourself out of a self created hole because you did not plan out your components and how they interact with each other. Think about how you want your app to look when creating a wireframe, then think about what each component does when you click it or enter text (makes a fetch request/calls a function etc.) My first component i made was the search bar, i needed to make it a controlled component so that the state of searchTerm updates based on user input. In HTML, form elements such as &lt;input&gt;, &lt;textarea&gt;, and &lt;select&gt; typically maintain their own state and update it based on user input. In React, mutable state is typically kept in the state property of components, and only updated with <a href="https://reactjs.org/docs/react-component.html#setstate">setState()</a>. We can combine the two by making the React state be the “single source of truth”. Then the React component that renders a form also controls what happens in that form on subsequent user input. An input form element whose value is controlled by React in this way is called a “controlled component”. I accomplished this by setting the value of the search bar to this.state.searchTerm, and then putting an onChange function to update the searchTerm state as event.target.value of the search bar onChange event fires. State is a javascript object that gets managed within the component; every time the user changes the search term in the search bar i update the state of a variable i named searchTerm. Props are short for properties, they get passed to components but aren’t created in the one they exist; that is to say if i pass state to another component it becomes props in the receiving component when i use it (more on that later!).</p><p>In React there is a component hierarchy; state can only be passed down to “lower” or “child” components. If you need to pass state up the hierarchy, you need to create a function in a more “parent” component, then pass that function to the child component, then call that function in the child component with the state from the child component. Trust me, it’s a lot simpler when you see what i’m talking about, here is my component hierarchy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I7XQvYojHJJg-3nbeQApaQ.jpeg" /></figure><p>Now that i have my input in the search bar updating state as the user types, i will send the searchTerm, which is state, up to App by calling a function that i passed down from App. Now i have the searchTerm in App; I will send a “GET,” request to the recipe API via the fetch function utilizing the searchTerm to retrieve an array of recipe objects. I will save the array of recipe objects in state in my App component, as recipes and recipesFilter(more on this later) then pass the array down to recipeList and Filter respectively. Now that i have the array i received from the API(we’ll focus on recipes now more on recipesFilter later), i can map through the array in the RecipeList component and pass each object i iterate through down to the Recipe component. Inside recipe i can control what gets shown in the recipe card. I utilized Semantic UI to create the recipe cards, i highly recommend semantic it is simple, pretty, and effective. Here is a link to <a href="https://react.semantic-ui.com/">Semantic Ui React</a>! Below are screenshots of my App and SearchBar component so you can follow along with this paragraph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xIJFAKHVRrosT42jGQtNSw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mYfBmZZL8REkHHh-XVPb7Q.png" /></figure><p>Ok that was a lot. But now we are ready to rock and roll. The hierarchy i choose for my components (as shown in the wireframe diagram) was chosen carefully. I put my fetch requests in the top component of my hierarchy due to the needs of this app; normally i strive to have most parent component as empty as possible, i usually just have components that i am returning in the render. The reason i did this was because i have a search bar to filter through recipes by ingredients, so i have to pass the array of recipe objects i receive from the fetch request to my Filter and RecipeList components. Normally i would have done my fetch request inside my RecipeList component; after all RecipeList is “responsible” for the array of recipe objects. If i did this i would have had to put a function in app, call that function in RecipeList to send the array of recipe objects to app, then send this array to Filter from App. If i did this i would have had to have a function in App, and my code would be a less clear to the reader. Remember most of the code you write as a developer is read many times, so be a team player and write clear code! I feel my code is pretty self explanatory because the reader sees my most parent component, sees my fetch requests in that component, and can easily follow the flow downwards.</p><p>In React we want to have simple components, in the sense we don’t want them to have more than one responsibility. SearchBar should only be responsible for SearchBar; all the logic in this component must only pertain to the search bar. This goes for coding in general, not only React, and this way of developing is known as the Single Responsibility Principle. My first blogpost goes into details about this principle, and how it connects to Taoism, an ancient Chinese philosophy and religion. The term was introduced by Robert C. Martin and he expresses it as a class should only have one reason to change. Or to put it another way classes should have only one responsibility. By concerning itself with the dynamic, it creates a way of doing that is flexible, mutable, and results in a more robust program. This makes modifying or adapting your code much easier because if a class only has one reason to change, you know exactly where to go to change something, and you don’t have to worry about messy and time costly code breakups. Class and component can be used interchangeably in this definition. So if there is an issue with the SearchBar component and i need to change my code, i know these changes won’t have unintended consequences.</p><p>Please please please please follow this principle. I began my final project at my coding bootcamp, The Flatiron School, not adhering to this principle. I was just excited to get things working so i didn’t really bother with the principle, but after a few days of coding anytime i needed to change one thing i had to find it which was quite the process because my code was such a mess, then when i changed it there would be unintended consequences because everything was so intertwined. I spent an entire ten hour day solely reorganizing my code, that is to say i didn’t add a single line or new feature, i just unscrewed myself. After i organized and simplified my code i was blown away by how easy everything was, if i wanted to change to change the title for my InputJumbler component i went to my InputJumbler component and it was right there. When i got bugs and would go into a specific component to fix them, there were hardly ever unintended consequences because i untangled all my code. Learn from my mistakes, i made them so you don’t have to!</p><p>We’re almost done i swear, just three more things. I spoke about passing state around and component hierarchies and i wanted to mention that Redux, which is a predictable state container for Javascript apps. I know i won’t bring back the Scooby Doo meme but i felt the same when i first heard that definition. Redux acts as the single source of truth for all your state! It’s a Javascript object that holds all your state. It takes a good day of reading and setup to get it going, but once you have it you don’t have to worry about passing around state because it’s all contained in your store which is the Javascript object that holds all your state. You will still need a component hierarchy, and sometimes you will still pass state around like we are doing in this post but way less often. Redux really simplifies your life especially as your app gets more and more complex. Ok, two things left!</p><p>The throttle function i spoke of earlier was imported from the Lodash library. If you look at the screenshot of my App component, right under the render at the bottom of the page and before the return i set a variable equal to this function like this:</p><p>const recipeSearch = _.debounce( (searchTerm) =&gt; { this.recipeSearch(searchTerm) }, 300)</p><p>recipeSearch is a function that sends a “Get” request to the recipe API i’m using; all i did was import lodash at the top of the page (import _ from ‘lodash’;) then i used the _ variable that i assigned to lodash to utilize the debounce function. All this function does is call an already existing function (recipeSearch) and set a time in milliseconds (300) as its second argument. This is how often you want this function to fire; so every 300 milliseconds as the user is typing it will send a “Get,” request to the API. It’s a great tool and it will impress the company you are interviewing with if you bring it up as a solution to a problem. One thing left!</p><p>To simplify your life and fetch requests, especially with larger applications, use an Adapter (look below for screenshot). An adapter is just a file where you keep your fetch requests. To utilize fetch requests in your adapter files just import the Adapter file at the top of the component you need a fetch request in like this: import Adapter from ‘../Adapter’, then to call the function with the fetch request just put Adapter. in front of the function call that is in the adapter file like this: Adapter.getRecipesAPI(searchTerm). If you need to see this for it to click just scroll back to the top of this post and find the screenshot of the App component. I know what you thinking- why would i ever want an Adapter when i can just do the fetch request in the component without having to make an Adapter file or import anything when i need to utilize the fetch? Using an Adapter, especially if your working on a larger app/project will make your life some much easier if you decide to host your project online. Right now i’m sending requests to `localhost:3000/recipes` when i want to save something to favorites, or retrieve my favorites when i need them. But if i choose to host this project live, then my URL will change and i’d have to go through all my files and change every fetch request from `localhost:3000/recipes` to something like `mycoolapp.heroku.com`. In addition to making your code more dynamic, flexible, and adaptable(sorry i couldn’t help myself) using an Adapter will also clean up your code- you will have less code in your components and your code will still be clear and concise. Ok that’s it. Good luck! Let me know if you have any questions, comments, concerns- you can reach me at otoolerj@gmail.com! Thanks for reading =)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Co8nhKqi82L91VPjkY4zhA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9d1ac7bdc3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redux (the flux capacitor of React )]]></title>
            <link>https://medium.com/@otoolerj_42923/redux-the-flux-capacitor-of-react-623a72ebda15?source=rss-4dd6de0955ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/623a72ebda15</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ryan O'Toole]]></dc:creator>
            <pubDate>Sun, 08 Jul 2018 23:51:16 GMT</pubDate>
            <atom:updated>2018-07-09T00:50:37.963Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*_K5VoUcYJEvBv0wW.png" /></figure><p>I’ve been learning to use React the last few weeks in school to build applications and i absolutely love it. React is a Javascript library used for building user interfaces and it makes the process of building front end applications much easier. React is a very effective tool for building single page or mobile applications, but it doesn’t scale well with large applications. This is due to the fact that “state,” needs to be passed down from parent component to child component. Thus if you need to pass state from the top of your component hierarchy down to the very bottom this can be extremely time consuming and error prone.</p><p>In the React sense, “state” is an object that represents the parts of the app that can change. Each component can maintain its own state, which lives in an object called <em>this.state.</em> complex React applications usually require the use of additional libraries, like Redux, to solve this issue of state management. According to the its documentation, Redux is a predictable state container for JavaScript apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*oioFENPpxuSLaRK77wXZFA.jpeg" /></figure><p>I know Scooby, but trust me it sounds scarier than it is. We can think of state container as a collection of all the data that describes the app. In an application like a dating app, state would contain data like Users (their images and chat logs), a list of current users with a conversation, list of users to be reviewed, the currently viewed conversation, currently viewed user for image swiping. Below is an example of the data vs. the views in the aforementioned app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ApQLLgi4MNDK_ODgEmoyHA.png" /></figure><p>Redux lets you keep the views and the data separated, which follows the Single Responsibility Principle that i’ve fondly written of in previous posts. By keeping the data and views separated, the application becomes easier to manage because each part only has one reason to change. If the views need to change you don’t have to involve the application’s data and vice versa. The data or state in Redux is contained in a single object. It also helps with organization because you know where everything belongs. The views would contain things including like/dislike buttons, your conversation list, individual text lists, and your profile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a6LV_OrvlLMmJp5GCGSAxw.png" /></figure><p>As i said earlier Redux circumvents the need to pass state and data down from one component to the next which can become unmanageable when your dealing with large applications with hundreds of components. In the following example you can see a map of a React application i coded for class without using Redux. The application is small so i didn’t need Redux, but you’ll quickly see how passing state around like this is unrealistic for large applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pl3Dcy5r9sAxZfJR9Pz-5g.jpeg" /></figure><p>My highest level containing state is Karaoke Container (KC). When i want to pass information down to the Lyrics component i need to manually pass it down from Karaoke Container, to Karaoke Display, to the Lyrics component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9APDjNSSMDIUpOSMGufB1Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KnGSLBfBFiGFNyXTY6XPAQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vcXFzpHLbgyTun_1we93vg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ccs-BM2PemJJjcHdFRMBUQ.png" /></figure><p>In the second screenshot of code you can see i pass a prop, which is like a variable, down to the Karaoke Display component, &lt;Karaoke Component song={this.state.selectedSong} /&gt;, then from the Karaoke Display yo Lyrics, &lt;Lyrics lyrics={this.props.song.lyrics}. When a variable is passed down as props, it can be accessed as props.(variable name) if it is a functional component (not a class), and this.props.state if it is a class component.</p><p>This becomes increasingly unmanageable as your application grows beyond several levels. This setup also creates further problems because state can live in multiple components so keeping track of where things are located can get messy. Thankfully Redux simplifies this dilemma and creates a better organization structure by separating the state and views.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=623a72ebda15" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>