<?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 Moid Khan on Medium]]></title>
        <description><![CDATA[Stories by Moid Khan on Medium]]></description>
        <link>https://medium.com/@skhan852000?source=rss-75f24f1b219d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LDxNpD_4bGqPxnT434Bs6A.png</url>
            <title>Stories by Moid Khan on Medium</title>
            <link>https://medium.com/@skhan852000?source=rss-75f24f1b219d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:51:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@skhan852000/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A quick guide to developing upgradable smart contracts using UUPS — Openzeppelin]]></title>
            <link>https://coinsbench.com/a-quick-guide-to-developing-upgradable-smart-contracts-using-uups-openzeppelin-3f2b6809b8b?source=rss-75f24f1b219d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f2b6809b8b</guid>
            <category><![CDATA[upgrade]]></category>
            <category><![CDATA[openzeppelin]]></category>
            <category><![CDATA[smartcontractsdevelopment]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Moid Khan]]></dc:creator>
            <pubDate>Thu, 02 Feb 2023 21:18:53 GMT</pubDate>
            <atom:updated>2023-02-06T15:04:35.723Z</atom:updated>
            <content:encoded><![CDATA[<h3>A quick guide to developing upgradable smart contracts using UUPS — Openzeppelin</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-zOXekwwAQN_AM85BFf6vg.png" /></figure><p>Hey guys 👋, in this blog we’ll be developing an upgradable smart contract using UUPS (Upgradeable Universal Proxy Standard).</p><p>Smart contracts are self-executing code stored on a blockchain network that allows for the automated execution of digital transactions. As they are stored on the blockchain it is immutable, but there is a way to deploy upgradable smart contracts.</p><p>First, let’s get our starter code from <a href="https://www.openzeppelin.com/contracts">Openzeppelin Contracts Wizard</a>. There, select custom contract and the option of UUPS like this —</p><h3>Part 1: Initial contract</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s8wKc7WO3gmh-ysfHNWXSA.png" /></figure><p>Then open your VS Code terminal.</p><p>We’ll be creating 2 folders — one for the smart contract and one for the front-end.</p><p>Create the smart contract folder and run:</p><pre>npx hardhat</pre><p>Select <br>&gt; Create a TypeScript project → Enter → Enter → Enter</p><p>Run this as well —</p><pre>npm install --save-dev &quot;hardhat@^2.12.6&quot; &quot;@nomicfoundation/hardhat-toolbox@^2.0.0 @openzeppelin/hardhat-upgrades&quot;</pre><p>Now install the Openzeppelin upgradable package</p><pre>npm install &quot;@openzeppelin/contracts-upgradeable&quot;</pre><p>Go into the contracts folder &gt; Lock.sol and change the code to the one you have copied from the Openzeppelin contracts wizard also change the file’s name.</p><p>Let’s declare a variable and a function to change it.</p><pre>uint public counter1;<br><br>function increaseTest() public {<br>        counter1 += 20;<br>}</pre><p>Put this in your contract below the constructor and that should be all for this contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vMaw--hVVvsyzTciSoq2aA.png" /><figcaption>Medium.sol contract</figcaption></figure><p>Now we’ll deploy it.</p><p>I’ll be using the Polygon testnet (Mumbai) to deploy it, <strong>get an RPC URL from Alchemy or wherever you feel convenient, and copy it.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*36XLE00CCXJMHY2iBz8XjA.png" /><figcaption>Configurations for hardhat.</figcaption></figure><p>Lastly, let&#39;s change the deploy.ts file to deploy a proxy-type contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yYBVL40JqABUJZhta2StGg.png" /></figure><p>Run the following command to deploy it —</p><pre>npx hardhat run scripts/deploy.ts --network mumbai</pre><p>Once the contract is deployed, you should see the contract address in the console. Copy the contract address and store it somewhere, we’ll use this for deploying an upgradable contract.</p><h3>Part 2: Upgrade</h3><p>In the same contract folder, make a new file for the new contract. Here, import the previous contract to get it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5f8xMaLA8QXRUIEONYrv3A.png" /></figure><p>As you can see we have created a new unit variable and a new function as well. Make sure to not use the same name for variables. More details on <a href="https://docs.openzeppelin.com/contracts/4.x/upgradeable">Openzeppelin</a> :)</p><p>At last, we’ll also deploy this new contract. No changes to the hardhat.config.ts file for this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*djAVYZR-20sexRwZSVEuNQ.png" /></figure><p>After deploying this, we notice that the address has not changed — that’s an upgrade. The storage between the proxy contract and our contract is shared so we don’t lose any data as well.</p><p>Thank you : )</p><blockquote><strong>PS: This was a quick guide blog, so I have not gone into detail regarding this. If you have any doubts, feel free to dm me on </strong><a href="http://import { ethers, upgrades  } from &quot;hardhat&quot;;  async function main() {     const Medium2 = await ethers.getContractFactory(&quot;Medium2&quot;);   const medium2 = await upgrades.upgradeProxy(&#39;&lt;--- Initial contract&#39;s address ---&gt;&#39;,Medium2)   await medium2.deployed();    console.log(` deployed to ${medium2.address}`); }  // We recommend this pattern to be able to use async/await everywhere // and properly handle errors. main().catch((error) =&gt; {   console.error(error);   process.exitCode = 1; });"><strong>LinkedIn</strong></a><strong> ❤️</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f2b6809b8b" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/a-quick-guide-to-developing-upgradable-smart-contracts-using-uups-openzeppelin-3f2b6809b8b">A quick guide to developing upgradable smart contracts using UUPS — Openzeppelin</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lazy NFT Minting — EIP 721 and Vouchers]]></title>
            <link>https://coinsbench.com/lazy-nft-minting-eip-721-and-vouchers-88ad41654e6b?source=rss-75f24f1b219d------2</link>
            <guid isPermaLink="false">https://medium.com/p/88ad41654e6b</guid>
            <dc:creator><![CDATA[Moid Khan]]></dc:creator>
            <pubDate>Fri, 20 Jan 2023 20:20:47 GMT</pubDate>
            <atom:updated>2023-02-02T21:20:02.040Z</atom:updated>
            <content:encoded><![CDATA[<h3>Lazy NFT Minting — EIP 721 and Voucher</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kbIla6A3iOaoaWoiFa9vfg.png" /></figure><p>Hey there, in this blog we will discuss how you can approve an NFT and someone else can mint it for its specified price.</p><p><strong>Here’s a scenario</strong> — Imagine you need to sell your artwork in your marketplace but don&#39;t wish to pay the gas fees for minting the NFT. You can achieve this by signing the NFT data with your private key (metamask browser) and then storing that signature in a secure place or on any Web 2.0 database. When the person who wishes to buy the NFT not only acquires the NFT but also mints it for you.</p><p>Let’s begin :)</p><blockquote><strong>Special thanks to </strong><a href="https://www.youtube.com/channel/UCJbA7dA_YPbnef0vEBFuhKQ/videos"><strong>Web3 Club</strong></a><strong> (Shobhit) ❤️</strong></blockquote><p>We will be using React.js and ethers.js for this. It’s okay if you don’t know much about react, we will be using the basics of it for our front end. Nothing fancy…</p><h3>Solidity smart contract</h3><p>We’ll be building our contract from the <a href="https://wizard.openzeppelin.com/">OpenZeppelin Contracts Wizard</a>.</p><p>Make sure you select — <strong>ERC721</strong>, <strong>Mintable</strong>, <strong>URI Storage</strong>, and <strong>Ownable</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gHKFQIbo0o4o7izqr9jFLg.png" /></figure><p>— Let’s not reinvent the wheel by writing the contract from scratch —</p><p>Edit the <strong>constructor()</strong> to this —</p><pre>constructor() ERC721(&quot;Voucher&quot;, &quot;VCT&quot;) EIP712(SIGNING_DOMAIN, SIGNATURE_VERSION) {<br>        minter = msg.sender;<br>    }</pre><p>We are passing our token’s name and its abbreviation in the ERC721() parameters and coming to the parameters of EIP712, we will be passing the domain and version. But first, we need to define these. Also, let&#39;s define the minter variable.</p><pre>string private constant SIGNING_DOMAIN = &quot;Voucher-Domain&quot;;<br>string private constant SIGNATURE_VERSION = &quot;1&quot;;<br>address public minter;</pre><h4><strong>What’s </strong><a href="https://docs.openzeppelin.com/contracts/3.x/api/drafts"><strong>EIP</strong></a><strong>?</strong></h4><p>It’s used for hashing and signing data structures in solidity. We use this to get the signer of a certain signed message. We’ll discuss this later on in the blog.</p><p>Let’s create our struct that has our different data types for the Voucher.</p><pre>struct Voucher {<br>        uint256 tokenId;<br>        uint256 price;<br>        string uri;<br>        address buyer;<br>        bytes signature;<br>    }</pre><p>Now comes the cream of the crop, the <strong>recover()</strong> function to verify who has signed our voucher and if it is valid or not.</p><pre>function recover(Voucher calldata voucher) public view returns (address) {<br>        bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(<br>            keccak256(&quot;Voucher(uint256 tokenId,uint256 price,string uri,address buyer)&quot;),<br>            voucher.tokenId,<br>            voucher.price,<br>            keccak256(bytes(voucher.uri)),<br>            voucher.buyer<br>        )));<br>        address signer = ECDSA.recover(digest, voucher.signature);<br>        return signer;<br>    }</pre><p>Now line by line —</p><blockquote>1. <strong>function recover(Voucher calldata voucher) public view returns (address)</strong></blockquote><p>We pass in the Voucher struct by the name <strong>voucher, </strong>it&#39;s a view function that returns an address. Ideally, we want it to retrieve the admin’s address here who has signed the voucher.</p><blockquote><strong>2.bytes32 digest = _hashTypedDataV4(keccak256(<em>abi</em>.encode( … )));</strong></blockquote><p>In order to recover the signer of a voucher, we need to take into account the data types and variables from our struct and encode it by keccak256 and hash it using _hashTypedDataV4. This is stored in a bytes32 data type — <strong>digest</strong>.</p><blockquote><strong>3.keccak256(“Voucher(uint256 tokenId,uint256 price,string uri,address buyer)”)</strong></blockquote><p>This is where people get errors, make sure to use the same names here as we use on our front end.</p><p>In the next lines, we pass the values from the voucher.</p><blockquote><strong>4. address signer = ECDSA.recover(digest, voucher.signature);</strong></blockquote><p>Here we store the address retrieved from the digest we have sent along with the voucher signature. EDCSA (Elliptic Curve Digital Signature Algorithm)</p><p>We will now visit the safeMint function we got from the OpenZeppelin Wizard.</p><pre>function safeMint(Voucher calldata voucher)<br>        public<br>        payable<br>    {  <br>        require(minter == recover(voucher), &quot;Wrong signature.&quot;);<br>        require(msg.sender == voucher.buyer, &quot;This NFT is not assigned for you&quot;);<br>        require(msg.value &gt;= voucher.price, &quot;Not enough ether sent.&quot;);<br>        _safeMint(voucher.buyer, voucher.tokenId);<br>        _setTokenURI(voucher.tokenId, voucher.uri);<br>    }</pre><p>This is the function we call from the front end and pass in the voucher. ( How? Will discuss this later in this blog )</p><p>Three new lines have been added here and two lines have been changed —</p><blockquote><strong>require(<em>msg.sender</em> == voucher.buyer, “This NFT is not assigned for you”);</strong></blockquote><p>To make sure the person calling this function is the buyer.</p><blockquote><strong>require(minter == recover(voucher), “Wrong signature.”);</strong></blockquote><p>This line here calls the recover function above and checks the signer of the voucher. If it is the minter ( admin ), then the validation passes and we go to the next check.</p><blockquote><strong>require(<em>msg</em>.value &gt;= voucher.price, “Not enough ether sent.”);</strong></blockquote><p>Lastly, we check if the amount sent during the smart contract interaction is the amount specified in the voucher.</p><blockquote><strong>_safeMint(voucher.buyer, voucher.tokenId);</strong></blockquote><p>Here we mint to the buyer of the contract. You can look into the _safeMint function for more details.</p><blockquote><strong>_setTokenURI(voucher.tokenId, voucher.uri);</strong></blockquote><p>Setting the token URI to the minted token ID.</p><p>You can now deploy the smart contract, make sure to store its <strong>ABI </strong>and <strong>address </strong>: )</p><h3>React App</h3><p><strong>Install ethers on your react app.</strong></p><pre>npm install ethers</pre><p>Now, clearing out the App.js. It should look something like this.</p><pre>import React from ‘react’<br>function App() {<br>return (<br>&lt;div&gt;App&lt;/div&gt;<br>)<br>}<br>export default App</pre><p>Define the domain name, version, and chain ID. I’ll be using MATIC so my chain ID would be 80001;</p><pre>  const SIGNING_DOMAIN_NAME = &quot;Voucher-Domain&quot;;<br>  const SIGNING_DOMAIN_VERSION = &quot;1&quot;;<br>  const chainId = 80001;</pre><p>Import ethers.</p><pre>import { ethers } from &quot;ethers&quot;;</pre><p>Make a state variable <strong>voucher </strong>to store the voucher we will be signing.</p><pre>const [voucher, setVoucher] = useState(&quot;&quot;);</pre><p>Define a const named domain to store the above values. Make sure you have imported your contract address.</p><pre>  const domain = {<br>    name: SIGNING_DOMAIN_NAME,<br>    version: SIGNING_DOMAIN_VERSION,<br>    verifyingContract: ContractAddress,<br>    chainId,<br>  };</pre><p>Let’s now make the approve function, this function takes in 4 parameters — tokenId, price, URI, buyer.</p><pre>const approve = async (tokenId, price, uri, buyer) =&gt; {<br>    const voucher = { tokenId, price, uri, buyer };<br><br>    const types = {<br>      Voucher: [<br>        { name: &quot;tokenId&quot;, type: &quot;uint256&quot; },<br>        { name: &quot;price&quot;, type: &quot;uint256&quot; },<br>        { name: &quot;uri&quot;, type: &quot;string&quot; },<br>        { name: &quot;buyer&quot;, type: &quot;address&quot; },<br>      ],<br>    };<br>    try {<br>      const provider = new ethers.providers.Web3Provider(window.ethereum);<br>      const signer = provider.getSigner();<br>      const signature = await signer._signTypedData(domain, types, voucher);<br>     <br>      return {<br>        ...voucher,<br>        signature,<br>      };<br>    } catch (err) {<br>      console.log(err);<br>    }<br>  };</pre><p>Whoa, now that&#39;s a lot of code. We’ll go through them one by one.<br>First, make an object of our NFT data and name it. Next, We define const types that have a key Voucher and an array of our NFT data with respect to each of its types and name. Make sure to have the same names here as you have mentioned in the smart contract.</p><p>We now open a try-catch block to start the web3 functionality.<br>The first two lines get the injected web3 from the browser, in this case, metamask, and get its signer.</p><pre>const signature = await signer._signTypedData(domain, types, voucher);</pre><p>The above function calls metamask to get the signature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*pZJPt0G8ZA1284ugGVRvxg.png" /><figcaption>Metamask pop-up</figcaption></figure><p>Lastly, return the voucher along with the signature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*vNRfVO-wKpNdxoNXxZFRkA.png" /><figcaption>Console log of the returned object.</figcaption></figure><pre>const signNFT = async (id, price, uri, buyer) =&gt; {<br>    const signature = await approve(id, price, uri, buyer);<br>    console.log(signature);<br>    setVoucher(signature);<br>  };</pre><p>This function is to redirect the call to the approve() function and stores the signature.</p><blockquote><strong>Make sure to store the signature in a secured database where the buyer can reach</strong></blockquote><p>Let’s write up HTML to call this function. I’m using Tailwind CSS to style my Button. I’m also passing in the values here<br>tokenID — 3<br>price — 100 wei<br>uri — Some generic URI<br>buyer — Address of the assigned buyer</p><pre>return (<br>    &lt;div className=&quot;p-8 flex gap-5 flex-col items-start justify-start&quot;&gt;<br>      &lt;p<br>        className=&quot;text-pink-400 bg-slate-800 hover:text-pink-300 py-2 rounded-full cursor-pointer px-6&quot;<br>        onClick={() =&gt; {<br>          signNFT(<br>            3,<br>            100,<br>            &quot;https://gateway.pinata.cloud/ipfs/QmX2ubhtBPtYw75Wrpv6HLb1fhbJqxrnbhDo1RViW3oVoi/5.json&quot;,<br>            &quot;0x8559B274b601a15B4f155aE3f09eb62BEC6317A3&quot;<br>          );<br>        }}<br>      &gt;<br>        Approve<br>      &lt;/p&gt;<br>    &lt;/div&gt;<br>  );</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/183/1*kzlFETklBijrZRggXYj89Q.png" /><figcaption>Approve Button</figcaption></figure><p>Call this function to sign the voucher. You should get the metamask pop-up which asks you to sign.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*lRToFLLXTC5pSszaU9Tu3w.png" /><figcaption>Metamask pop-up</figcaption></figure><pre>const mintNFT = async () =&gt; {<br>    try {<br>      const provider = new ethers.providers.Web3Provider(window.ethereum);<br>      const signer = provider.getSigner();<br>      const contract = new ethers.Contract(ContractAddress, ABI, signer);<br>      const create = await contract.safeMint(<br>        [3, voucher.price, voucher.uri, voucher.buyer, voucher.signature],<br>        { value: &quot;100&quot; }<br>      );<br>      await create.wait();<br><br>      console.log(create);<br>      return true;<br>    } catch (error) {<br>      return false;<br>    }<br>  };</pre><p>This function is to call the mint functionality of the smart contract. We open a try-catch block here as well. The first two lines are to get the signer from the web browser. Later we define the contract by passing in the Contract Address, ABI, and signer.</p><p>Call the safeMint function of the smart contract.</p><pre>const create = await contract.safeMint(<br>        [voucher.tokenId, voucher.price, voucher.uri, voucher.buyer, voucher.signature],<br>        { value: &quot;100&quot; }<br>      );</pre><p>Here we can compare the parameter ( singular ) to the parameter from the smart contract, the safeMint function accepts the Voucher struct, so we pass in the values of the struct Voucher —</p><p><strong>Note</strong>: The values to pass to the safeMint function are from the use state variable voucher. This value should be taken from a web 2.0 database. For the sake of the blog, I have stored it in my browser.</p><p>The second parameter<br>{ value : “100” }<br>is the amount of wei the NFT costs, the same as voucher.price.</p><p>Let’s make a button for this as well —</p><pre>  return (<br>    &lt;div className=&quot;p-8 flex gap-5 flex-col items-start justify-start&quot;&gt;<br>      &lt;p<br>        className=&quot;text-pink-400 bg-slate-800 hover:text-pink-300 py-2 rounded-full cursor-pointer px-6&quot;<br>        onClick={() =&gt; {<br>          signNFT(<br>            3,<br>            100,<br>            &quot;https://gateway.pinata.cloud/ipfs/QmX2ubhtBPtYw75Wrpv6HLb1fhbJqxrnbhDo1RViW3oVoi/5.json&quot;,<br>            &quot;0x8559B274b601a15B4f155aE3f09eb62BEC6317A3&quot;<br>          );<br>        }}<br>      &gt;<br>        Approve<br>      &lt;/p&gt;<br><br>      &lt;p<br>        className=&quot;text-pink-400 bg-slate-800 hover:text-pink-300 py-2 rounded-full cursor-pointer px-6&quot;<br>        onClick={() =&gt; {<br>          mintNFT();<br>        }}<br>      &gt;<br>        Mint<br>      &lt;/p&gt;<br>    &lt;/div&gt;<br>  );</pre><p>Calling this function should give the metamask pou-up to finally mint the NFT.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*NkQXclDPjmmGM5Zvjv-N9w.png" /></figure><p>And voila, you have lazy-minted an NFT.</p><h3>Thank You</h3><p>GitHub — <a href="https://gist.github.com/Khanisic/b4379dc3c5df8b7968f552db6148092f">https://gist.github.com/Khanisic/b4379dc3c5df8b7968f552db6148092f</a></p><p>I’m always open to suggestions and discussions on <a href="https://www.linkedin.com/in/abdulmoidkhan/">LinkedIn</a>. Hit me up with direct messages.</p><p>Ciao 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88ad41654e6b" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/lazy-nft-minting-eip-721-and-vouchers-88ad41654e6b">Lazy NFT Minting — EIP 721 and Vouchers</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory vs Storage | copy vs reference — Solidity]]></title>
            <link>https://coinsbench.com/memory-vs-storage-copy-vs-reference-solidity-4d46b50533ba?source=rss-75f24f1b219d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d46b50533ba</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[erc20-token]]></category>
            <dc:creator><![CDATA[Moid Khan]]></dc:creator>
            <pubDate>Fri, 22 Jul 2022 14:03:28 GMT</pubDate>
            <atom:updated>2022-07-29T06:06:09.385Z</atom:updated>
            <content:encoded><![CDATA[<h3>Memory vs Storage | copy vs reference — Solidity</h3><p>Persistent and temporary data storage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6rJ1jbVshLKGDTj4vJ-W-Q.png" /></figure><p>Hey guys, in this blog I’ll be explaining memory and storage, which are two out of three areas where the Ethereum virtual machine stores data, behaves when they are accessed in a function and how we can write/access them — <strong>copy </strong>&amp; <strong>reference</strong>. While initialising a variable in a function, we must specify where we are storing this data of the variable we are accessing.</p><p>Let me start by loosely explaining the two —</p><h4>Storage</h4><p>Persistent data area that can be called from within and outside the functions and also during transactions. Kind of like a global variable.</p><h4>Memory</h4><p>Temporary data that gets wiped out after a function call and has limited scope in its respective function.</p><p>We’ll be looking into <strong>4 </strong>scenarios where either of the data areas accesses each other.<br>1. storage → memory<br>2. memory → storage<br>3. storage → storage<br>4. memory → memory</p><h4>1. storage → memory</h4><pre>contract Test{<br>    uint[] <strong>arrayStorage </strong>= [2];</pre><pre>    function <strong>test</strong>( <strong>uint[] memory</strong> <strong>arrayMemory </strong>) public returns ( uint[] memory, uint[] memory ){<br>        <strong>arrayStorage = arrayMemory;</strong><br>        arrayStorage.push(4);<br>        return ( arrayStorage, arrayMemory )<br>     }</pre><pre>}</pre><p>Here, we are first initialising the arrayStorage to [2]. We are calling the function test by passing an empty memory array → test ( [] ). <br>Then we are assigning the memory array ( here → [] ) to the storage array.</p><blockquote>arrayStorage = []</blockquote><p>After this, we are pushing a number ( arrayStorage.push(4) )into the storage array.</p><blockquote>arrayStorage = [4]</blockquote><p>Lastly, we return the values —</p><blockquote>arrayStorage = [4]<br>arrayMemory= []</blockquote><h4>2. memory → storage</h4><pre>contract Test{<br>    uint[] <strong>arrayStorage </strong>= [2];</pre><pre>function <strong>test</strong>( <strong>uint[] memory</strong> <strong>arrayMemory </strong>) public returns ( uint[] memory, uint[] memory ){<br>        <strong>arrayMemory= arrayStorage;</strong><br>        arrayStorage.push(4);<br>        return ( arrayStorage, arrayMemory )<br>     }</pre><pre>}</pre><p>Similarly, We are calling the function test by passing an empty memory array → test ( [] ). Since we can’t push to a memory array we’ll be pushing to the storage array arrayStorage.push(4); . Then we are assigning the storage array ( here → [2] ) to the memory array.</p><blockquote>arrayMemory = [2]</blockquote><p>Lastly, we return the values —</p><blockquote>arrayStorage = [2,4]<br>arrayMemory= [2]</blockquote><h4>3. storage → storage</h4><pre>contract Test{<br>    uint[] <strong>arrayStorage </strong>= [2];</pre><pre>function <strong>test</strong>( ) public returns ( uint[] memory, uint[] memory ){<br>        uint[] storage localArrayStorage;     <br>        <strong>localArrayStorage = arrayStorage;</strong><br>        localArrayStorage.push(6);<br>        arrayStorage.push(4);<br>        return ( arrayStorage, localArrayStorage);<br>     }</pre><pre>}</pre><p>Here, we are first initialising the arrayStorage to [2] outside the function. After calling the function test(), firstly we define a new array localArrayStorage . Next, we assign the arrayStorage to the local storage array → localArrayStorage</p><blockquote>localArrayStorage = [2]</blockquote><p>After this, we push [4] into the localArrayStorage and we push [6 ] into the arrayStorage.</p><blockquote>arrayStorage = [2,4,6]<br>localArrayStorage= [2,4,6]</blockquote><p>As we have assigned a storage array to another storage array, any change in either of the arrays will reflect on both arrays.</p><h4>4. memory → memory</h4><pre>contract Test{<br>    uint[] <strong>arrayStorage </strong>= [2];</pre><pre>function <strong>test</strong>( uint[] memory memoryArray ) public view returns ( uint[] memory, uint[] memory ){<br>        uint[] memory <strong>localArrayMemory</strong>;<br>        <strong>localArrayMemory= memoryArray;</strong><br>        memoryArray = arrayStorage;<br>        return (localArrayMemory, memoryArray );<br>      }</pre><pre>}</pre><p>Here, we are first initialising the arrayStorage to [2] outside the function. After calling the function test( [] ) → passing the memory array as [], firstly we define a new array localArrayMemory. Next, we assign the arrayOfMemory to the local memory array → localArrayMemory.<br>In this case, any change to either of the memory arrays before assigning themselves to each other ( localArrayMemory → memoryArray or memoryArray →localArrayMemory ) will not reflect either array, they remain independent.</p><blockquote>localArrayMemory= []<br>memoryArray= [2]</blockquote><h3>Conclusion:</h3><p>Storage arrays when assigned to another storage array are assigned by reference ( pointer ) and change in either of them will affect both the storage arrays. Memory arrays, when assigned to storage and vice-versa are assigned by copy. Lastly, when a memory array is assigned to another memory array, it is assigned by copy and no change happens on changing either of the arrays.</p><p>Thank you :) ❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d46b50533ba" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/memory-vs-storage-copy-vs-reference-solidity-4d46b50533ba">Memory vs Storage | copy vs reference — Solidity</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Better Version of Kickstarter Using Web3.0 — Solidity]]></title>
            <link>https://medium.com/better-programming/a-better-version-of-kickstarter-using-web3-0-solidity-8bbea829d2f0?source=rss-75f24f1b219d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bbea829d2f0</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Moid Khan]]></dc:creator>
            <pubDate>Wed, 20 Jul 2022 11:25:46 GMT</pubDate>
            <atom:updated>2022-07-20T17:50:01.028Z</atom:updated>
            <content:encoded><![CDATA[<h4>To prevent Kickstarter fraud, contributors can vote on monetary decisions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KxaNo5iT4f7QYt44gUQdCw.png" /><figcaption>Landing page</figcaption></figure><p>In this blog, I’ll be explaining how to make a prototype for Kickstarter that takes into account the votes of the contributors who have the backing of the project to make major decisions regarding where the funds would go. In this case, the manager of the campaign can create a request in which he can mention the recipient&#39;s address and the services of the recipient and people can vote on whether to approve the service or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gv8HdbZnQUVIEK_UGq-kQw.png" /><figcaption>Example of a request viewed by a contributor.</figcaption></figure><p>This, however, is a smart contract.<strong> A smart</strong> contract could be defined as an entity that can send and receive currency ( <em>crypto </em>) beyond just users on the web. It’s a piece of code that manages your money and how you direct it to perform certain functions — ergo, programs on the blockchain!</p><p>These programs once deployed cannot be modified and are final. Let’s not go deep into the many beneficial aspects of smart contracts, as there are many and time is relative.</p><p>I’ll be explaining <strong>2 </strong>smart contracts here.</p><ol><li>Contract that creates campaigns.</li><li>Contract that deals with how the manager of a campaign can create a request and how other people can interact with it.</li></ol><p>Let’s start with our compiler version and contract function.</p><pre>pragma solidity ^<strong>0.8.15</strong>;</pre><pre>contract CampaignCreator{</pre><pre>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VY_cqCOh9t2lB4C8aufF3A.png" /><figcaption>Create a campaign page.</figcaption></figure><p>We’ll start by creating a struct, that takes in the above details.</p><pre>struct CreateNewCampaign{<br>    <strong>address </strong>addressOfNewCampaign;<br>    <strong>string </strong>name;<br>    <strong>uint </strong>minimumContribution;<br>}</pre><ul><li>addressOfNewCampaign → address of the campaign to be created.</li><li>name → Title of the campaign to be created.</li><li>minimumContribution → minimum amount that one has to contribute in order to vote on decisions of the campaign.</li></ul><p>Now an array to store a list of the above structs.</p><pre>CreateNewCampaign[] public deployedCampaigns;</pre><p>Here, the syntax for creating an array is as follows:</p><pre>data_type [] visibility name_of_the_array;</pre><p>Now, a function to create campaigns, that takes in 2 parameters → minimum contribution and title of the campaign.</p><pre>function <strong>createCampaign</strong>(uint minimum, string memory _name) public {</pre><pre>Campaign newCampaign = new Campaign(minimum, <em>msg.sender</em>);</pre><pre><strong>deployedCampaigns</strong>.push( <strong>CreateNewCampaign</strong>( address(<strong>newCampaign</strong>), _name, minimum) );</pre><pre>}</pre><p>Line: 1 — Campaign newCampaign = new Campaign(minimum, <em>msg.sender</em>); Here, <strong>Campaign</strong>is the campaign contract that we’ll be coding later and <strong>newCampaign </strong>is its instance. We pass in two parameters namely minimum and msg.sender that calls the constructor of the campaign contract which we will also be coming later in this blog.<br>Line: 2 — <strong>deployedCampaigns</strong>.push( <br><strong>CreateNewCampaign</strong>( address(newCampaign), _name, minimum) <br>); Here we are just pushing the values of the newly created contract into our list of campaigns that we create.</p><p>Lastly in this contract, a function to retrieve all the campaigns.</p><pre>function <strong>getDeployedCampaigns</strong>() public view returns ( CreateNewCampaign[] memory) {</pre><pre>return deployedCampaigns;</pre><pre>}</pre><h4>Let’s now begin the Campaign contract —</h4><pre>contract Campaign{</pre><pre>}</pre><p>Now the first thing that gets invoked when a contract gets called is the constructor.</p><p>We’ll make 2 variables managerand minimumContribution which gets the value of the campaign manager and the campaign’s minimum contribution.</p><pre>address public <strong>manager</strong>;<br>uint public <strong>minimumContribution</strong>;</pre><pre><strong>constructor</strong>(uint minimum, address creator) {</pre><pre>    manager = creator;<br>    minimumContribution = minimum;</pre><pre>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aZE5Oxtb1whX8ZN4hKoqng.png" /><figcaption>Accessing the constructor of the Campaign contract.</figcaption></figure><p>Now, create a function that takes in the contributions. Whoever contributes, gets to approve campaign decisions/requests. But before that, we’ll need to store our approvers somewhere.</p><pre>mapping(address =&gt; bool) public contributer;</pre><p>This mapping helps us check if a specific address ( user ) has contributed or not. We just need to change the key— address to true. By default, all the values in this mapping will be false.</p><p>Also, a variable that gets the count of contributors.</p><pre>uint public <strong>countOfContributers</strong>;</pre><pre>function <strong>contribute</strong>() public <strong>payable</strong>{</pre><pre>  require( msg.value &gt; minimumContribution );<br>  if(contributers[msg.sender] == false)<br>  {<br>    contributers[msg.sender] = true;<br>    countOfContributers++;<br>  }</pre><pre>}</pre><p>Firstly, the function is marked as payable that means it accepts payments.</p><p>Line 1 — require( msg.value &gt; minimumContribution ); this line checks if the value sent is greater than the minimum contribution. msg.value is the amount of ETH that is being sent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*XxNDzF2q4wh3QJrmSTlM8w.png" /><figcaption>How the above function is called.</figcaption></figure><p>The next if statement checks if the address ( user ) that is calling the contribute function is already a contributor or not, if not then it writes into the contributers mapping and increases the countOfContributers uint. <br>This is done in order to correctly count the number of contributors, in case someone contributes more than once.</p><h4>Now the difficult part, making requests on which the contributors can vote.</h4><p>Firstly, create a struct that defines what a request looks like.</p><pre>struct Request{</pre><pre>   string title;<br>   uint fundsRequired;<br>   address receiver;<br>   uint approvalCount;<br>   bool complete;</pre><pre>}</pre><p>title → Title of the request<br>fundsRequired→ Funds needed <br>receiver→ Address to whom the money ( ETH ) will be going on finalising the request.<br>approvalCount→ No. of people who have approved the request.<br>complete→ Status of the request, if completed then true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JseibqEXj1n_i0LnOGdYlA.png" /><figcaption>Create a request page</figcaption></figure><p>Now an array to store a list of the requests.</p><p>Request[] public requestsArray;</p><p>Now, a function to create a request.</p><pre>function <strong>createRequest </strong>( string memory _title , uint _funds , address _receiver ) public{</pre><pre><strong>requestsArray</strong>.push( Request( _title, _funds,_receiver,0, false ) );</pre><pre>}</pre><h4>Note:</h4><p>We use memory while accessing a string as a parameter in a function, basically what memory does is, limits the scope of the accessed variable to the function itself.</p><p>Now let’s approve those requests :)</p><pre>function approveRequest( uint idOfRequestToApprove ) public {</pre><pre>Request storage requestToApprove = requestsArray[idOfRequestToApprove];</pre><pre><strong>require</strong>( contributers[msg.sender] == true );</pre><pre><strong>require</strong>( approvalsOfAllRequests[msg.sender][idOfRequestToApprove] == false );</pre><pre><strong>approvalsOfAllRequests</strong>[msg.sender][idOfRequestToApprove] = true;</pre><pre><strong>requestToApprove</strong>.approvalCount++;</pre><pre>}</pre><p>We call the above function with a uint parameter — idOfRequestToApprove this is used to access a specific request, eg: approveRequest(0) will get the first request in the array of requests requestsArray .</p><p>Line 1 — Request storage requestToApprove = requestsArray[idOfRequestToApprove]; This line takes the idOfRequestToApprove ( 0,1,2,3,4,5 … a number ) request in the requestsArray and stores it into the requestToApprove struct. So we can access the actual request from the requestsArray . → We use storage for this purpose ( storage → storage — assign by reference ).</p><p>Line 2 — <strong>require</strong>( contributers[msg.sender] == true );, just checks if the address ( user ) approving the request is a contributor.</p><p>Line 3 — This line is to check if the address ( user ) has already not approved the request or not. This is done by a double mapping.</p><pre><strong>mapping </strong>( <strong>address </strong>=&gt; <strong>mapping</strong>( uint =&gt; bool )) <strong>approvalsOfAllRequests</strong>;</pre><p>Here we map the address with another map that has a uint as key and bool as its value, here uint is the request ID and bool is whether the address has approved the request or not. Let’s say we want to know if address XYZ has voted on the 3rd request or not?</p><pre>return approvalsOfAllRequests[XYZ][2] == true;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ClCFeEtr8lstJtijwa8_Hw.png" /></figure><p>Line 4— This line is to prevent an address ( user ) from approving the same request again.<br>Line 5— Lastly we increase the approval count from the Request struct of the respective request that we are accessing in this function.</p><p>The last function is to finalize a request. We have indeed come a long way :)</p><pre>function finaliseRequest( uint idOfRequestToApprove)  public {</pre><pre>require(msg.sender == mananger);</pre><pre>Request storage requestToApprove = requestsKaArray[idOfRequestToApprove];</pre><pre>require(requestToApprove.approvalCount&gt;(countOfContributers/2));</pre><pre>require( requestToApprove.complete == false );</pre><pre>require ( address(this).balance &gt; requestToApprove.fundsRequired );</pre><pre>requestToApprove.complete == true;</pre><pre>payable( requestToApprove.receiver ).transfer(requestToApprove.fundsRequired);</pre><pre>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*o5w7Lf0kXboHhGBSybUTDg.png" /><figcaption>Finalise request</figcaption></figure><p>Similar to the approve function, we pass a uint → ID of the request we want to access.</p><p>Line 1 — require(msg.sender == mananger); This is to check if the address ( user ) calling the finalise function is the manager of the campaign. We don’t want someone else to finalise our requests, do we?</p><p>Line 2 — Similar to the approve function.</p><p>Line 3 — require(requestToApprove.approvalCount &gt;(countOfContributers/2)); This is to check if the majority<strong> </strong>of contributors have approved the request.</p><p>Line 4 — require( requestToApprove.complete == false ); To check if the request has not already been finalised.</p><p>Line 5 — require ( address(this).balance &gt; requestToApprove.fundsRequired ); This is to check if the contract has enough balance to carry out the transaction to the recipient. We get the balance of the contract by address(this).balance.</p><p>Line 6— payable( requestToApprove.receiver ). transfer ( requestToApprove . fundsRequired ); Lastly, we pay the recipient the funds :).</p><p>Here is the complete code:</p><pre><a href="https://gist.github.com/Khanisic/5d069575addc0716ce09d4e849027be1">https://gist.github.com/Khanisic/5d069575addc0716ce09d4e849027be1</a></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qZOJvET11QjGbqXEafeJKg.png" /><figcaption>Our campaign page</figcaption></figure><h4>Links</h4><ul><li><a href="https://crowdcoin-five.vercel.app/">Vercel deployed Link</a></li><li><a href="https://github.com/Khanisic/Crowdcoin">Github</a></li><li><a href="https://www.figma.com/file/Tx5fzNUGJ1vB4CcsqsWfIj/Crowdcoin&#39;s-Figma?node-id=0%3A1">Figma design file</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bbea829d2f0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/a-better-version-of-kickstarter-using-web3-0-solidity-8bbea829d2f0">A Better Version of Kickstarter Using Web3.0 — Solidity</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating an NFT Marketplace With Solidity]]></title>
            <link>https://medium.com/better-programming/creating-an-nft-marketplace-solidity-2323abca6346?source=rss-75f24f1b219d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2323abca6346</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[nft]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Moid Khan]]></dc:creator>
            <pubDate>Sat, 16 Jul 2022 10:26:56 GMT</pubDate>
            <atom:updated>2022-07-18T17:50:47.822Z</atom:updated>
            <content:encoded><![CDATA[<h4>With just 200 lines of code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QbbcIMaBLeTEgl6rOs5etA.png" /></figure><blockquote><strong>Web 3.0</strong> has the potential to change the internet as we know it, <em>forever. <br> — Adrian ( JavaScript Mastery )</em></blockquote><p>In this blog, I’ll be explaining solidity and how one can create an NFT marketplace with just 200 lines of code.</p><p>This, however, is a smart contract.<strong> A</strong>smart contract could be defined as an entity that can send and receive currency ( <em>crypto </em>) beyond just users on the web. It’s a piece of code that manages your money and how you direct it to perform certain functions — ergo, programs on the blockchain!</p><p>These programs once deployed cannot be modified and are final. Let’s not go deep into the many beneficial aspects of smart contracts, as there are many and time is relative.</p><h3>Starting with the demo of the application —</h3><ol><li>Connect with our metamask<strong> </strong>wallet ( <em>you can continue reading this blog even if you don’t have metamask account or have no idea about it :|</em>, <em>just assume it’s an online wallet </em>)</li></ol><figure><img alt="Connected with the metamask wallet" src="https://cdn-images-1.medium.com/max/656/1*qqnkGk-_PKGNF2w8BTtcow.png" /><figcaption>Connected with the metamask wallet</figcaption></figure><p>2. Create an NFT</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ibI-2qAX9pkYdAqLHOnDg.png" /><figcaption>Create an NFT page ( zoom 50%, to fit it here )</figcaption></figure><p>Upload your image and fill in the details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j_FXto_ps3Qi4PkT8m2U5A.png" /><figcaption>Confirmation from metamask to list the NFT on the marketplace.</figcaption></figure><p>You’ll be sending 0.00025 ether to the owner of the marketplace as the listing fee. The above image is the approval of the transaction, <em>think of it as entering your PIN code or OTP for an online transaction.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*axoB9Mbzkx6Edhrz5oLmMg.png" /><figcaption>Your image is now on the marketplace, voila!</figcaption></figure><p>3. Let’s buy that NFT<strong> </strong>that you listed. Now we’ll be changing our account in metamask, cause let’s be real here, we can’t buy our own NFT.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*dulXHXf41tUs7K4Vykzl9A.png" /><figcaption>Switching the account on metamask.</figcaption></figure><p>4. Buy the NFT.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aJdD3cd6429G4R_VNPcAbA.png" /><figcaption>NFT details page.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-8aY8J1tWYb6dUUeZNILg.png" /><figcaption>Checkout confirmation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_tVxvpzhk3eAK-CVaaXzrg.png" /><figcaption>Confirmation for buying the NFT.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wlh5qlQwbAxqJJo6YW5C3A.png" /><figcaption>You can now check that you have bought the NFT on the NFT details page.</figcaption></figure><p>Now that the demo is over, we can start with the solidity code.</p><h3><strong>Solidity Code</strong></h3><p>For starters, if you know JavaScript, then you’ll be comfortable with understanding the code of solidity. Smart contracts for Ethereum are programmed in solidity which is an object-oriented, high-level language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*UVIZlWG8tc14Kxat3QoiFg.png" /><figcaption>Starting code.</figcaption></figure><p>Let’s go through this code line by line:</p><p>Line 2 — It is mandatory to mention the solidity version before writing our contract. Here we will be working with version 0.8.4.</p><p>Line 4,5,6 — Just like any other language, here we are importing other contracts that we are using to build upon our code, think of them as libraries.<br>Counters.sol: To keep a counter of — ( will be discussed further ). <br>ERC721.sol: Standard for writing contracts relevant to NFTs.<br>ERC721URIStorage.sol: For inheriting _tokenURI, should resolve to a JSON document</p><p><strong><em>Line 8</em></strong> — Defining the contract NFTMarketplace<strong> </strong>which inherits ERC721URIStorage ( another contract ), we do not inherit ERC721.sol as ERC721URIStorage already inherits it. These contracts are by <a href="https://www.openzeppelin.com/">OpenZepplin</a>.</p><p>using Counters for Counters.Counter;</p><p>Initializing the Counters that we inherited.</p><pre>Counters.Counter private _tokenIds; <br>Counters.Counter private _itemsSold;</pre><p>Here the contract keeps count of two variables — _tokenIds and _itemsSold. Whenever we call _tokenIds.increment(); the value of _tokenIds will be incremented from say 1 → 2, likewise for _itemsSold.</p><pre>uint256 listingPrice = 0.00025 ether;</pre><p>Specifying the listing price, whenever someone wants to create their NFT and list it on the marketplace, they pay the listing fee ie. 0.00025 ETH. Here uint256 is a data type. u → unsigned, int → integer with base 256.</p><pre>address payable owner;</pre><p>Variable of type address ( takes only addresses ) called the owner. Here it is defined as payable, meaning that this address can involve in transactions.</p><pre>constructor() ERC721(“Metaverse Tokens”, “METT”) {<br>   owner = payable(<em>msg.sender</em>);<br>}</pre><p>Whenever our contract is called, a constructor gets invoked. In our case, we need to invoke 2 constructors — Our contracts and the ERC721.sol contract as we are inheriting<strong> </strong>from it.</p><p>In this constructor, we are telling the contract that the owner is the person who is calling the contract, but in blockchain, we convey that by address thereby getting the address of the sender, msg.sender is an in-built argument that takes in the address of the account that is invoking/calling the contract.</p><p>Long story short, we’re informing the contract that we ( <em>msg.sender</em> ) are the owner by defining the owner variable! When we deploy our contract, it takes in our address, so only we have the authority of ownership. <br>phew…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*VcJSiI1UAAFOF3JonhopVg.png" /><figcaption>During calling the constructor of ERC721, we need to call it as it wants to get called ie. its required parameters.</figcaption></figure><pre>struct MarketItem {<br>   uint256 tokenId;<br>   address payable seller;<br>   address payable owner;<br>   uint256 price;<br>   bool sold;<br>}</pre><p>Creating a struct Market Item to store various types of data.</p><ul><li>tokenID<strong> </strong>→ Id of the token involved in the sale</li><li>seller → to store the seller’s address</li><li>owner → to store the owner’s address ( If an NFT is created, initially it is owned by the marketplace, ie. Contract’s address )</li><li>price → price of the NFT</li><li>sold → boolean value ( true/false ) to mention if the NFT is sold or not.</li></ul><pre>mapping(uint256 =&gt; MarketItem) private idToMarketItem;</pre><p>mapping<strong> </strong>— another data type of solidity. It stores a key ( a data type ) and its corresponding value ( also a data type ), ergo — Key — value pairs.</p><pre>mapping ( &lt;data-type&gt; =&gt; &lt;data-type/structure&gt;/ ) visibility name;</pre><p>In this case, we are mapping an uint256 data type to the struct MarketItem. Here, the visibility is private, meaning it can only be called from within the contract and not from outside.</p><pre>function updateListingPrice(uint _listingPrice) public payable {<br>     require(owner == <em>msg.sender</em>);<br>     listingPrice = _listingPrice;<br>}</pre><pre>function getListingPrice() public view returns (uint256) {<br>     return listingPrice;<br>}</pre><p>Alright, let’s pick up the pace now.</p><ul><li>updateListingPrice()<strong> </strong>— Takes in a uint → _listingPrice as an argument and updates the current listing price.<br>getListingPrice()<strong> </strong>— A return function that returns the current listing price of the contract.</li></ul><p>Here, require is a condition that gets run before the code under it runs. So in theory, if someone else apart from the owner calls the above functions, it simply does not run.</p><p>Taking a detour now…</p><p>You must wonder what private, public, etc. are.</p><ul><li>public, private, internal, external → These are just visibility types that are given to each function/variable telling the contract who can call these functions/variables and from where.</li><li>public→ Can be called by anyone.</li><li>private→ Can be called only from within the contract and not by anyone else outside of it.</li><li>external→ Can be called by contracts inheriting the function with external visibility.</li><li>internal (default )→Can only be accessible within the contract in which they were declared and also from derived contracts.</li></ul><p>Moving on with the contract…</p><pre>function createToken(string memory tokenURI, uint256 price) public                                                                                                                                       payable returns (uint) {</pre><pre>   _tokenIds.<strong>increment</strong>();<br>   uint256 newTokenId = _tokenIds.<strong>current</strong>();<br>   <strong>_mint</strong>(<em>msg.sender</em>, newTokenId);<br>   <strong>_setTokenURI</strong>(newTokenId, tokenURI);<br>   <strong>createMarketItem</strong>(newTokenId, price);<br>   return newTokenId;</pre><pre>}</pre><p>How this function is called in JavaScript:</p><pre><strong>createToken</strong>(url, price, { value: listingPrice.toString() })</pre><ul><li>_tokenIds.increment() — increases the value of _tokenIds in the contract by 1.</li><li><strong>uint256 newTokenId = _tokenIds.current()</strong> — stores the current value of _tokenIds from the contract to the variable newTokenId.</li><li><strong>_mint(msg.sender, newTokenId) — </strong>This _mint() function is inherited from ERC721.sol contract. This is used to mint a new token to the contract and on the blockchain.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*3RctjFs6C5YvRXucDcm9vw.png" /><figcaption>_mint funtion in ERC721.sol</figcaption></figure><p><strong>_setTokenURI</strong>(newTokenId, tokenURI) — This _setTokenURI() function is also inherited from ERC721URIStorage.sol contract. This is used to set a token URI and check if the token already exists.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4p7SDT7Qk_thPkTl1211Lw.png" /><figcaption>_setTokenURI function from ERC721URIStorage.sol contract</figcaption></figure><p>createMarketItem(newTokenId, price) — This is the function within the contract, which will be explained next.<br>return newTokenId — returns the new token ID.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V1H8eQMTuZduLupMsjEAmQ.png" /><figcaption>Overview of how an NFT is minted.</figcaption></figure><p>Lastly, this function transfers 0.00025 ETH — (listing fee)to the contract as the listing price.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X0vcjEnNQPrnvkvUiAY8mA.png" /><figcaption>Screenshot from goerli.etherscan.io</figcaption></figure><pre>function createMarketItem(uint256 tokenId, uint256 price) private {</pre><pre><strong>require</strong>(price &gt; 0, “Price must be at least 1 wei”);</pre><pre><strong>require</strong>(<em>msg</em>.value == listingPrice);</pre><pre><strong>idToMarketItem</strong>[<strong>tokenId</strong>] = <strong>MarketItem</strong>(tokenId,payable(<em>msg.sender</em>),payable(address(<em>this</em>)),price,false);</pre><pre>_transfer(<em>msg.sender</em>, address(<em>this</em>), tokenId);</pre><pre><strong>emit</strong>  MarketItemCreated( tokenId , <em>msg.sender</em>, address(<em>this</em>),price,false);</pre><pre>}</pre><p>The above function is called by the createToken function, once a token is created, it needs to be on the Market place, for that we call this function. Notice how we have mentioned the visibility as private here, which tells the contract that it can only be called from within the contract</p><p>The first two lines check that the price for the token to be listed on the marketplace should be greater than 0 and that the amount sent along with the function should be exactly equal to the listing fee mentioned ie. 0.00025 ether.</p><p>Next line <strong>idToMarketItem</strong>[<strong>tokenId</strong>] = <strong>MarketItem </strong>(tokenId, payable(<em>msg.sender</em>) ,payable(address(<em>this</em>)),price,false), As mentioned above, idToMarketItem is a mapping that maps the struct MarketItem to a specific key, here, the tokenId. So for a specific token ID, we have, the struct that it points to. We can pass the parameters of the struct as mentioned above.</p><p>payable(msg.sender) — address of the wallet calling the contract.<br>payable(address(this)) — address of the contract.<br>price — the price of the NFT.<br>false — referring to the bool sold.</p><p>_transfer(<em>msg.sender</em>, address(<em>this</em>), tokenId);— This is also a function that has been inherited from the ERC721.sol contract. It’s used to mention the transfer of tokens from one address to another. Here in this case it’s the transfer from msg.sender →address(this).</p><p>emit MarketItemCreated(tokenId,<em>msg.sender</em>,address(<em>this</em>),price,false); — This emits an event. Events are like logs in the contract that notifies if something has happened. For this, we need to define the event MarketItemCreated in our code.</p><pre>event MarketItemCreated (<br>     uint256 indexed tokenId,<br>     address seller,<br>     address owner,<br>     uint256 price,<br>     bool sold<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AMnDlfYBHPurQdVOlJ00nw.png" /><figcaption>Logs of event MarketItemCreated on goerli.etherscan.io</figcaption></figure><pre>function <strong>resellToken</strong>(uint256 tokenId, uint256 price) public payable {<br>     require(idToMarketItem[tokenId].owner == <em>msg.sender</em>);<br>     require(<em>msg</em>.value == listingPrice);<br>     idToMarketItem[tokenId].sold = false;<br>     idToMarketItem[tokenId].price = price;<br>     idToMarketItem[tokenId].seller = payable(<em>msg.sender</em>);<br>     idToMarketItem[tokenId].owner = payable(address(<em>this</em>));<br>      _itemsSold.decrement();<br>      _transfer(<em>msg.sender</em>, address(<em>this</em>), tokenId);<br>}</pre><p>Almost similar to the createTokenfunction, this function already has the IPFS URL that specifies the data. So in our code, we just change the owner from our address to the contract’s address. In addition to this, we also mention the new price of the NTF along with changing the bool sold to false.</p><p>Penultimately, we decrease the variable _itemsSold by 1 and lastly, we call the _transfer function from the ERC721.sol contract which we inherited to transfer the ownership.</p><pre>function createMarketSale(uint256 tokenId) public payable {</pre><pre>   uint price = idToMarketItem[tokenId].price;<br>   address payable creator = idToMarketItem[tokenId].seller;<br>   require(<em>msg</em>.value == price);<br>   idToMarketItem[tokenId].owner = payable(<em>msg.sender</em>);<br>   idToMarketItem[tokenId].sold = true;<br>   idToMarketItem[tokenId].seller = payable(address(0));<br>   _itemsSold.increment();<br>   _transfer(address(<em>this</em>), <em>msg.sender</em>, tokenId);<br>   payable(owner).transfer(listingPrice);<br>   payable(creator).transfer(<em>msg</em>.value);</pre><pre>}</pre><p>This function deals with the transfer of money (ETH) from one address to another. This creates a market sale — Which happens when someone is buying an NFT. <br>.transfer() — inbuilt function to transfer crypto.</p><pre>function fetchMarketItems() public view returns (MarketItem[] memory) {</pre><pre>uint itemCount = _tokenIds.current();<br>uint unsoldItemCount = _tokenIds.current() - _itemsSold.current();<br>uint currentIndex = 0;<br>MarketItem[] memory items = new MarketItem[](unsoldItemCount);<br>for (uint i = 0; i &lt; itemCount; i++) <br>    {<br>      if (idToMarketItem[i + 1].owner == address(<em>this</em>)) <br>       {<br>         uint currentId = i + 1;<br>         MarketItem storage currentItem = idToMarketItem[currentId];<br>         items[currentIndex] = currentItem;<br>          currentIndex += 1;<br>       }<br>    }<br>return items;</pre><pre>}</pre><p>In this return funtion, we fetch the NFTs that are currently owned by the contract — idToMarketItem[i + 1].owner == address(<em>this</em>).</p><p>For this, we first create a temporary array of MarketItem called items and give it a fixed size unsoldItemCount which we get by subtracting the current index of _tokenIds with current number of items sold in our contract — _itemsSold.current().</p><p>Then, we iterate through this array and apply the condition to check if the owner of the NFT is the contract or not, if yes, then push the details of the NFT to the temporary array created ( items ). In the end return the array items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qYSZiRLK8ppDPVblxrDE0g.png" /><figcaption>Market Items</figcaption></figure><pre>function fetchMyNFTs() public view returns (MarketItem[] memory) {</pre><pre>uint totalItemCount = _tokenIds.current();<br>uint itemCount = 0;<br>uint currentIndex = 0;<br>for (uint i = 0; i &lt; totalItemCount; i++) {<br>    <em>// check if nft is mine<br>    </em>if (idToMarketItem[i + 1].owner == <em>msg.sender</em>) <br>    {<br>     itemCount += 1;<br>    }<br>  }</pre><pre>MarketItem[] memory items = new MarketItem[](itemCount);</pre><pre>for (uint i = 0; i &lt; totalItemCount; i++) {<br>     if (idToMarketItem[i + 1].owner == <em>msg.sender</em>) <br>     {<br>      uint currentId = i + 1;<br>      MarketItem storage currentItem = idToMarketItem[currentId];<br>      items[currentIndex] = currentItem;<br>      currentIndex += 1;<br>      }<br>    }<br>return items;<br>}</pre><p>Similar to the above function, here we add one additional step, ie. to find the number of NFTs that we own<strong> </strong>we loop through the list of all the NFTs.</p><p>This is done to provide the temporary array items, its size — itemCount.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZGCbdLY0pzyc9NNqsDCZcg.png" /><figcaption>My NFTs</figcaption></figure><pre>function fetchItemsListed() public view returns (MarketItem[] memory) {</pre><pre>uint totalItemCount = _tokenIds.current();<br>uint itemCount = 0;<br>uint currentIndex = 0;</pre><pre>for (uint i = 0; i &lt; totalItemCount; i++) {<br>    if (idToMarketItem[i + 1].seller == <em>msg.sender</em>) {<br>      itemCount += 1;<br>    }<br>  }</pre><pre>MarketItem[] memory items = new MarketItem[](itemCount);</pre><pre>for (uint i = 0; i &lt; totalItemCount; i++) {<br>    if (idToMarketItem[i + 1].seller == <em>msg.sender</em>) {<br>      uint currentId = i + 1;<br>      MarketItem storage currentItem = idToMarketItem[currentId];<br>      items[currentIndex] = currentItem;<br>      currentIndex += 1;<br>     }<br>   }<br>return items;</pre><pre>}</pre><p>Here also similar to the above function, we get the list of NFTs that we are selling, idToMarketItem[i + 1].seller == <em>msg.sender .</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EQEI_1zanbjGorcybfIebw.png" /><figcaption>Listed NFTs.</figcaption></figure><p>Here is the complete solidity code.</p><pre><a href="https://gist.github.com/Khanisic/ac54144abd4eea043ff31953a98ab29f">https://gist.github.com/Khanisic/ac54144abd4eea043ff31953a98ab29f</a></pre><h3>Links</h3><ul><li><a href="https://github.com/Khanisic/nft_marketplace">Github</a></li><li><a href="https://nft-marketplace-khanisic.vercel.app/">Vercel Deployed Link</a></li></ul><pre>Special thanks to Adrian from <a href="https://www.youtube.com/c/JavaScriptMastery">Javascript Mastery </a>who taught me this project in his <a href="https://javascript-mastery.teachable.com/p/nft-marketplace">course </a>NFT Marketplace.</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2323abca6346" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/creating-an-nft-marketplace-solidity-2323abca6346">Creating an NFT Marketplace With Solidity</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CNN Convolution Neural Network]]></title>
            <link>https://skhan852000.medium.com/cnn-convolution-neural-network-144fc624a4f7?source=rss-75f24f1b219d------2</link>
            <guid isPermaLink="false">https://medium.com/p/144fc624a4f7</guid>
            <dc:creator><![CDATA[Moid Khan]]></dc:creator>
            <pubDate>Wed, 08 Sep 2021 19:25:33 GMT</pubDate>
            <atom:updated>2021-09-08T19:25:33.510Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i35Gy8_7qG6sKGhQ.png" /><figcaption>A Convolutional Neural Network for Impact Detection and Characterization of Complex Composite Structures</figcaption></figure><h3>What is image classification?</h3><p><strong>Image Classification</strong> is a fundamental task that attempts to comprehend an entire image as a whole. The goal is to classify the image by assigning it to a specific label. Typically, Image Classification refers to images in which only one object appears and is analyzed. In contrast, object detection involves both classification and localization tasks, and is used to analyze more realistic cases in which multiple objects may exist in an image.</p><p>A breakthrough in building models for image classification came with the discovery that a <a href="https://wikipedia.org/wiki/Convolutional_neural_network">convolutional neural network</a> (CNN) could be used to progressively extract higher- and higher-level representations of the image content. Instead of preprocessing the data to derive features like textures and shapes, a CNN takes just the image’s raw pixel data as input and “learns” how to extract these features, and ultimately infer what object they constitute.</p><h3>Convolutional Neural Network (CNN) :</h3><p>Convolutional Neural Network is an approach used in image recognition and processing that is specifically designed to process pixel data.</p><p>To start, the CNN receives an input feature map: a three-dimensional matrix where the size of the first two dimensions corresponds to the length and width of the images in pixels. The size of the third dimension is 3 (corresponding to the 3 channels of a color image: red, green, and blue). The CNN comprises a stack of modules, each of which performs three operations.</p><p>A <em>convolution</em> extracts tiles of the input feature map, and applies filters to them to compute new features, producing an output feature map, or <em>convolved feature</em> (which may have a different size and depth than the input feature map). Convolutions are defined by two parameters:</p><ul><li><strong>Size of the tiles that are extracted</strong> (typically 3x3 or 5x5 pixels).</li><li><strong>The depth of the output feature map</strong>, which corresponds to the number of filters that are applied.</li></ul><p>During a convolution, the filters (matrices the same size as the tile size) effectively slide over the input feature map’s grid horizontally and vertically, one pixel at a time, extracting each corresponding tile.</p><p>For each filter-tile pair, the CNN performs element-wise multiplication of the filter matrix and the tile matrix, and then sums all the elements of the resulting matrix to get a single value. Each of these resulting values for every filter-tile pair is then output in the <em>convolved feature</em> matrix.</p><p>During training, the CNN “learns” the optimal values for the filter matrices that enable it to extract meaningful features (textures, edges, shapes) from the input feature map. As the number of filters (output feature map depth) applied to the input increases, so does the number of features the CNN can extract. However, the tradeoff is that filters compose the majority of resources expended by the CNN, so training time also increases as more filters are added. Additionally, each filter added to the network provides less incremental value than the previous one, so engineers aim to construct networks that use the minimum number of filters needed to extract the features necessary for accurate image classification.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=144fc624a4f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use of Javascript in NETFLIX]]></title>
            <link>https://skhan852000.medium.com/use-of-javascript-in-netflix-fee3bbd1568a?source=rss-75f24f1b219d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fee3bbd1568a</guid>
            <dc:creator><![CDATA[Moid Khan]]></dc:creator>
            <pubDate>Wed, 18 Aug 2021 08:42:17 GMT</pubDate>
            <atom:updated>2021-08-18T08:42:17.095Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B2VW6bM4It-kxxJfsXMIOw.png" /></figure><p>JavaScript is a scripting or programming language that allows you to implement complex features on web pages every time a web page does more than just sit there and display static information for you to look at displaying timely content updates, interactive maps, animated 2D/3D graphics.</p><p><strong>Need of javascript</strong></p><ul><li>Autocomplete: The search box gives suggestions, based on what the user has already typed.</li><li>Form validation: If the users make a mistake while filling a form, JavaScript immediately informs them of the error, avoiding filling it all in again.</li><li>Fixes layout issues to avoid the overlapping of elements on the page.</li><li>Adds animation to the page to make it more attractive.</li></ul><p><a href="https://netflix.com/">Netflix</a> is one of the most popular video streaming services. Since launching globally in 2016, the company has found that many new users are not only signing up on mobile devices but are also using less-than-ideal connections to do so. By refining the JavaScript used for Netflix.com’s sign-up process and using prefetching techniques, the developer team was able to provide a better user experience for both mobile and desktop users and offer several improvements.</p><ul><li>Loading and Time-to-Interactive decreased by 50% (for the logged-out desktop homepage at Netflix.com)</li><li>JavaScript bundle size reduced by 200kB by switching from React and other client-side libraries to vanilla JavaScript. React was still used server-side.</li><li>Prefetching HTML, CSS and JavaScript (React) reduced Time-to-Interactive by 30% for future navigations</li></ul><p>By prefetching resources and optimizing the client-side code on Netflix’s logged-out homepage, Netflix was able to greatly improve their Time-to-Interactive metrics during the sign-up process. By prefetching future pages using the built-in browser API and XHR prefetching, Netflix was able to reduce Time-to-Interactive by 30%. This was for the second-page loading, which contained the bootstrapping code for single-page app sign-up flow.The code optimizations carried out by the Netflix team showed that while React is a useful library, it may not provide an adequate solution to every problem. By removing React from the client-side code on the first landing page for signup, the Time-to-Interactive was improved by over 50%. Reducing Time-to-Interactive on the client-side also caused users to click the sign-up button at a greater rate, showing that code optimization can lead to a greater user experience overall.</p><p>While Netflix didn’t use React for the homepage, they prefetched it for subsequent pages. This allowed them to leverage client-side React throughout the rest of the single page application sign-up process.</p><p><strong>CONCLUSION</strong></p><p>Netflix discovered opportunities to improve their Time-to-Interactive by keeping a close eye on the cost of JavaScript.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fee3bbd1568a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cybercrime — Confusion Matrix]]></title>
            <link>https://skhan852000.medium.com/cybercrime-confusion-matrix-77fc07b14ceb?source=rss-75f24f1b219d------2</link>
            <guid isPermaLink="false">https://medium.com/p/77fc07b14ceb</guid>
            <dc:creator><![CDATA[Moid Khan]]></dc:creator>
            <pubDate>Sun, 06 Jun 2021 14:28:45 GMT</pubDate>
            <atom:updated>2021-06-06T14:28:45.296Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cybercrime — Confusion Matrix</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*WLgE2y76Yp_x84gcRMGa6g.png" /></figure><p>Task 05 — Summer Program 2021</p><p>Task Description :</p><blockquote><strong>Create a blog about cybercrime cases where they talk about the confusion matrix or its two types of error.</strong></blockquote><p>Let us first discuss what is Cybercrime, as Wikipedia suggests <strong>Cybercrime </strong>is a crime that involves a computer and a network. The computer may have been used in the commission of a crime, or it may be the target. Cybercrime may harm someone’s security and financial health.</p><p>There are few or many cases wherein a company where a cyber attack happens and the prediction of the attack plays an important role in knowing whether the attack really did happen or not. To know if the attack has happened, they use a confusion matrix where it gives some of the information they needed. so let’s understand the confusion matrix.</p><h3>Confusion Matrix</h3><p>A Confusion matrix is an N x N matrix used for evaluating the performance of a classification model, where N is the number of target classes. It is a table with 4 different combinations of predicted and actual values. The matrix compares the actual target values with those predicted by the machine learning model.</p><blockquote>A basic layout for a binary classification problem, we would have a 2 x 2 matrix as shown below with 4 values:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/0*dQZTlh0LBReqwJ-Y.png" /></figure><blockquote><strong>True Positive</strong>: True Positive: Predicted values correctly predicted as actual positive</blockquote><blockquote><strong>False Positive</strong>: Predicted values incorrectly predicted an actual positive. i.e., Negative values predicted as positive. Also known as the Type 1 error</blockquote><blockquote><strong>False Negative</strong>: False Negative: Positive values predicted as negative. Also known as the Type 2 error</blockquote><blockquote><strong>True Negative</strong>: True Negative: Predicted values correctly predicted as an actual negative</blockquote><h3>Accuracy of the model</h3><p>Accuracy is used when the True Positives and True Negatives are more important. Accuracy is a better metric for Balanced Data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/0*wA3ys3a8YEcpZx4N.png" /></figure><p>In the above figure, it can be seen that TN and TP are having the actual and predicted values correct respectively. The accuracy of a model (through a confusion matrix) is calculated by the sum of all true values divided by total values, i.e.,</p><p>Accuracy = TN+TP / TN+FP+FN+TP</p><p>Accuracy can be misleading if used with imbalanced datasets, and therefore there are other metrics based on confusion matrix which can be useful for evaluating performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77fc07b14ceb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Grievance Redressal System using DJANGO]]></title>
            <link>https://skhan852000.medium.com/grievance-redressal-system-using-django-babddc43e80b?source=rss-75f24f1b219d------2</link>
            <guid isPermaLink="false">https://medium.com/p/babddc43e80b</guid>
            <dc:creator><![CDATA[Moid Khan]]></dc:creator>
            <pubDate>Mon, 29 Mar 2021 16:54:26 GMT</pubDate>
            <atom:updated>2021-03-29T16:54:26.722Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SB0ADR1pPy8rIxLIe3t6PA.png" /><figcaption>Home Page</figcaption></figure><p>A fully fledged Grievance Redressal System that addresses public complaints on day-to-day scenarios.</p><p>I along with my team have designed and developed this system in 2 days using Django which is a powerful python web framework used to design Web Applications. Django has its own database that makes it independent to store data.</p><p>We have created 2 database models, one for User details and the other for Complaints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ZTczJz4JCmTASVdFzaOwA.png" /><figcaption>models.py for creating models.</figcaption></figure><h3>Here is the step by step process on how to register a complaint :</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yOQAXRK-Tc5AunisPcLW5w.png" /><figcaption>1. Sign Up by clicking the Sign In button from the homepage</figcaption></figure><p>2. After Signing up, login using your credentials at the homepage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Cb_f-VDdQ3CNpKlGztcsw.png" /><figcaption>3. Click on Add Grievance/Complaint ( it will redirect you to Grievance page )</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*anySI0hvu9wwYvpzPYIBHg.png" /><figcaption>4.Submit Your Complaint</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ldKll816YWGd5RqkB3WMRw.png" /><figcaption>5. You can view your complaint by entering your user ID.</figcaption></figure><p>6. Wait for the response of your complaint.</p><h3>Admin Dashboard :</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQyA9_jhU7M-KmEHLO3QhA.png" /><figcaption>This is the admin dashboard, here the admin can reject/acknowledge the complaints. The updated status then gets displayed to the user on his/her user dashboard.</figcaption></figure><h3>Documentation and Code :</h3><p>https://github.com/Khanisic/myCity-Grievance-Portal-Mini-Project</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=babddc43e80b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>