<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Yassin Mahmud Abdul Quddus, Author at Be on the Right Side of Change</title>
	<atom:link href="https://blog.finxter.com/author/yassinmahmudabdulquddus/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.finxter.com/author/yassinmahmudabdulquddus/</link>
	<description></description>
	<lastBuildDate>Sat, 04 Nov 2023 20:19:21 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://blog.finxter.com/wp-content/uploads/2020/08/cropped-cropped-finxter_nobackground-32x32.png</url>
	<title>Yassin Mahmud Abdul Quddus, Author at Be on the Right Side of Change</title>
	<link>https://blog.finxter.com/author/yassinmahmudabdulquddus/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Prompt Engineering with Llama 2 (Full Course)</title>
		<link>https://blog.finxter.com/prompt-engineering-with-llama-2-full-course/</link>
		
		<dc:creator><![CDATA[Yassin Mahmud Abdul Quddus]]></dc:creator>
		<pubDate>Sat, 04 Nov 2023 20:19:20 +0000</pubDate>
				<category><![CDATA[Artificial Intelligence]]></category>
		<category><![CDATA[ChatGPT]]></category>
		<category><![CDATA[Large Language Model (LLM)]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[Prompt Engineering]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1651865</guid>

					<description><![CDATA[<p>💡 This&#160;Llama 2 Prompt Engineering course helps you stay on the right side of change.&#160;Our course is meticulously designed to provide you with hands-on experience through genuine projects. 🔗 Prompt Engineering with Llama 2: Four Practical Projects using Python, Langchain, and Pinecone You&#8217;ll delve into practical applications such as book PDF querying, payroll auditing, and ... <a title="Prompt Engineering with Llama 2 (Full Course)" class="read-more" href="https://blog.finxter.com/prompt-engineering-with-llama-2-full-course/" aria-label="Read more about Prompt Engineering with Llama 2 (Full Course)">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/prompt-engineering-with-llama-2-full-course/">Prompt Engineering with Llama 2 (Full Course)</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> This&nbsp;Llama 2 Prompt Engineering course helps you stay on the right side of change.&nbsp;Our course is meticulously designed to provide you with <em>hands-on experience through genuine projects</em>.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="Prompt Engineering with Llama 2 (Full Course)" width="937" height="527" src="https://www.youtube.com/embed/v5A6qJ-O_pQ?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<div class="wp-block-buttons alignwide is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex">
<div class="wp-block-button"><a class="wp-block-button__link has-text-align-center wp-element-button" href="https://academy.finxter.com/university/prompt-engineering-with-llama-2/">Llama 2 Academy Course &#8211; Get Your PDF Certificate</a></div>
</div>



<p class="has-text-align-center"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f517.png" alt="🔗" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <a href="https://academy.finxter.com/university/prompt-engineering-with-llama-2/"><strong>Prompt Engineering with Llama 2: Four Practical Projects using Python, Langchain, and Pinecone</strong></a></p>



<p>You&#8217;ll delve into practical applications such as book PDF querying, payroll auditing, and hotel review analytics.</p>



<p>These aren&#8217;t just theoretical exercises; they&#8217;re real-world challenges that businesses face daily.</p>



<p>By studying these projects, you&#8217;ll gain a deeper comprehension of how to harness the power of Llama 2 using <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f40d.png" alt="🐍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Python, <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f517.png" alt="🔗" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f99c.png" alt="🦜" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Langchain, <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f332.png" alt="🌲" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Pinecone, and a whole stack of highly <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2692.png" alt="⚒" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f6e0.png" alt="🛠" class="wp-smiley" style="height: 1em; max-height: 1em;" /> practical tools of exponential coders in a post-ChatGPT world.</p>



<p>Specifically, you&#8217;ll learn these topics (ToC):</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://academy.finxter.com/university/prompt-engineering-with-llama-2/" target="_blank" rel="noreferrer noopener"><img fetchpriority="high" decoding="async" width="809" height="977" src="https://blog.finxter.com/wp-content/uploads/2023/09/image-131.png" alt="" class="wp-image-1651866" srcset="https://blog.finxter.com/wp-content/uploads/2023/09/image-131.png 809w, https://blog.finxter.com/wp-content/uploads/2023/09/image-131-248x300.png 248w, https://blog.finxter.com/wp-content/uploads/2023/09/image-131-768x927.png 768w" sizes="(max-width: 809px) 100vw, 809px" /></a></figure>
</div>


<p>This knowledge can be your foundation in creating solutions that have tangible value for real people. Equip yourself with the expertise to keep pace with technological change and be a proactive force in shaping it.</p>



<div class="wp-block-buttons alignwide is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex">
<div class="wp-block-button"><a class="wp-block-button__link has-text-align-center wp-element-button" href="https://academy.finxter.com/university/prompt-engineering-with-llama-2/">Llama 2 Academy Course &#8211; Get Your PDF Certificate</a></div>
</div>
<p>The post <a href="https://blog.finxter.com/prompt-engineering-with-llama-2-full-course/">Prompt Engineering with Llama 2 (Full Course)</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How I Built My Own ERC-20 Token (2/2)</title>
		<link>https://blog.finxter.com/how-i-built-my-own-erc-20-token-2-2/</link>
		
		<dc:creator><![CDATA[Yassin Mahmud Abdul Quddus]]></dc:creator>
		<pubDate>Tue, 21 Feb 2023 20:33:55 +0000</pubDate>
				<category><![CDATA[Crypto]]></category>
		<category><![CDATA[Ethereum]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[Smart Contracts]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1151626</guid>

					<description><![CDATA[<p>In the first part, we connected the front end with Metamask but couldn&#8217;t fetch the balance. Let&#8217;s try to fetch the balance from the wallet this time. But first, install the ether.js library to communicate with the smart contract. Import ether.js library to App.js. Now we need to import the contract ABI. 💡 The contract ... <a title="How I Built My Own ERC-20 Token (2/2)" class="read-more" href="https://blog.finxter.com/how-i-built-my-own-erc-20-token-2-2/" aria-label="Read more about How I Built My Own ERC-20 Token (2/2)">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-i-built-my-own-erc-20-token-2-2/">How I Built My Own ERC-20 Token (2/2)</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="How I Built My Own ERC-20 Token (2/2)" width="937" height="527" src="https://www.youtube.com/embed/GNV3pPgdKKE?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>In the <a href="https://blog.finxter.com/how-i-built-my-own-erc-20-token-1-2/" data-type="post" data-id="1148734" target="_blank" rel="noreferrer noopener">first part</a>, we connected the front end with <a href="https://blog.finxter.com/metamask-simple-tutorial/" data-type="post" data-id="38157" target="_blank" rel="noreferrer noopener">Metamask</a> but couldn&#8217;t fetch the balance. Let&#8217;s try to fetch the balance from the wallet this time. But first, install the <code>ether.js</code> library to communicate with the smart contract.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">npm install --save ethers</pre>



<p><br>Import <code>ether.js</code> library to <code>App.js</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import {ethers} from "ethers";</pre>



<p><br>Now we need to import the contract ABI. </p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> The <strong>contract ABI</strong> is the JSON format of the contract that saves the bytecode of the deployed contract. </p>



<p>Create a <code>contracts</code> folder inside the source folder. Inside this <code>contracts</code> folder, create a JSON file called <code>SilverToken.json</code>. </p>



<p>Copy the ABI of the contract from the <a rel="noreferrer noopener" href="https://blog.finxter.com/solidity-remix-ide-quickstart/" data-type="post" data-id="946353" target="_blank">Remix IDE</a> and paste it inside the JSON file. Now import the ABI from the JSON file to the <code>app.js</code>.<br></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import contractABI from "./contracts/SilverToken.json";</pre>



<p>Create a variable for the contract address.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const contractAddress = "0xC16322799f2645D5b7a1287392072aA668F8144B";</pre>



<p><br>We need to create a contract instance to get access to the methods of our deployed smart contract. We need three things to create an instance of the contract. Those are the provider, signer, and contract ABI. </p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="957" height="632" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-300.png" alt="" class="wp-image-1149109" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-300.png 957w, https://blog.finxter.com/wp-content/uploads/2023/02/image-300-300x198.png 300w, https://blog.finxter.com/wp-content/uploads/2023/02/image-300-768x507.png 768w" sizes="auto, (max-width: 957px) 100vw, 957px" /></figure>
</div>


<p>We already imported the ABI. So, let&#8217;s create <a rel="noreferrer noopener" href="https://blog.finxter.com/state-variables-in-solidity/" data-type="post" data-id="765838" target="_blank">state variables</a> for the provider, signer, and contract and initially keep all the values null.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const [provider, setProvider] = useState(null);
const [signer, setSigner] = useState(null);
const [contract, setContract] = useState(null);</pre>



<p><br>Inside the <code>connectMetamask</code> button define <code>provider</code>, <code>signer</code>, and <code>contract</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const provider = new Web3Provider(window.ethereum);
const signer = provider.getSigner();
const contract = new ethers.Contract(
                               contractAddress,
                               contractABI,
                               signer);
setProvider(provider);
setContract(contract);
setSigner(signer);</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="410" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-302.png" alt="" class="wp-image-1151646" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-302.png 624w, https://blog.finxter.com/wp-content/uploads/2023/02/image-302-300x197.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<p>We defined the provider with the help of the <code>Web3Provider</code> method of the <code>ethers</code> library. In our case, the provider would be Metamask.</p>



<p>I was unable to access the <code>providers</code> library of ethers for some unknown reason. That’s why I imported the <code>providers</code> library from the <code>npm</code> Ethereum providers. You can use <a href="https://www.npmjs.com/package/@ethersproject/providers" data-type="URL" data-id="https://www.npmjs.com/package/@ethersproject/providers" target="_blank" rel="noreferrer noopener">this link</a> if you need it. </p>



<p>First, install and then import the <code>providers</code> library.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">npm i @ethersproject/providers</pre>



<p>since we will use the <code>Web3Provider</code> from the <code>providers</code> library, we will import this only.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import { Web3Provider } from "@ethersproject/providers";</pre>



<p>We are committing a transaction, so we must need a signer. We called the signer by using the <code>getSigner()</code> method of the provider.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="682" height="1024" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-245-682x1024.png" alt="" class="wp-image-1073516" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-245-682x1024.png 682w, https://blog.finxter.com/wp-content/uploads/2023/01/image-245-200x300.png 200w, https://blog.finxter.com/wp-content/uploads/2023/01/image-245.png 714w" sizes="auto, (max-width: 682px) 100vw, 682px" /></figure>
</div>


<p>Then we created an instance of our smart contract with the <code>contract()</code> method of the <code>ethers</code> library. </p>



<p>This <code>contract()</code> method takes the <a href="https://blog.finxter.com/solidity-members-of-address-types-and-type-information/" data-type="post" data-id="896974" target="_blank" rel="noreferrer noopener">contract address</a>, ABI, and the signer as the parameters.</p>



<p>Now the provider, signer, and contract are defined. So, we need to change the state of these three that we have defined as null earlier.</p>



<p>Now let’s <code><a rel="noreferrer noopener" href="https://blog.finxter.com/javascript-intro-how-to-see-your-code-output/" data-type="post" data-id="175068" target="_blank">console.log</a></code> the contract to check if all changes occurred.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">console.log(contract);</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="559" height="358" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-303.png" alt="" class="wp-image-1151653" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-303.png 559w, https://blog.finxter.com/wp-content/uploads/2023/02/image-303-300x192.png 300w" sizes="auto, (max-width: 559px) 100vw, 559px" /></figure>
</div>


<p>As you can see in my console, the contract&#8217;s state was initially null. But now it returns the contract address that we are connected to.</p>



<h2 class="wp-block-heading">Get Wallet Balance</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="707" height="462" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-306.png" alt="" class="wp-image-1151677" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-306.png 707w, https://blog.finxter.com/wp-content/uploads/2023/02/image-306-300x196.png 300w" sizes="auto, (max-width: 707px) 100vw, 707px" /></figure>
</div>


<p><br>Create a <code>getBalance()</code> method to get the balance from the address.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">  const getBalance = async () => {
    const balanceInBig = await contract.balanceOf(activeAccount);
    const balanceInNum = Number(balanceInBig) / 100;
    setTokenBalance(balanceInNum);
  };
</pre>



<p>We are using the <code>balanceOf</code> method of the contract to get the balance of our address. The balance will be returned as a <code>bigInteger</code> number. Read more about <code>BigInt</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" data-type="URL" data-id="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" target="_blank" rel="noreferrer noopener">here</a>.</p>



<p>In the 2nd line, we converted the big integer number to a readable format.</p>



<p>To initiate the <code>getBalance()</code> function, we can use <a rel="noreferrer noopener" href="https://blog.finxter.com/project-react-dapp-for-selling-ebooks-in-a-decentralized-manner-1-4/" data-type="post" data-id="1055370" target="_blank">React</a>&#8216;s <code>useEffect()</code> hook.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">useEffect(() => {
    if (contract != null) {
      getBalance();
    }
  }, [contract]);
</pre>



<p><br>The <code>useEffect()</code> hook will trigger the <code>getBalance</code> method if a contract is available. The <code>useEffect()</code> hook will render the page again whenever the contract is changed.</p>



<h2 class="wp-block-heading">Transfer the Balance</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="709" height="636" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-307.png" alt="" class="wp-image-1151678" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-307.png 709w, https://blog.finxter.com/wp-content/uploads/2023/02/image-307-300x269.png 300w" sizes="auto, (max-width: 709px) 100vw, 709px" /></figure>
</div>


<p>Now to transfer the balance, we need a form where we will input the address of the account to which we will be transferring the amount. Let&#8217;s do this part in a separate functional component.</p>



<p>Let&#8217;s create a components folder inside the source folder and create a new file called <code>Transaction.js</code>. </p>



<p>Inside this file, create a component structure by pressing &#8220;<code>rsc</code>&#8221; on the keyboard. If the autocompletion doesn&#8217;t work, no need to worry. Write the code manually.</p>



<p>I will create a simple form using custom codes from flowbite. You can check it out or make your own custom one. Inside the return function, paste the following.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">  return (
    &lt;div className="w-1/2 mx-auto bg-slate-600 mt-10 p-5 border rounded-lg">
      &lt;form onSubmit={transactionHandler}>
        &lt;div className="mb-6">
          &lt;label
            for="address"
            className="block mb-2 text-sm font-medium text-gray-900 dark:text-white"
          >
            Receiver Address
          &lt;/label>
          &lt;input
            type="text"
            id="address"
            className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
            placeholder="Enter Receiver Address"
            required
          />
        &lt;/div>
        &lt;div className="mb-6">
          &lt;label
            for="amount"
            className="block mb-2 text-sm font-medium text-gray-900 dark:text-white"
          >
            Transfer Amount
          &lt;/label>
          &lt;input
            type="number"
            id="amount"
            className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
            required
          />
        &lt;/div>
        &lt;button
          type="submit"
          className="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm w-full sm:w-auto px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"
        >
          Send Token
        &lt;/button>
        &lt;div className="mt-5">
          &lt;h3 className="text-slate-100">{transactionHash}&lt;/h3>
        &lt;/div>
      &lt;/form>
    &lt;/div>
  );
</pre>



<p><br>We created two input fields inside the form. One is text type for the receiver address, and another is a number type for the amount that would be sent to the receiver.</p>



<p>The id of each input filed is changed to &#8220;<code>address</code>&#8221; and &#8220;<code>amount</code>&#8221; respectively.</p>



<p>A <code>transactionHandler()</code> function will be triggered whenever you click on the <code>send</code> button. This function will collect the info from the input fields and do something further.</p>



<p>Let’s define the <code>transactionHandler()</code> function.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const transactionHandler = async (event) => {
    event.preventDefault();
    let receiverAddress = event.target.address.value;
    let sendAmount = event.target.amount.value;
    let transferAmount = sendAmount * 100;
    let trans = await contract.transfer(receiverAddress, transferAmount);
    console.log(trans);
    setTransactionHash("Transaction confirmed with hash:" + trans.hash);
  };
</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="219" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-304.png" alt="" class="wp-image-1151666" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-304.png 624w, https://blog.finxter.com/wp-content/uploads/2023/02/image-304-300x105.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<p>The <code>transactionHandler()</code> is an <code>async await</code> function that will trigger an event. The <code>preventDefault()</code> method will prevent the function from reloading automatically for changes.</p>



<p>The <code>transferAmount</code> and <code>receiverAddress</code> variables will collect the info from the input fields. “<code>event.target</code>&#8221; will access the input fields by using the id of the input field &#8220;<code>amount</code>&#8221; and &#8220;<code>address</code>.&#8221;</p>



<p>We need to use the <code>transfer</code> method of the contract to commit the transaction. To access the contract state, we need to pass it as a prop from the <code>app.js</code> file.</p>



<p>Call the <code>transaction.js</code> component from the <code>app.js</code> file and pass the contract as props.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;Transaction contract={contract}>&lt;/Transaction></pre>



<p>We are using the “<code>contract.transfer</code>” method to commit the transaction. This method will take the receiver address and the send amount as parameters.</p>



<p>We will get a transaction hash as a transfer confirmation when the transaction is done. We can store this transaction hash as a state variable to display it on the user interface.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="707" height="478" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-308.png" alt="" class="wp-image-1151679" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-308.png 707w, https://blog.finxter.com/wp-content/uploads/2023/02/image-308-300x203.png 300w" sizes="auto, (max-width: 707px) 100vw, 707px" /></figure>
</div>


<p>Let’s create a new account on the Goerli testnet. This will be our receiver account. </p>



<p>Now use this address and send an amount of 50 tokens from the main wallet. We need to multiply the amount by 100 to get the exact value, as we used a two-digit return in the decimals function of the smart contract.</p>



<p>Now if you check this transaction hash on the Etherscan website, you will get the complete transaction details. You will also receive the token balance on the Metamask receiver wallet.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="424" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-305.png" alt="" class="wp-image-1151670" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-305.png 624w, https://blog.finxter.com/wp-content/uploads/2023/02/image-305-300x204.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<p>This is the screenshot of my recent transaction. To get your transaction details, just use the transaction hash in the search bar. Make sure you choose the Goerli testnet as the network.</p>



<p>That’s all for today. Thanks for the reading! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2665.png" alt="♥" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Github</strong>: <a rel="noreferrer noopener" href="https://github.com/finxter/silver_wallet" target="_blank">https://github.com/finxter/silver_wallet</a></p>
<p>The post <a href="https://blog.finxter.com/how-i-built-my-own-erc-20-token-2-2/">How I Built My Own ERC-20 Token (2/2)</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How I Built My Own ERC-20 Token (1/2)</title>
		<link>https://blog.finxter.com/how-i-built-my-own-erc-20-token-1-2/</link>
		
		<dc:creator><![CDATA[Yassin Mahmud Abdul Quddus]]></dc:creator>
		<pubDate>Mon, 20 Feb 2023 17:06:38 +0000</pubDate>
				<category><![CDATA[Crypto]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[dApp]]></category>
		<category><![CDATA[Ethereum]]></category>
		<category><![CDATA[React]]></category>
		<category><![CDATA[Smart Contracts]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1148734</guid>

					<description><![CDATA[<p>Project Scenario In this 2-part series, I&#8217;ll show you how I built my own ERC-20 token like ETH in this project. I share this because you may want to do the same and learn from my experience. 👉 Recommended: How I Built My Own ERC-20 Token (2/2) I use Solidity to write a smart contract ... <a title="How I Built My Own ERC-20 Token (1/2)" class="read-more" href="https://blog.finxter.com/how-i-built-my-own-erc-20-token-1-2/" aria-label="Read more about How I Built My Own ERC-20 Token (1/2)">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-i-built-my-own-erc-20-token-1-2/">How I Built My Own ERC-20 Token (1/2)</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="How I Built My Own ERC-20 Token (1/2)" width="937" height="527" src="https://www.youtube.com/embed/FfwjGQ3zUEg?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading">Project Scenario</h2>



<p>In this 2-part series, I&#8217;ll show you how I built my own ERC-20 token like ETH in this project. I share this because you may want to do the same and learn from my experience.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/how-i-built-my-own-erc-20-token-2-2/" data-type="post" data-id="1151626" target="_blank" rel="noreferrer noopener">How I Built My Own ERC-20 Token (2/2)</a></p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="768" height="641" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-298.png" alt="" class="wp-image-1149104" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-298.png 768w, https://blog.finxter.com/wp-content/uploads/2023/02/image-298-300x250.png 300w" sizes="auto, (max-width: 768px) 100vw, 768px" /></figure>
</div>


<p>I use Solidity to write a smart contract for my ERC-20 token, and then the contract will be deployed on a test net, for starters. </p>



<p>The token balance will be displayed on the user interface along with the wallet address. The front end will be formed with React &amp; Tailwind CSS.</p>



<p>In the next part of this series, I&#8217;ll show you how to transfer tokens with the help of the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/i-created-a-counter-smart-contract-with-ether-js-heres-how/" data-type="post" data-id="1002304" target="_blank">ether.js</a></code> library. You&#8217;ll be able to check the details regarding the transaction by using the transaction hash on the Etherscan website.</p>



<h2 class="wp-block-heading">Create the Smart Contract</h2>



<p>We will use the Openzeppelin framework to build our ERC-20 token.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/how-does-the-erc-20-token-work/" data-type="URL" data-id="https://blog.finxter.com/how-does-the-erc-20-token-work/" target="_blank" rel="noreferrer noopener">How Does the ERC-20 Token Work?</a></p>



<p>OpenZeppelin is a secured open-source framework that is used to build, manage, and inspect all aspects of software development for decentralized applications. OpenZeppelin’s ERC-20 <a rel="noreferrer noopener" href="https://blog.finxter.com/layout-of-a-solidity-source-file/" data-type="post" data-id="455693" target="_blank">solidity file</a> contains all the code to build the token.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="956" height="637" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-299.png" alt="" class="wp-image-1149107" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-299.png 956w, https://blog.finxter.com/wp-content/uploads/2023/02/image-299-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2023/02/image-299-768x512.png 768w" sizes="auto, (max-width: 956px) 100vw, 956px" /></figure>
</div>


<p>Move to the <a href="https://blog.finxter.com/solidity-remix-ide-quickstart/" data-type="post" data-id="946353" target="_blank" rel="noreferrer noopener">Remix IDE</a> and create a solidity file inside the contract folder. I am naming it as “<code>SilverToken.sol</code>”. Declare the <a href="https://blog.finxter.com/layout-of-a-solidity-source-file-spdx-license-identifier-and-version-pragmas/" data-type="post" data-id="703612" target="_blank" rel="noreferrer noopener">solidity version number</a> in the first line.</p>



<p>So, import Openzeppelin’s ERC-20 Solidity file.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pragma solidity  >= 0.5.0 &lt; 0.9.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";</pre>



<p>If you want to learn more about the OpenZeppelin implementation, you can follow <a rel="noreferrer noopener" href="https://docs.openzeppelin.com/contracts/4.x/erc20" data-type="URL" data-id="https://docs.openzeppelin.com/contracts/4.x/erc20" target="_blank">this link</a>.</p>



<p>Now create the contract named <code>SilverToken</code>. This token inherits the token structure from the ERC-20 implementation of Openzeppelin.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">contract SilverToken is ERC20 {
    constructor (uint256 initialSupply) ERC20("silver", "SLV"){
        _mint(msg.sender, initialSupply);
    }
    function decimals() public pure override returns (uint8) {
        return 2;
    }
}
</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="277" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-293.png" alt="" class="wp-image-1149067" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-293.png 624w, https://blog.finxter.com/wp-content/uploads/2023/02/image-293-300x133.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<p>As our token is a child of the ERC-20 class, we can access the different methods of that class now. We are calling the constructor method first. This method asks for the initial supply amount to the contract.</p>



<p>We called the base contractor ERC-20 with name and symbol parameters. This will pass the name and symbol of our token to the parent constructor. Silver is the name of our token, and SLV is the symbol.</p>



<p>To create the initial supply, we started minting tokens. The initial supply of the token will be minted to the <code>msg.sender</code> which is the address of the person who deploys the contract.</p>



<p>We usually can see the 18<sup>th</sup> decimal of precession for the ETH value. But here, for simplicity, we override that decimal function. We will get up to 2 decimal values.</p>



<h2 class="wp-block-heading">Deploy the Smart Contract</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="957" height="632" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-300.png" alt="" class="wp-image-1149109" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-300.png 957w, https://blog.finxter.com/wp-content/uploads/2023/02/image-300-300x198.png 300w, https://blog.finxter.com/wp-content/uploads/2023/02/image-300-768x507.png 768w" sizes="auto, (max-width: 957px) 100vw, 957px" /></figure>
</div>


<p>Let’s compile the contract and move to the deployment section. </p>



<p>We will deploy this on the Goerli <a href="https://blog.finxter.com/how-to-deploy-a-smart-contract-to-the-ropsten-testnet-in-brownie/" data-type="post" data-id="63341">testnet</a>. It would be best if you had the goerli test network added to your browser. </p>



<p>If you don&#8217;t have the goerli test network on your browser, then move to the &#8220;add network&#8221; option of the <a rel="noreferrer noopener" href="https://blog.finxter.com/metamask-simple-tutorial/" data-type="post" data-id="38157" target="_blank">Metamask</a> and add the goerli test net from the networks option. </p>



<p>The configuration for the goerli network is given below:</p>



<ul class="wp-block-list">
<li><strong>Network name:</strong> Goerli test network</li>



<li><strong>New RPC URL:</strong> <a href="https://goerli.infura.io/v3/" target="_blank" rel="noreferrer noopener">https://goerli.infura.io/v3/</a></li>



<li><strong>Chain ID:</strong> 5</li>



<li><strong>Currency symbol:</strong> GoerliETH</li>



<li><strong>Block explorer URL (Optional):</strong> <a href="https://goerli.etherscan.io" target="_blank" rel="noreferrer noopener">https://goerli.etherscan.io</a></li>
</ul>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="469" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-294.png" alt="" class="wp-image-1149068" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-294.png 624w, https://blog.finxter.com/wp-content/uploads/2023/02/image-294-300x225.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<p>Goerli testnet must be added to your browser by this time. </p>



<p>You can create a new account by clicking the <code>create account</code> option of Metamask. </p>



<p>We need some goerli Eth in your wallet for the deployment cost. You can quickly get some free goerli eth from <em><strong>goerliFaucet.com</strong></em>.</p>



<p>You may need to sign up in Alchemy to avail the opportunity. Just sign up on Alchemy and create an app. Move back to the goerli faucet and transfer some ETH to your wallet. It&#8217;s that simple.&nbsp;</p>



<p>Now get back to the Remix IDE. Choose the <strong><em>“Injected provider- Metamask”</em></strong> option from the environment dropdown menu. Make sure you are logged into the goerli testnet in Metamask. </p>



<p>You must see the goerli wallet address on the account section if you get connected to Remix IDE. Choose any account. You have to set an initial amount to supply at this address. </p>



<p>I am setting the initial supply amount as a million goerli ETH. <a href="https://blog.finxter.com/how-to-sell-coupons-on-eth-build-deploy-and-test-the-smart-contract-2-4/" data-type="post" data-id="952575" target="_blank" rel="noreferrer noopener">Deploy the contract</a>, and you will see all the functions and data types available under the menu.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="312" height="563" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-295.png" alt="" class="wp-image-1149070" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-295.png 312w, https://blog.finxter.com/wp-content/uploads/2023/02/image-295-166x300.png 166w" sizes="auto, (max-width: 312px) 100vw, 312px" /></figure>
</div>


<p>If you want to check the balance, you can check it from the <code>balanceOf</code> menu. Just enter the wallet address and press the menu. The current token balance will be displayed there.</p>



<p>If you don’t see the token balance in the Metamask, move to the assets option In the Metamask and click on the <code>import tokens</code> option. Then paste the contract address from the Remix IDE, and the tokens will be automatically imported. </p>



<p>You will get the contract address from the deployed contracts section of the Remix IDE.</p>



<p>So, our simple, smart contract is ready. Now let&#8217;s build the front end to do transactions to other accounts.</p>



<h2 class="wp-block-heading">Create a React App and Tailwind CSS</h2>



<p>We will use <a href="https://blog.finxter.com/learn-to-build-smart-contracts-in-react-with-web3-js-heres-how-1-2/" data-type="post" data-id="978706" target="_blank" rel="noreferrer noopener">React</a> and Tailwind CSS to build our front end. So, create our react app first.</p>



<p>Open the command prompt from your directory. Then type</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">npx create-react-app silver_wallet</pre>



<p>Now the react is installed. But before initializing react, move to the installed directory and install the tailwind CSS for react.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">cd silver_wallet
npm install -D tailwindcss
npx tailwindcss init
</pre>



<p>Inside the <code>tailwind.config.js</code> file, configure the template paths</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">content: [
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
</pre>



<p>And inside the index.css file, add the tailwind directives.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@tailwind base;
@tailwind components;
@tailwind utilities;
</pre>



<p>Tailwind is installed.</p>



<p>Now initiate the React App.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">npm start</pre>



<p>The React app should be running on the browser in the port 3000.</p>



<p>Now move to the <code>app.js</code> file and clear it for writing the contracts.</p>



<h2 class="wp-block-heading">Connect to Metamask</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="908" height="617" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-301.png" alt="" class="wp-image-1149116" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-301.png 908w, https://blog.finxter.com/wp-content/uploads/2023/02/image-301-300x204.png 300w, https://blog.finxter.com/wp-content/uploads/2023/02/image-301-768x522.png 768w" sizes="auto, (max-width: 908px) 100vw, 908px" /></figure>
</div>


<p>The first thing we need to do is to establish a connection with the Metamask wallet.</p>



<p>Create a button and a container to show the account address to which we would be connected. The wallet&#8217;s address will be shown in the UI when connected to the wallet.</p>



<p>Let&#8217;s apply some styles also at the same time when we proceed. Get a nice button from the Flowbite website. Flowbite is one of the open-source UI libraries that will help us to build a front-end design faster.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;div>
      &lt;div className="text-center mt-10">
        &lt;button
          type="button"
          onClick={connectMetamask}
          className="text-white bg-gradient-to-r from-cyan-500 to-blue-500 hover:bg-gradient-to-bl focus:ring-4 focus:outline-none focus:ring-cyan-300 dark:focus:ring-cyan-800 font-medium rounded-lg text-sm px-5 py-2.5 text-center mr-2 mb-2"
        >
          Connect to Metamask
        &lt;/button>
{errorMessage}

      &lt;/div>
      &lt;div className="items-center mt-5 py-3 px-4 text-sm font-medium text-center text-white bg-sky-500 rounded-lg hover:bg-sky-500 focus:ring-4 focus:outline-none focus:ring-blue-300 w-1/2 m-auto">
        &lt;h3>Wallet Address: {activeAccount} &lt;/h3>
      &lt;/div>
      &lt;/div>
    &lt;/div>
</pre>



<p>Our button is visible in the UI, and we need to add some functionalities to the connectMetamask event handler to make it work.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const connectMetamask = async () => {
    try {
      if (window.ethereum) {
        await window.ethereum
          .request({ method: "eth_requestAccounts" })
          .then((result) => {
            setActiveAccount(result[0]);
          });
      } else {
        console.log("Need to install Metamask");
      }
    } catch (error) {
      console.log(error);
    }
  };
</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="450" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-296.png" alt="" class="wp-image-1149079" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-296.png 624w, https://blog.finxter.com/wp-content/uploads/2023/02/image-296-300x216.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<p>An &#8220;if-else&#8221; condition is introduced to confirm if the Metamask is injected into the browser.</p>



<p>Inside the if condition, the <code>eth_requestAccounts</code> method of the Ethereum library is used to request the accounts of the Metamask. From the results, we choose the <code>results[0]</code>, that is, the connected account of Metamask.</p>



<p>We need to declare a state variable outside the event handler to show our account address to the UI. A <code>useState</code> hook of React would be helpful here. Import <code>useState</code> from React.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import React, { useState } from "react";</pre>



<p>Now create a <a href="https://blog.finxter.com/state-variables-in-solidity/" data-type="post" data-id="765838" target="_blank" rel="noreferrer noopener">state variable</a> to store the value of the active account address.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const [activeAccount, setActiveAccount] = useState(null);</pre>



<p>Now set the <code>results[0]</code> as the active account.</p>



<p>If the event handler fails to connect to Metamask, It will throw an error message in the console.</p>



<p>Now if you run the code you must get the wallet address displayed on the User Interface.</p>



<p>At the same time, we need to show the token balance. Under the address section, we can create another <code>&lt;div&gt;</code> container to show the balance of that wallet address. Let&#8217;s do this.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;div className="items-center mt-5 py-3 px-4 text-sm font-medium text-center text-white bg-sky-500 rounded-lg hover:bg-sky-500 focus:ring-4 focus:outline-none focus:ring-blue-300 w-1/2 m-auto">
        &lt;h3>Token Balance: {tokenBalance} &lt;/h3>
      &lt;/div>
</pre>



<p>Create another state variable outside the function to show balance in the UI.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const [tokenBalance, setTokenBalance] = useState(null);</pre>



<p>Our <code>balance</code> state variable is ready, but we need to connect with the contract to fetch the balance from the wallet.</p>



<p>We get connected with the smart contract and transfer some balance into a specific account in the next part:</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/how-i-built-my-own-erc-20-token-2-2/" data-type="post" data-id="1151626" target="_blank" rel="noreferrer noopener">How I Built My Own ERC-20 Token (2/2)</a></p>



<p><strong>Github</strong>: <a rel="noreferrer noopener" href="https://github.com/finxter/silver_wallet" data-type="URL" data-id="https://github.com/finxter/silver_wallet" target="_blank">https://github.com/finxter/silver_wallet</a></p>
<p>The post <a href="https://blog.finxter.com/how-i-built-my-own-erc-20-token-1-2/">How I Built My Own ERC-20 Token (1/2)</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (4/4)</title>
		<link>https://blog.finxter.com/dapp-ebook-part-4/</link>
		
		<dc:creator><![CDATA[Yassin Mahmud Abdul Quddus]]></dc:creator>
		<pubDate>Sat, 14 Jan 2023 12:27:05 +0000</pubDate>
				<category><![CDATA[Crypto]]></category>
		<category><![CDATA[dApp]]></category>
		<category><![CDATA[Ethereum]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[Smart Contracts]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1056919</guid>

					<description><![CDATA[<p>We completed a transaction in the last part, but the transaction data had yet to be seen. In this part, we will drive the smart contract data to the user interface. The user&#8217;s data and the transaction time will be displayed on the user interface. This is part 4 of our four-tutorial series on creating ... <a title="I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (4/4)" class="read-more" href="https://blog.finxter.com/dapp-ebook-part-4/" aria-label="Read more about I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (4/4)">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/dapp-ebook-part-4/">I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (4/4)</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>We completed a transaction in the last part, but the transaction data had yet to be seen. In this part, we will drive the smart contract data to the user interface. The user&#8217;s data and the transaction time will be displayed on the user interface.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="I Created a React Decentralized App to Sell eBooks – Here’s How (4/4)" width="937" height="527" src="https://www.youtube.com/embed/pvqwI5sfl68?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>This is part 4 of our four-tutorial series on creating a decentralized web app to sell ebooks: <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<ul class="wp-block-list">
<li><strong>Part 1</strong>: <a href="https://blog.finxter.com/project-react-dapp-for-selling-ebooks-in-a-decentralized-manner-1-4/" data-type="post" data-id="1055370" target="_blank" rel="noreferrer noopener">I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (1/4)</a></li>



<li><strong>Part 2</strong>: <a href="https://blog.finxter.com/i-created-a-react-decentralized-app-to-sell-ebooks-heres-how-2-4/" data-type="post" data-id="1056760" target="_blank" rel="noreferrer noopener">I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (2/4)</a></li>



<li><strong>Part 3</strong>: <a href="https://blog.finxter.com/i-created-a-react-decentralized-app-to-sell-ebooks-heres-how-3-4/" data-type="post" data-id="1056859" target="_blank" rel="noreferrer noopener">I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (3/4)</a></li>



<li><strong>Part 4</strong>: <a href="https://blog.finxter.com/1056919-2/" data-type="post" data-id="1056919" target="_blank" rel="noreferrer noopener">I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (4/4)</a></li>
</ul>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="587" height="881" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-142.png" alt="" class="wp-image-1056968" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-142.png 587w, https://blog.finxter.com/wp-content/uploads/2023/01/image-142-200x300.png 200w" sizes="auto, (max-width: 587px) 100vw, 587px" /></figure>
</div>


<p>Move to the <code>Receipt</code> component and import the <code>ethers</code> library. Set the state that we created on the <code>app.js</code> file as props. Here again, we need to connect the smart contract with the frontend. So, destruct the contract from the state.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const Receipts = ({ state }) => {
  const { contract } = state;
  const [receipts, setReceipts] = useState([]);
  useEffect(() => {
    const receiptsInfo = async () => {
      const contractReceipts = await contract.getReceipts();
      setReceipts(contractReceipts);
    };
    contract &amp;&amp; receiptsInfo();
  }, [contract]);
  return (
    &lt;>
    &lt;/>
  );
};
export default Receipts;
</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="238" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-137.png" alt="" class="wp-image-1056926" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-137.png 624w, https://blog.finxter.com/wp-content/uploads/2023/01/image-137-300x114.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<p>Again we used the <code>useEffect()</code> hook of the react to write all our codes inside.</p>



<p>Inside the <code>useEffect()</code> hook, we created an async <code>receiptsInfo()</code> function to collect the information on the receipts. It is also an <code>async await</code> function. </p>



<p>You must remember we have created a receipts array in the smart contract to store all the transaction receipts together. At the same time, we also created a <code>getReceipts()</code> function inside the contract to fetch all the information regarding the transaction. Here, we created a receipts constant and called the <code>getReceipts</code> method from the contract instance.</p>



<p>To show the receipts info on the user interface, we created a receipts state variable with the help of <code>useState</code> hook. At last, we have set the receipts as the receipts we got from the contract.</p>



<p>We need to initiate the function. Otherwise, the code will not work. I initiated the contract and the <code>receiptsInfo()</code> function at the same time.</p>



<p>Ultimately, we add the contract as a dependency of the <code>useEffect()</code> hook. That means every time you bring some changes to the contract, the page will render again.</p>



<h2 class="wp-block-heading">Display Data on the Browser</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="683" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-106-1024x683.png" alt="" class="wp-image-1048723" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-106-1024x683.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/01/image-106-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2023/01/image-106-768x512.png 768w, https://blog.finxter.com/wp-content/uploads/2023/01/image-106.png 1190w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Now we have all the receipts in our hands. To show these receipts, we will map through the receipts and display them in a table format.</p>



<p>We need a table with five columns, so visit the flow bite website again. Why do you waste time doing the front end? If you like, you can use your CSS code, also. But for the fast demonstration, those ready-to-use codes are my favorites.</p>



<p>Now create a <code>&lt;h1></code> tag inside the return function for a heading that will remain on top of the table. “<strong>Recent Subscribers</strong>” is a good heading, I think.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">return (
    &lt;div className="py-10">
      &lt;h1 className="text-center text-2xl font-extrabold font-serif text-cyan-700">
        RECENT SUBSCRIBERS
      &lt;/h1>
      &lt;div className="relative overflow-x-auto shadow-md sm:rounded-lg w-3/4 m-auto mt-1">
        &lt;table className="w-full text-sm text-left text-gray-500 dark:text-gray-400">
          &lt;thead className="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400">
            &lt;tr>
              &lt;th scope="col" className="px-6 py-3">
                BUYER
              &lt;/th>
              &lt;th scope="col" className="px-6 py-3">
                BOOK
              &lt;/th>
              &lt;th scope="col" className="px-6 py-3">
                WRITER
              &lt;/th>
              &lt;th scope="col" className="px-6 py-3">
                ADDRESS
              &lt;/th>
              &lt;th scope="col" className="px-6 py-3">
                TIME
              &lt;/th>
            &lt;/tr>
          &lt;/thead>
          {receipts.map((receipt) => {
            return (
              &lt;tbody>
                &lt;tr className="bg-white border-b dark:bg-gray-900 dark:border-gray-700">
                  &lt;td className="px-6 py-4">{receipt.name}&lt;/td>
                  &lt;td className="px-6 py-4">{receipt.book}&lt;/td>
                  &lt;td className="px-6 py-4">{receipt.writer}&lt;/td>
                  &lt;td className="px-6 py-4">{receipt.buyer}&lt;/td>
                  &lt;td className="px-6 py-4">{String(receipt.timestamp)}&lt;/td>
                &lt;/tr>
              &lt;/tbody>
            );
          })}
        &lt;/table>
      &lt;/div>
    &lt;/div>
  );
};
</pre>



<p>Create a new <code>&lt;div></code> then. Inside the <code>&lt;div></code>, pass the code of the table structure that we copied from the flowbite website. </p>



<p>From the table structure, just keep a row of the table data and delete others. We will pass dynamic content on the table structure. So, the rows will be generated automatically. </p>



<p>If we start mapping through the receipt, the table header will be repeated with the dynamic code. So, we should map the receipts from where the table header is finished. But first, change the captions of the columns.</p>



<p>I changed the five columns&#8217; captions to buyer, book, writer, address, and time.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="376" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-138.png" alt="" class="wp-image-1056929" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-138.png 624w, https://blog.finxter.com/wp-content/uploads/2023/01/image-138-300x181.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<p>Now we can map through the receipts array. We will only map through the table body and insert each buyer&#8217;s info in each row.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="241" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-139.png" alt="" class="wp-image-1056930" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-139.png 624w, https://blog.finxter.com/wp-content/uploads/2023/01/image-139-300x116.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<ul class="wp-block-list">
<li>By mapping through the array, we are iterating over the receipts. Apart from this, we are getting the info on each receipt simultaneously.</li>



<li>We can access each receipt&#8217;s data now, and from the receipt, we can collect dynamic data like <code>receipt.name</code>, <code>receipt.book</code>, <code>receipt.writer</code>, <code>receipt.buyer</code> and <code>receipt.timestamp</code>. In the Solidity smart contract, we created a <a rel="noreferrer noopener" href="https://blog.finxter.com/solidity-complications-with-arrays-and-structs-and-order-of-evaluation/" data-type="post" data-id="979282" target="_blank">struct</a> for all those data. Now we are fetching the input data, the buyer&#8217;s account address, and the transaction timing from the contract.</li>



<li>Now insert these dynamic data on each of the table data tag (<code>&lt;td></code>) of the table row. When a new buyer subscribes, automatically, a new row for this buyer will be created on display.</li>



<li>The <code>recipt.timestamp</code> will return an object. To get the readable format convert it into a string.</li>
</ul>



<h2 class="wp-block-heading">Send Ethers from Buyer to Owner</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="682" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-143-1024x682.png" alt="" class="wp-image-1056970" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-143-1024x682.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/01/image-143-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2023/01/image-143-768x511.png 768w, https://blog.finxter.com/wp-content/uploads/2023/01/image-143.png 1113w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Now our dapp is ready. But for a long time, we have been using the same account for receiving and sending ethers.</p>



<p>Now let&#8217;s create a different account on the Goerli test net. You can easily do this from the <a rel="noreferrer noopener" href="https://blog.finxter.com/metamask-simple-tutorial/" data-type="post" data-id="38157" target="_blank">Metamask</a> wallet. Just move to &#8220;my accounts&#8221; section, and you will find create a new account option. Create a new account there. Then send some Goerli eth on your empty account from the Goerli faucet.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="356" height="436" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-140.png" alt="" class="wp-image-1056931" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-140.png 356w, https://blog.finxter.com/wp-content/uploads/2023/01/image-140-245x300.png 245w" sizes="auto, (max-width: 356px) 100vw, 356px" /></figure>
</div>


<p>Assume that the second account is the buyer, who will buy a subscription now. </p>



<p>The first address is obviously the bookstall owner, as we deployed the contract from the first address. Connect the second account with the browser. You can do this manually from the wallet. Now input the required information in the form and hit subscribe button. When the Metamask appears, confirm the transaction.</p>



<p>If your dapp is active, you should see the transaction confirmation notification after some time. You can check the transaction status on the Etherscan website by clicking on that notification. You will see the transaction details, including the receiver and sender addresses, from there.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="398" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-141.png" alt="" class="wp-image-1056932" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-141.png 624w, https://blog.finxter.com/wp-content/uploads/2023/01/image-141-300x191.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<p>My transaction details are here for you. You can see the amount that has been transferred along with the transaction fee. The sender and receiver addresses and the contract address are mentioned there.</p>



<p>You can confirm the transaction in another way. Just check the Metamask wallet of the buyer and the owner. You must see that the owner&#8217;s account is credited with 0.001 eth. The buyer&#8217;s account must be debited with the subscription and transaction fees. All the buyers will bear the cost of the transaction.</p>



<p>If you reload the browser, the last buyer&#8217;s data should be added to the table in a new row. Our bookstall project is accomplished if you get the correct data in the user interface.</p>



<p>You can check the video for the live demonstration of the transaction. I beautified the front end a little with the help of Tailwind CSS, and you can get the code from the GitHub link attached below.</p>



<h2 class="wp-block-heading">Thanks! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2665.png" alt="♥" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </h2>



<p>That was all for my bookstall dapp. You are always appreciated for creating new dapp by taking the ideal concept out of this. Thanks for reading.</p>



<p><strong>GitHub</strong>: <a rel="noreferrer noopener" href="https://github.com/finxter/bookSell" data-type="URL" data-id="https://github.com/finxter/bookSell" target="_blank">https://github.com/finxter/bookSell</a></p>



<p>Also, check out our academy courses on smart contract development such as this one:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><a href="https://academy.finxter.com/university/creating-a-dao-from-scratch-with-solidity-and-javascript/" target="_blank" rel="noopener"><img loading="lazy" decoding="async" width="363" height="650" src="https://blog.finxter.com/wp-content/uploads/2022/05/image-282.png" alt="" class="wp-image-387280" srcset="https://blog.finxter.com/wp-content/uploads/2022/05/image-282.png 363w, https://blog.finxter.com/wp-content/uploads/2022/05/image-282-168x300.png 168w" sizes="auto, (max-width: 363px) 100vw, 363px" /></a></figure></div>
<p>The post <a href="https://blog.finxter.com/dapp-ebook-part-4/">I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (4/4)</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>I Created a React Decentralized App to Sell eBooks – Here’s How (3/4)</title>
		<link>https://blog.finxter.com/i-created-a-react-decentralized-app-to-sell-ebooks-heres-how-3-4/</link>
		
		<dc:creator><![CDATA[Yassin Mahmud Abdul Quddus]]></dc:creator>
		<pubDate>Sat, 14 Jan 2023 11:30:42 +0000</pubDate>
				<category><![CDATA[dApp]]></category>
		<category><![CDATA[Ethereum]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[React]]></category>
		<category><![CDATA[Smart Contracts]]></category>
		<category><![CDATA[Solidity]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1056859</guid>

					<description><![CDATA[<p>This is part 3 of our four-tutorial series on creating a decentralized web app to sell ebooks: 👇 We will connect the front end with the smart contract in this part of the series. The interaction with the smart contract will be done using ether.js. Move to the app.js file inside the source folder. We ... <a title="I Created a React Decentralized App to Sell eBooks – Here’s How (3/4)" class="read-more" href="https://blog.finxter.com/i-created-a-react-decentralized-app-to-sell-ebooks-heres-how-3-4/" aria-label="Read more about I Created a React Decentralized App to Sell eBooks – Here’s How (3/4)">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/i-created-a-react-decentralized-app-to-sell-ebooks-heres-how-3-4/">I Created a React Decentralized App to Sell eBooks – Here’s How (3/4)</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>This is part 3 of our four-tutorial series on creating a decentralized web app to sell ebooks: <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<ul class="wp-block-list">
<li><strong>Part 1</strong>: <a href="https://blog.finxter.com/project-react-dapp-for-selling-ebooks-in-a-decentralized-manner-1-4/" data-type="post" data-id="1055370" target="_blank" rel="noreferrer noopener">I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (1/4)</a></li>



<li><strong>Part 2</strong>: <a href="https://blog.finxter.com/i-created-a-react-decentralized-app-to-sell-ebooks-heres-how-2-4/" data-type="post" data-id="1056760" target="_blank" rel="noreferrer noopener">I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (2/4)</a></li>



<li><strong>Part 3</strong>: <a href="https://blog.finxter.com/i-created-a-react-decentralized-app-to-sell-ebooks-heres-how-3-4/" data-type="post" data-id="1056859" target="_blank" rel="noreferrer noopener">I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (3/4)</a></li>



<li><strong>Part 4</strong>: <a href="https://blog.finxter.com/1056919-2/" data-type="post" data-id="1056919" target="_blank" rel="noreferrer noopener">I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (4/4)</a></li>
</ul>



<p>We will connect the front end with the smart contract in this part of the <a href="https://blog.finxter.com/project-react-dapp-for-selling-ebooks-in-a-decentralized-manner-1-4/" data-type="post" data-id="1055370" target="_blank" rel="noreferrer noopener">series</a>. The interaction with the smart contract will be done using <code>ether.js</code>.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="I Created a React Decentralized App to Sell eBooks – Here’s How (3/4)" width="937" height="527" src="https://www.youtube.com/embed/Mrgxwj-Lbh4?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>Move to the <code>app.js</code> file inside the source folder. We need to import the <code>ethers</code> library and the ABI of the <a href="https://blog.finxter.com/top-solidity-smart-contract-examples-for-learning/" data-type="post" data-id="663675" target="_blank" rel="noreferrer noopener">smart contract</a>. </p>



<p>This ABI or Application Binary Interface is nothing but the JSON format of the smart contract. This JSON format will allow us to talk to the smart contract from the front end. By using this ABI, we can call all the functions of the smart contract we have created. </p>



<p>Whenever you deploy the smart contract, a JSON format of the contract should have been created inside the artifacts folder. Just move to the artifacts folder, copy the file and paste it inside the source folder. </p>



<p>Now, React will be able to locate the directory of the smart contract. If the JSON file stays outside the source folder, it will not be accessible.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import Heading from "./components/Heading";
import abi from ".BookSell.json";
import { ethers } from "ethers"; 
import { useEffect, useState } from "react";
</pre>



<p>We will use the provider, signer, and contract variables regularly on the React <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-sell-coupons-on-eth-a-sample-solidity-dapp-with-react-and-truffle-1-4/" data-type="post" data-id="952551" target="_blank">dapp</a>. That’s why it is better to store all these as an object inside a state variable. It will refrain us from creating those variables individually on the code, meanwhile saving our time. </p>



<p>We will use the <code>useState()</code> hook of React to implement this.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">  const [state, setState] = useState({
    provider: null,
    signer: null,
    contract: null,
  });
</pre>



<p>We have created an object inside the <code>useState()</code> hook. This object takes the provider, signer, and the contract as keys. I am keeping the initial values for all the variables null.</p>



<p>To initialize all these variables, we will use the <code>useEffect()</code> hook of the React. Inside this <code>useEffect()</code> hook, first, we will create a <code>connectMetamask()</code> function to establish a connection with the <a href="https://blog.finxter.com/metamask-simple-tutorial/" data-type="post" data-id="38157" target="_blank" rel="noreferrer noopener">Metamask</a>. </p>



<p>But try to fetch the contract address and the contract ABI first. If you forget the contract address, move to the Etherscan website and insert the Goerli account address, you will get the contract address info in the latest transaction section.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const contractAddress = "0xede6825532dc2f6a8ac5b8dfc6874e80ae872dd4";
const contractABI = abi.abi;
</pre>



<p>Let&#8217;s create a try-catch method that will throw an error if the Metamask is not connected to the browser. Inside the try method, create a constant for the <a href="https://blog.finxter.com/ethereum-top-10-articles-to-get-started/" data-type="post" data-id="53284" target="_blank" rel="noreferrer noopener">Ethereum</a> object. You can consider the window as the Metamask. This Metamask injects an object called Ethereum into the browser that helps the browser interact with the blockchain.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const { ethereum } = window;</pre>



<p>Now create an if else condition to check if the Metamask browser is detected. If the Metamask browser is injected, then it will ask for the account from Metamask. Otherwise, it will throw an error.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">useEffect(() => {
    const connectMetamask = async () => {
      const contractAddress = "0xede6825532dc2f6a8ac5b8dfc6874e80ae872dd4";
      const contractABI = abi.abi;
      try {
        const { ethereum } = window;
        if (ethereum) {
          const account = await ethereum.request({
            method: "eth_requestAccounts",
          });

          const provider = new ethers.providers.Web3Provider(ethereum);
          const signer = provider.getSigner();
          const contract = new ethers.Contract(
            contractAddress,
            contractABI,
            signer
          );
          setState({ provider, signer, contract });
        } else {
          alert("Please install metamask");
        }
      } catch (error) {
        console.log(error);
      }
    };
    connectMetamask();
  }, []);
</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="415" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-130.png" alt="" class="wp-image-1056865" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-130.png 624w, https://blog.finxter.com/wp-content/uploads/2023/01/image-130-300x200.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<p>Inside the if condition, &#8220;<code>eth_requestAccounts</code> method&#8221; of the Ethereum library is used to request the account from the Metamask wallet.</p>



<p>We defined the provider with the help of the <code>Web3Provider</code> method of the <code>ethers</code> library. In our case, the provider would be Metamask.</p>



<p>We are committing a transaction, and for that, we must need a signer. We called the signer by using the <code>getSigner()</code> method of the provider.</p>



<p>Then we created an instance of our smart contract <code>Contract()</code> method of the library. This <code>contract()</code> method takes the Contract address, ABI and the signer as the parameters.</p>



<p>Now the provider, signer and contract are defined. So, we need to change the state of these three that we have defined as null earlier. With the help of <code>setState()</code>, we applied the changes.</p>



<p>If Metamask is not installed in the browser, then the else condition will show an alert, “<strong>Please install Metamask</strong>”, on the browser.</p>



<p>Our <code>connectMetamask()</code> function is ready. In the last line, we called the function to be activated.</p>



<p>Now let&#8217;s <code><a href="https://blog.finxter.com/javascript-intro-how-to-see-your-code-output/" data-type="post" data-id="175068" target="_blank" rel="noreferrer noopener">console.log</a></code> the state to check if all the changes occur and the Metamask is connected to the browser.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">console.log(state);</pre>



<p>Now reload the React web page. If everything works well, you should get the provider, signer, and the contract on the console.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="557" height="328" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-131.png" alt="" class="wp-image-1056866" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-131.png 557w, https://blog.finxter.com/wp-content/uploads/2023/01/image-131-300x177.png 300w" sizes="auto, (max-width: 557px) 100vw, 557px" /></figure>
</div>


<p>As you can see in my console, the state of the provider, signer, and contract was initially null. But now it returns the injected <code>web3Provider</code> as the provider, and our contract and signer state is also changed.</p>



<h2 class="wp-block-heading">Create Components</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="682" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-136-1024x682.png" alt="" class="wp-image-1056914" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-136-1024x682.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/01/image-136-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2023/01/image-136-768x511.png 768w, https://blog.finxter.com/wp-content/uploads/2023/01/image-136.png 1113w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Now we will create two functional components to write the codes for buying the book and fetching the receipts. </p>



<p>Create two components called <code>Book.js</code> and <code>Receipt.js</code>. Import react on those files and just type <code>rsc</code>. A component structure will be created automatically. If it doesn&#8217;t, then you can create the structure manually. Not a big deal.</p>



<p>We need to call the <a rel="noreferrer noopener" href="https://blog.finxter.com/learn-to-build-smart-contracts-in-react-with-web3-js-heres-how-1-2/" data-type="post" data-id="978706" target="_blank">smart contract</a> instance for the interaction. In the <code>app.js</code> file, we already created a state by which we can access the provider, signer, and contract instance. We will pass the state props from the <code>app.js</code>.</p>



<p>Inside the return function of the <code>app.js</code>, create a <code>&lt;div&gt;</code> and initiate the <code>Book</code> and <code>Receipt</code> components. Pass the state as props so we can access the state from the components file. Don&#8217;t forget to import the components in the <code>app.js</code> file.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">return (
    &lt;div className="bg-black min-h-full">
      &lt;Heading>&lt;/Heading>
      &lt;Book state={state}>&lt;/Book>
      &lt;Receipt state={state}>&lt;/Receipt>
    &lt;/div>
  );
</pre>



<p>Now move to the <code>Book</code> component. Pass the state props inside the fat arrow function. We need to create a form to collect the data of the buyers. The buyer will input the required data on that form and then submit it. I will use the flowbite website again to get some ready-made tailwind form components.</p>



<p>We need to customize the form that we are bringing from the website. We need to create three text input fields for the buyer&#8217;s name, the book name and the writer&#8217;s name. You can add some placeholder to make it looks nice. At the bottom, we need a submit button to submit the information. That is our simple form.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="369" height="378" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-132.png" alt="" class="wp-image-1056870" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-132.png 369w, https://blog.finxter.com/wp-content/uploads/2023/01/image-132-293x300.png 293w" sizes="auto, (max-width: 369px) 100vw, 369px" /></figure>
</div>


<p>Create a <code>formData()</code> function that will be triggered when the form is submitted. We have created an <code>onSubmit</code> event handler on the form already.</p>



<p>Inside the <code>formData()</code> function, We need to destructor the contract instance from the state props so that we can call the different functions of the smart contract.</p>



<p>Now we want to collect the data from the form. To do that, we need to access the DOM elements. </p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Info</strong>: DOM elements are the individual parts of a web page, such as text, images, and videos, that are represented as objects in a web browser&#8217;s Document Object Model (DOM). These objects can be manipulated by <a href="https://blog.finxter.com/javascript-developer-income-and-opportunity/" data-type="post" data-id="191233" target="_blank" rel="noreferrer noopener">JavaScript</a> to dynamically change the web page&#8217;s content, structure, and styling.</p>



<p>We can access DOM elements using the <code>document.queryselector()</code> method of JavaScript. But we should take advantage of React by using the <code><a href="https://www.w3schools.com/react/react_useref.asp" data-type="URL" data-id="https://www.w3schools.com/react/react_useref.asp" target="_blank" rel="noreferrer noopener">useRef()</a></code> hook. With the help of <code>useRef()</code> hook, we can access the particular data of the input field.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import { ethers } from "ethers";
import React, { useRef } from "react";

const Book = ({ state }) => {
  const form = useRef();
  const formData = async (event) => {
    event.preventDefault();
    const { contract } = state;
    const name = form.current.name.value;
    const book = form.current.book.value;
    const writer = form.current.writer.value;
    const amount = { value: ethers.utils.parseEther("0.001") };
    const transaction = await contract.buyBook(name, book, writer, amount);
    await transaction.wait();
    event.target.reset();
  };
  return (
    &lt;div className="mt-10">
      &lt;h1 className="text-center text-3xl font-extrabold font-serif text-red-400 pb-2">
        SUBSCRIBE HERE
      &lt;/h1>
      &lt;form
        onSubmit={formData}
        ref={form}
        className="w-1/4 bg-slate-800 p-5 m-auto border rounded-xl"
      >
        &lt;div className="mb-6">
          &lt;label className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">
            Your Name
          &lt;/label>
          &lt;input
            type="text"
            name="name"
            className="bg-gray-500 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
            placeholder="Enter your name"
            required
          />
        &lt;/div>
        &lt;div className="mb-6">
          &lt;label className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">
            Book Name
          &lt;/label>
          &lt;input
            type="text"
            name="book"
            className="bg-gray-500 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
            placeholder="Enter The book's name"
            required
          />
        &lt;/div>
        &lt;div className="mb-6">
          &lt;label className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">
            Writer Name
          &lt;/label>
          &lt;input
            type="text"
            name="writer"
            className="bg-gray-500 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
            placeholder="Enter the writer's name"
            required
          />
        &lt;/div>

        &lt;div className="flex items-center justify-center">
          &lt;button
            type="submit"
            className="text-white bg-red-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm w-full sm:w-auto px-5 py-2.5 text-center dark:bg-red-700 dark:hover:bg-blue-700 dark:focus:ring-blue-800"
          >
            Subscribe
          &lt;/button>
        &lt;/div>
      &lt;/form>
    &lt;/div>
  );
};
</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="380" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-133.png" alt="" class="wp-image-1056871" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-133.png 624w, https://blog.finxter.com/wp-content/uploads/2023/01/image-133-300x183.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<p>I created a <code>ref</code> attribute for the form inside the return function, i.e., (<code>ref = {form}</code>). We also added a <code>name</code> attribute on each of the input fields. Using the <code>name</code> attribute, we can access each property&#8217;s input value with the help of <code>useRef()</code>.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="109" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-134.png" alt="" class="wp-image-1056873" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-134.png 624w, https://blog.finxter.com/wp-content/uploads/2023/01/image-134-300x52.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<p>Form data is an <code>async await</code> function that triggers an event. <code>Event.preventDefault()</code> is used to prevent the unnecessary loading of the data.</p>



<p>We need to get the current properties of the input fields. That’s why we used “<code>form.current</code>” method to access the current input value of each input field.</p>



<p>We <code>console.log</code> the name, book, writer and contract just to check if our code is working.</p>



<p>Now we will access the <code>buyBook</code> function of the smart contract. If you can <a rel="noreferrer noopener" href="https://blog.finxter.com/project-react-dapp-for-selling-ebooks-in-a-decentralized-manner-1-4/" data-type="post" data-id="1055370" target="_blank">remember</a>, we have already created a <code>buyBook</code> function for the transaction purpose. The <code>buyBook()</code> function will take the name, book, writer and amount as parameters. The first three are already defined inside the <code>formData()</code> function; we need to define the amount here.</p>



<p>We used the <code>utils</code> module of the <code>ethers</code> library to fix the transaction amount as 0.001 ETH.</p>



<p>We need to wait for some time for the transaction to take place. If the transaction is completed, &#8220;transaction is done&#8221; will be shown on the console.</p>



<p>Now move to the browser and refresh the page. Enter the buyer&#8217;s name, book and writer&#8217;s name in the input field. Then click on the <code>buy</code> button. </p>



<p>Metamask will pop up, asking for the confirmation of the transaction. Confirm the transaction and wait for some time. A transaction-confirmed notification will pop up after a while. In the console, you should get &#8220;transaction is done&#8221; written. </p>



<p>You can confirm the transaction by checking it on the Etherscan website. Just insert the Metamask account address of the Goerli wallet, and the transaction details will be displayed there.</p>



<h2 class="wp-block-heading">Thanks for Reading &#8212; Keep it Up! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /></h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="683" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-135-1024x683.png" alt="" class="wp-image-1056911" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-135-1024x683.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/01/image-135-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2023/01/image-135-768x512.png 768w, https://blog.finxter.com/wp-content/uploads/2023/01/image-135.png 1113w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>That&#8217;s all for today. In the next part, we will try to bring the buyer&#8217;s info in to the user interface. Hope this will be interesting.</p>



<p><strong>GitHub</strong>: <a rel="noreferrer noopener" href="https://github.com/finxter/bookSell" data-type="URL" data-id="https://github.com/finxter/bookSell" target="_blank">https://github.com/finxter/bookSell</a></p>
<p>The post <a href="https://blog.finxter.com/i-created-a-react-decentralized-app-to-sell-ebooks-heres-how-3-4/">I Created a React Decentralized App to Sell eBooks – Here’s How (3/4)</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (2/4)</title>
		<link>https://blog.finxter.com/i-created-a-react-decentralized-app-to-sell-ebooks-heres-how-2-4/</link>
		
		<dc:creator><![CDATA[Yassin Mahmud Abdul Quddus]]></dc:creator>
		<pubDate>Sat, 14 Jan 2023 10:11:17 +0000</pubDate>
				<category><![CDATA[dApp]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[React]]></category>
		<category><![CDATA[Smart Contracts]]></category>
		<category><![CDATA[Solidity]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1056760</guid>

					<description><![CDATA[<p>This is part 2 of our four-tutorial series on creating a decentralized web app to sell ebooks: 👇 In the previous part, we built the smart contract and deployed it on the hardhat node for testing. Now it’s time to deploy the contract on the testnet. But before that, let&#8217;s install the react app first. ... <a title="I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (2/4)" class="read-more" href="https://blog.finxter.com/i-created-a-react-decentralized-app-to-sell-ebooks-heres-how-2-4/" aria-label="Read more about I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (2/4)">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/i-created-a-react-decentralized-app-to-sell-ebooks-heres-how-2-4/">I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (2/4)</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>This is part 2 of our four-tutorial series on creating a decentralized web app to sell ebooks: <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<ul class="wp-block-list">
<li><strong>Part 1</strong>: <a href="https://blog.finxter.com/project-react-dapp-for-selling-ebooks-in-a-decentralized-manner-1-4/" data-type="post" data-id="1055370" target="_blank" rel="noreferrer noopener">I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (1/4)</a></li>



<li><strong>Part 2</strong>: <a href="https://blog.finxter.com/i-created-a-react-decentralized-app-to-sell-ebooks-heres-how-2-4/" data-type="post" data-id="1056760" target="_blank" rel="noreferrer noopener">I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (2/4)</a></li>



<li><strong>Part 3</strong>: <a href="https://blog.finxter.com/i-created-a-react-decentralized-app-to-sell-ebooks-heres-how-3-4/" data-type="post" data-id="1056859" target="_blank" rel="noreferrer noopener">I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (3/4)</a></li>



<li><strong>Part 4</strong>: <a href="https://blog.finxter.com/1056919-2/" data-type="post" data-id="1056919" target="_blank" rel="noreferrer noopener">I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (4/4)</a></li>
</ul>



<p>In the <a href="https://blog.finxter.com/project-react-dapp-for-selling-ebooks-in-a-decentralized-manner-1-4/" data-type="post" data-id="1055370" target="_blank" rel="noreferrer noopener">previous part</a>, we built the smart contract and deployed it on the hardhat node for testing. </p>



<p>Now it’s time to deploy the contract on the testnet. </p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="I Created a React Decentralized App to Sell eBooks – Here’s How (2/4)" width="937" height="527" src="https://www.youtube.com/embed/WjduVcdMjo8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>But before that, let&#8217;s install the react app first. Open the command prompt from your directory. Then type</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">npx create-react-app frontend</pre>



<p>Now, the React framework is installed. But before initializing react, move to the installed directory and install the tailwind CSS for react.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">cd frontend
npm install -D tailwindcss
npx tailwindcss init</pre>



<p>Inside the <code>tailwind.config.js</code> file, configure the template paths</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">content: [
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
</pre>



<p>And inside the <code>index.css</code> file add the tailwind directives.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@tailwind base;
@tailwind components;
@tailwind utilities;</pre>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Info</strong>: Tailwind directives are CSS classes generated by Tailwind CSS that add custom styles to your web projects quickly and easily. With their help, you can create custom design systems with minimal effort while still being able to customize the look and feel of your website. Tailwind directives are incredibly flexible and customizable, so you can use them to create complex and unique designs.</p>



<p>Now initiate the React.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">npm start</pre>



<p>The react app should be running on the browser in the <code>port:3000</code>.</p>



<p>Now it’s time to <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-sell-coupons-on-eth-build-deploy-and-test-the-smart-contract-2-4/" data-type="post" data-id="952575" target="_blank">deploy</a> the contract. <a rel="noreferrer noopener" href="https://blog.finxter.com/project-react-dapp-for-selling-ebooks-in-a-decentralized-manner-1-4/" data-type="post" data-id="1055370" target="_blank">Earlier</a>, we deployed the contract on the hardhat blockchain node, but this time we will deploy it to the testnet. </p>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Info</strong>: We will use the famous <strong>Goerli</strong> testnet for the deployment. Goerli is a cross-client Ethereum testnet designed for developers, service providers, and users. It is an alternative to <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-deploy-a-smart-contract-to-the-ropsten-testnet-in-brownie/" data-type="post" data-id="63341" target="_blank">Ropsten</a>, featuring <em>Clique Proof of Authority</em> as its <a href="https://blog.finxter.com/common-consensus-mechanisms-in-blockchains/" data-type="post" data-id="70966" target="_blank" rel="noreferrer noopener">consensus mechanism</a> for faster block times and greater reliability. Goerli is composed of nodes from Geth, Parity, Nethermind, and Besu, offering greater security and more options for developers.</p>



<p>Create a new javascript file, &#8220;<code>goerliDeploy</code>&#8220;, inside the script folder to deploy the contract on the test net.</p>



<h2 class="wp-block-heading">Connect Hardhat with Goerli Testnet</h2>



<p>We did not install our <code>dotenv</code> file yet. So, let’s install it first.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">npm install dotenv</pre>



<p>Now create a <code>.env</code> file in the <code>bookSell</code> folder. Inside the <code>dotenv</code> file, we will secure the Goerli URL, Goerli API key, and the private key that will be acquired from the <a href="https://blog.finxter.com/metamask-simple-tutorial/" data-type="post" data-id="38157" target="_blank" rel="noreferrer noopener">Metamask wallet</a>. You must have known the importance of the <code>dotenv</code> file. </p>



<p>When we deploy the code on <a href="https://github.com/finxter/bookSell" data-type="URL" data-id="https://github.com/finxter/bookSell" target="_blank" rel="noreferrer noopener">GitHub</a>, this <code>dotenv</code> file will remain in the local directory, thus making it difficult for hackers to infiltrate the private keys.</p>



<p>To connect the hardhat with the goerli test net, we need to bring some changes on the hardhat.config.js file.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">require("@nomicfoundation/hardhat-toolbox");
require("dotenv").config();
const GOERLI_URL = process.env.GOERLI_URL;
const PRIVATE_KEY = process.env.PRIVATE_KEY;
/** @type import('hardhat/config').HardhatUserConfig */
module.exports = {
  solidity: "0.8.17",
  networks: {
    goerli: {
      URL: GOERLI_URL,
      accounts: [PRIVATE_KEY],
    },
  },
};
</pre>



<p>We imported a <code>dotenv</code> file to keep the private key and the Goerli testnet URL safe.</p>



<p>This private key is the account&#8217;s private key that will bear the transaction cost for deploying the smart contract on the blockchain.</p>



<p>Inside the &#8220;<code>module.exports</code>&#8221; you need to mention the network you are using. Since we are using the Goerli testnet, we mentioned the Goerli URL and the account we are using. You need to input the private key of your account; the system will fetch the account you belong to on the Goerli test net.</p>



<p>Now, where will you get this info? You will get those from the test net. You can connect to a Goerli test net via an Infura node or <a href="https://www.alchemy.com/" data-type="URL" data-id="https://www.alchemy.com/" target="_blank" rel="noreferrer noopener">alchemy</a>. </p>



<p>In my <a rel="noreferrer noopener" href="https://blog.finxter.com/project-react-dapp-for-selling-ebooks-in-a-decentralized-manner-1-4/" data-type="post" data-id="1055370" target="_blank">other videos in this series</a>, I have shown how you can connect with the Goerli blockchain. Today we will try to connect to goerli test net via alchemy.</p>



<p>After signing in to alchemy, you will reach a dashboard. Click on the &#8220;Create app&#8221; option on the dashboard. A form will appear.</p>



<p>You need to feel it up with Ethereum as a chain and Goerli as the network. You can give it any name you want. Click on the <code>create app</code> button. Your app will be created.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="462" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-125.png" alt="" class="wp-image-1056794" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-125.png 624w, https://blog.finxter.com/wp-content/uploads/2023/01/image-125-300x222.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<p>Now the app is created, and you click on the <code>view key</code> option. You will get the API key and the URL of the goerli testnet. Just copy and paste this on the <code>dotenv</code> file. As we all know, the keys will be secured inside the <a rel="noreferrer noopener" href="https://blog.finxter.com/witness-the-magic-of-python-ai-written-and-illustrated-storybooks-for-children/" data-type="post" data-id="973429" target="_blank">dotenv</a> file because this file won&#8217;t be sent to GitHub with the other codes.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="348" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-126.png" alt="" class="wp-image-1056795" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-126.png 624w, https://blog.finxter.com/wp-content/uploads/2023/01/image-126-300x167.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<p>To collect the private key, we need to go to the Metamask extension. You must be connected to the Goerli testnet.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="462" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-127.png" alt="" class="wp-image-1056796" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-127.png 624w, https://blog.finxter.com/wp-content/uploads/2023/01/image-127-300x222.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<p>If you are not, move to the <code>add network</code> option and add Goerli as a test network. In the Metamask, click on the <code>add network</code> option and move to the networks option. From the networks, select the Goerli testnet to add to your network.</p>



<p>If you want to recharge your Goerli account with some free test <a rel="noreferrer noopener" href="https://blog.finxter.com/introduction-to-ethereums-gas-in-solidity-development/" data-type="post" data-id="37644" target="_blank">ETH</a>, move to the <a rel="noreferrer noopener" href="https://goerlifaucet.com/" data-type="URL" data-id="https://goerlifaucet.com/" target="_blank">Goerli faucet website</a> and insert your Metamask wallet address. You can collect 0.2 fake ETH per day from the Goerli wallet for testing purposes.</p>



<p>In the Metamask wallet, just beside the account name, click on the three vertical dots and go for the account details. You will get the option to export the private key. Copy the key and paste it to the dotenv file.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="348" height="460" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-128.png" alt="" class="wp-image-1056797" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-128.png 348w, https://blog.finxter.com/wp-content/uploads/2023/01/image-128-227x300.png 227w" sizes="auto, (max-width: 348px) 100vw, 348px" /></figure>
</div>


<p>All the requirements are fulfilled. Move to the <code>goerliDeploy.js</code> file.</p>



<p>Create an instance of the contract as we did earlier on the <code>deploy.js</code> file. Write the code to deploy the contract. To make sure the contract is deployed, ask for the contract address. Just &#8220;<code>console.log</code>&#8221; the <a href="https://blog.finxter.com/data-types-in-solidity-smart-contract-part-21-contract-types-fixed-size-byte-arrays-dynamically-sized-byte-arrays-address-literals-rational-and-integer-literals/" data-type="post" data-id="753297" target="_blank" rel="noreferrer noopener">contract address</a> after the deployment.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const hre = require("hardhat");
async function main() {
  const bookSell = await hre.ethers.getContractFactory("BookSell");
  const contract = await bookSell.deploy();
  await contract.deployed();
  console.log("Contract Address:", contract.address);
}

// We recommend this pattern to be able to use async/await everywhere
// and properly handle errors.
main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
</pre>



<p>Finally, it’s time to deploy the contract on the goerli test net. In the terminal type:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">npx hardhat run -–network goerli scripts/goerliDeploy.js</pre>



<p>Remember to mention the directory of the file you want to deploy. You would get the contract address as a return if the smart contract was deployed.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="91" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-129.png" alt="" class="wp-image-1056798" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-129.png 624w, https://blog.finxter.com/wp-content/uploads/2023/01/image-129-300x44.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<p>In my terminal, I got this contract address. Copy the address and move to the Etherscan website to check if the contract is really deployed. You will get the details of the transaction hash and the deployment time on the website.</p>



<p>We need to copy the contract address and save it somewhere. We will require this address after some time when we call the smart contract from the front end.</p>



<h2 class="wp-block-heading">Create Functional Components in React</h2>



<p>We have initialized react but have not done anything yet. Let’s create a components folder inside the source folder. </p>



<p>Create a <code>heading.js</code> file for making a simple heading component. Get inside the folder and press “RSC&#8221; on the keyboard. A functional component structure will be ready. If you don&#8217;t have the required plug-in installed, then there is no need to worry. You can make it manually.</p>



<p>I will not waste much time on the front end as this is not our main focus. </p>



<p>Instead, we will import some ready-to-use templates from the <a rel="noreferrer noopener" href="https://flowbite.com/" data-type="URL" data-id="https://flowbite.com/" target="_blank">flowbite website</a>. Move to the flowbite and collect a colorful heading that you love. Then customize the code in your own way. If you like, you can build on my own code.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const Heading = () => {
  return (
    &lt;div className="text-center pt-5">
      &lt;h1 className="mb-4 mt-4 text-3xl font-extrabold text-gray-900 dark:text-white md:text-5xl lg:text-6xl">
        &lt;span className="text-transparent bg-clip-text bg-gradient-to-r to-emerald-600 from-sky-400 font-serif">
          BOOK STALL
        &lt;/span>
      &lt;/h1>
      &lt;p className="font-serif font-bold text-gray-500 lg:text-3xl dark:text-cyan-600">
        FOR THE BOOK LOVERS TO READ YOUR FAVORITE BOOKS.
      &lt;/p>
      &lt;p className="font-serif font-bold text-gray-500 lg:text-3xl dark:text-cyan-600">
        THE BEST BOOK SUBSCRIPTION SERVICE IS HERE.
      &lt;/p>
    &lt;/div>
  );
};
</pre>



<p>Here I have introduced a heading and then written a couple of lines. Then just did a little edit. You are always welcome to make your custom code.</p>



<p>That&#8217;s all for today. In the next part, we will start interacting with the smart contract with the help of <code>ether.js</code>. Hope that will be an interesting one.</p>



<p><strong>GitHub</strong>: <a rel="noreferrer noopener" href="https://github.com/finxter/bookSell" target="_blank">https://github.com/finxter/bookSell</a></p>
<p>The post <a href="https://blog.finxter.com/i-created-a-react-decentralized-app-to-sell-ebooks-heres-how-2-4/">I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (2/4)</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (1/4)</title>
		<link>https://blog.finxter.com/project-react-dapp-for-selling-ebooks-in-a-decentralized-manner-1-4/</link>
		
		<dc:creator><![CDATA[Yassin Mahmud Abdul Quddus]]></dc:creator>
		<pubDate>Fri, 13 Jan 2023 19:44:07 +0000</pubDate>
				<category><![CDATA[dApp]]></category>
		<category><![CDATA[Ethereum]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[React]]></category>
		<category><![CDATA[Smart Contracts]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1055370</guid>

					<description><![CDATA[<p>Welcome to another project of a decentralized dapp with React and ether.js. This is part 1 of our four-tutorial series on creating a decentralized web app to sell ebooks: 👇 Project Scenario We will build an ebook stall from which anyone can buy an ebook on a monthly subscription basis. The buyer will submit his ... <a title="I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (1/4)" class="read-more" href="https://blog.finxter.com/project-react-dapp-for-selling-ebooks-in-a-decentralized-manner-1-4/" aria-label="Read more about I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (1/4)">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/project-react-dapp-for-selling-ebooks-in-a-decentralized-manner-1-4/">I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (1/4)</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Welcome to another project of a decentralized dapp with <a href="https://blog.finxter.com/learn-to-build-smart-contracts-in-react-with-web3-js-heres-how-1-2/" data-type="post" data-id="978706" target="_blank" rel="noreferrer noopener">React</a> and <code><a href="https://blog.finxter.com/i-created-a-counter-smart-contract-with-ether-js-heres-how/" data-type="post" data-id="1002304" target="_blank" rel="noreferrer noopener">ether.js</a></code>.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Project - React dApp for Selling eBooks in a Decentralized Manner (1/4)" width="937" height="527" src="https://www.youtube.com/embed/k9FWq9hTYiA?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>This is part 1 of our four-tutorial series on creating a decentralized web app to sell ebooks: <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<ul class="wp-block-list">
<li><strong>Part 1</strong>: <a href="https://blog.finxter.com/project-react-dapp-for-selling-ebooks-in-a-decentralized-manner-1-4/" data-type="post" data-id="1055370" target="_blank" rel="noreferrer noopener">I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (1/4)</a></li>



<li><strong>Part 2</strong>: <a href="https://blog.finxter.com/i-created-a-react-decentralized-app-to-sell-ebooks-heres-how-2-4/" data-type="post" data-id="1056760" target="_blank" rel="noreferrer noopener">I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (2/4)</a></li>



<li><strong>Part 3</strong>: <a href="https://blog.finxter.com/i-created-a-react-decentralized-app-to-sell-ebooks-heres-how-3-4/" data-type="post" data-id="1056859" target="_blank" rel="noreferrer noopener">I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (3/4)</a></li>



<li><strong>Part 4</strong>: <a href="https://blog.finxter.com/1056919-2/" data-type="post" data-id="1056919" target="_blank" rel="noreferrer noopener">I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (4/4)</a></li>
</ul>



<h2 class="wp-block-heading">Project Scenario</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1019" height="679" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-122.png" alt="" class="wp-image-1055400" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-122.png 1019w, https://blog.finxter.com/wp-content/uploads/2023/01/image-122-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2023/01/image-122-768x512.png 768w" sizes="auto, (max-width: 1019px) 100vw, 1019px" /></figure>
</div>


<p>We will build an ebook stall from which anyone can buy an ebook on a monthly subscription basis. </p>



<p>The buyer will submit his name, the book&#8217;s name, and the writer&#8217;s name at the time of buying the subscription. When he pays for the subscription, the subscription fee will be added to the bookstall owner&#8217;s account, and at the same time, the system will debit the transaction fee from the buyer&#8217;s account. </p>



<p>Apart from this, the details info of the buyer will be displayed on the user interface. The information includes the buyer&#8217;s name, wallet address, transaction time, book, and writer&#8217;s name.</p>



<h2 class="wp-block-heading">Technology</h2>



<p>We will use <code>react.js</code> and tailwind CSS in the frontend, <a href="https://blog.finxter.com/solidity-crash-course/" data-type="post" data-id="445146" target="_blank" rel="noreferrer noopener">Solidity</a> for writing the smart contract, Ether.js for interacting with the smart contract, and the hardhat for smooth development.</p>



<h2 class="wp-block-heading">Initiate Hardhat</h2>



<p>Hardhat is arguably the best <a href="https://blog.finxter.com/ethereum-top-10-articles-to-get-started/" data-type="post" data-id="53284" target="_blank" rel="noreferrer noopener">Ethereum</a> development environment to compile your contracts and run them on a development network. To install the hardhat, open the <code>vscode</code> terminal and just type</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">npm install –save-dev hardhat</pre>



<p>Hardhat will be installed on the directory. Now run hardhat.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">npx hardhat</pre>



<p>The command prompt will ask for creating a <a rel="noreferrer noopener" href="https://blog.finxter.com/javascript-developer-income-and-opportunity/" data-type="post" data-id="191233" target="_blank">JavaScript</a> project. Approve it. You need to install some dependencies to run the project. Copy this from the terminal and run. All the extra dependencies will be installed.</p>



<p>Create a new <a href="https://blog.finxter.com/layout-of-a-solidity-source-file-spdx-license-identifier-and-version-pragmas/" data-type="post" data-id="703612" target="_blank" rel="noreferrer noopener">Solidity file</a> inside the contract folder. &#8220;<code>bookSell.sol</code>&#8220;. We will be writing all the code here.</p>



<h2 class="wp-block-heading">Build Solidity Smart Contract</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1019" height="764" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-123.png" alt="" class="wp-image-1055401" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-123.png 1019w, https://blog.finxter.com/wp-content/uploads/2023/01/image-123-300x225.png 300w, https://blog.finxter.com/wp-content/uploads/2023/01/image-123-768x576.png 768w" sizes="auto, (max-width: 1019px) 100vw, 1019px" /></figure>
</div>


<p>I will create a simple and quick smart contract. This smart contract is basically for inputting the name, Book name, writer’s name, buyer address, the timing of issuing the order, etc.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pragma solidity  >= 0.5.0 &lt; 0.9.0;
contract BookSell{
    address payable owner;
    constructor(){
        owner = payable(msg.sender);
    }
    struct Receipt{
        uint256 timestamp ;
        string name;
        address buyer;
        string book;
        string writer;
    }
    Receipt[] receipts;
    function buyBook(string memory name, string memory book, string memory writer) public payable{
        require(msg.value>0,"Payment is not acceptable");
        owner.transfer(msg.value);
        receipts.push(Receipt(block.timestamp, name, msg.sender,book, writer));
    }
    function getReceipts() public view returns(Receipt[] memory) {
        return receipts;
    }
}
</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="336" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-116.png" alt="" class="wp-image-1055383" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-116.png 624w, https://blog.finxter.com/wp-content/uploads/2023/01/image-116-300x162.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<p>First, we need to confirm the address of the owner of the bookstall. This address will be <code><a href="https://blog.finxter.com/what-is-payable-in-solidity/" data-type="post" data-id="37282" target="_blank" rel="noreferrer noopener">payable</a></code> cause it will receive the money of the buyers.</p>



<p>Create a constructor for the owner. “<code>msg.sender</code>” will be the owner in this case. <code>msg.sender</code> is normally the address that is used to deploy the contract. The person or the account that deploys the contract is normally the contract owner and will receive the transaction on his account.</p>



<p>Create a <a rel="noreferrer noopener" href="https://blog.finxter.com/solidity-reference-types-array-slices-and-structs/" data-type="post" data-id="829701" target="_blank">struct</a> “<code>Receipt</code>” with three strings, that is,</p>



<ul class="wp-block-list">
<li>&#8220;<code>name</code>” for the buyer’s name, </li>



<li>“<code>book</code>&#8221; for the book buyers want to buy, and </li>



<li>&#8220;<code>writer</code>&#8221; for the writer of the book. </li>
</ul>



<p>The timestamp would be an unsigned integer to note down the time and an address to collect the buyer&#8217;s account address.</p>



<p>To store the data of several buyers, I created a &#8220;<code>receipts</code>&#8221; <a href="https://blog.finxter.com/solidity-array-members-and-manipulation-techniques/" data-type="post" data-id="830098" target="_blank" rel="noreferrer noopener">array</a>. It is a dynamic array, which means whenever a new buyer inputs his information, the receipt will be added dynamically to the receipts array.</p>



<p><a href="https://blog.finxter.com/solidity-function-type-examples-a-simple-illustrated-guide/" data-type="post" data-id="830464" target="_blank" rel="noreferrer noopener">Create a function</a> to buy the book. This <code>buyBook</code> function will take the information of the buyer as the parameters. The information includes the buyer&#8217;s name, book, and writer&#8217;s name. This function will also be <code>payable</code> cause we will use this to transfer money to the owner&#8217;s address.</p>



<p>Buyers must not pay zero eth as an amount. That&#8217;s why we added a condition with the &#8220;<code>require</code>&#8221; method. “<code>msg.value</code>&#8221; is the amount the buyer spends to buy the book.</p>



<p>“<code>owner.transfer(msg.value)</code>&#8221; is used to transfer the fund to the stall owner&#8217;s account.</p>



<p>When the transaction is done, add the transaction receipt to the receipts array with the help of the push method. Since the receipts array is a struct type of array, you can input the required fields as the parameter of receipt.</p>



<p>To get the information from the receipts, we created a <code>getReceipts()</code> function. This returns the receipt of each buyer when we call the function.</p>



<h2 class="wp-block-heading">Test the Smart Contract</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1019" height="679" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-124.png" alt="" class="wp-image-1055403" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-124.png 1019w, https://blog.finxter.com/wp-content/uploads/2023/01/image-124-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2023/01/image-124-768x512.png 768w" sizes="auto, (max-width: 1019px) 100vw, 1019px" /></figure>
</div>


<p>Before deploying the contract, we need to check if all the functionalities of the <a href="https://blog.finxter.com/smart-contracts-discover-how-to-create-them-directly-and-indirectly/" data-type="post" data-id="978963" target="_blank" rel="noreferrer noopener">smart contract</a> are working properly or not. Hardhat has its own node and tools for checking the smart contract. We will first deploy our smart contract on the hardhat node to check its functionality and then deploy it to our testnet.</p>



<p>Move inside the <code>deploy.js</code>. We will create several functions here for different purposes.</p>



<p>We need to generate some accounts for the transaction. Inside the <code>async main()</code> function, generate account addresses with the help of the <code>getSigners()</code> method of <code>ether.js</code>. One account is for the contract owner, and the other three are for different buyers.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const [owner, buyer1, buyer2, buyer3] = await hre.ethers.getSigners();</pre>



<p>Hardhat will generate four accounts with the help of ether modules. Each account will have 1000 eth by default. We can use that at the time of the transaction for testing purposes.</p>



<p>Create an addresses array to store all the addresses together.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const addresses = [
    owner.address,
    buyer1.address,
    buyer2.address,
    buyer3.address,
  ];
</pre>



<p>Now to get the balances of those addresses, we will create <code>obtainBalance()</code> function outside the main <code>function()</code></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const obtainBalance = async (address) => {
  const balanceBigInt = await hre.ethers.provider.getBalance(address);
  return hre.ethers.utils.formatEther(balanceBigInt);
};
</pre>



<p>This <code>obtainBalance()</code> function will take an address from the addresses array, and it will use the <code>getBalance()</code> method of the <code>ethers.provider</code> to get the balance.</p>



<p>We will get the output as a Big Int object, and we need to convert it to get the actual number. The <code>formatEther()</code> method of the <code>utils</code> library converts the big int object into a readable format.</p>



<p><strong>Reference</strong>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" target="_blank" rel="noreferrer noopener">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt</a></p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="345" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-117.png" alt="" class="wp-image-1055385" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-117.png 624w, https://blog.finxter.com/wp-content/uploads/2023/01/image-117-300x166.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<p>Now we will create another function to loop through the addresses, and it will also show the balances on the console.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const printBalances = async (addresses) => {
  let id = 0;
  for (const address of addresses) {
    console.log(`Account ${id} Balance:`, await obtainBalance(address));
    id++;
  }
};
</pre>



<p>The &#8220;<code>for</code>&#8221; loop is used to loop through all the addresses of the array. While looping, the <code>obtainBalance()</code> function will get the balance from each account. An <code>id</code> variable is used to mark each account with a unique id.</p>



<p>Apart from that, we want to see the receipt for each buyer. Let&#8217;s create a <code>printReceipt()</code> function to get the receipt.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const printReceipts = async (receipts) => {
  for (const receipt of receipts) {
    const timestamp = receipt.timestamp;
    const name = receipt.name;
    const buyer = receipt.buyer;
    const book = receipt.book;
    const writer = receipt.writer;
    console.log(
      `Buyer Details: Name:${name},Book:${book},Writer:${writer},Address:${buyer},Time:${timestamp}`
    );
  }
};
</pre>



<p></p>



<p>The <code>printReceipts()</code> function initiates a for loop that will loop through all the receipts of the receipts array. Then it will show all the buyer&#8217;s details from the receipt that will be called.</p>



<p>Now we need to call the receipts array from the smart contract. Otherwise, it won&#8217;t be possible to get data from the contract. Create an instance of the smart contract inside the <code>main()</code> function.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">  const bookSell = await hre.ethers.getContractFactory("BookSell");
  const contract = await bookSell.deploy(); //instance of the contract
</pre>



<p>With the first line of code, we called smart contract with the <code>getContractFactory()</code> method of the <code>ethers</code> library. Then we created an instance of the smart contract in the second line.</p>



<p>Now we can call the functions of the smart contract from here.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="309" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-118.png" alt="" class="wp-image-1055386" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-118.png 624w, https://blog.finxter.com/wp-content/uploads/2023/01/image-118-300x149.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<p>Let&#8217;s say we want to check the accounts&#8217; balances first. Let&#8217;s <a href="https://blog.finxter.com/javascript-intro-how-to-see-your-code-output/" data-type="post" data-id="175068" target="_blank" rel="noreferrer noopener">console log</a> the balance on the terminal with the help of <code>printBalance()</code> method that we created earlier.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">  console.log("Initial Balance:");
  printBalances(addresses);
</pre>



<p>Assume we want to send some balance to the owner’s address for buying books. Fix the amount we want to transfer</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">  const amount = { value: hre.ethers.utils.parseEther("1") };
  await contract
    .connect(buyer1)
    .buyBook("Adam", "Miracle Morning", "Hal Elrod", amount);
  await contract
    .connect(buyer2)
    .buyBook("Mike", "The Slight Edge", "Jeff Olson", amount);
  await contract
    .connect(buyer3)
    .buyBook("Peter", "Loving what is", "Byron Katie", amount);
</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="470" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-119.png" alt="" class="wp-image-1055387" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-119.png 624w, https://blog.finxter.com/wp-content/uploads/2023/01/image-119-300x226.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<p>We fixed an amount, one eth, to transfer from all the buyer’s addresses. We used the <code>parseEther()</code> method of the <code>utils</code> library to fix the value.</p>



<p>In the next few lines, we called the contract and established a connection with the buyer&#8217;s address. We also called the <code>buyBook</code> method of the smart contract to buy the books.</p>



<p>Inside the <code>buyBook</code> function we passed the buyer address, the book name, the writer name, and the amount as the parameter. For simplicity, we are sending the same amount from all the buyer&#8217;s accounts.</p>



<p>To check the balances after buying the book, we will call the <code>printBalance()</code> method again.&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">  console.log("Last Balance:");
  await printBalances(addresses);
</pre>



<p>We forgot to call the receipts array from the smart contract. We will use the <code>getReceipts()</code> methods from the smart contract to get the receipts.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">  const receipts = await contract.getReceipts();
  printReceipts(receipts);
}
</pre>



<p>Now. Let’s deploy the contract on the hardhat and check how it works.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">  await contract.deployed();
  console.log("Contract Address:", contract.address);
</pre>



<p>I deployed the contract in the first line and then asked for the contract address.</p>



<p>Let’s move to the terminal and run the script.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">npx hardhat run scripts/deploy.js</pre>



<p>Don’t forget to mention the directory of the file on the code.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="186" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-120.png" alt="" class="wp-image-1055388" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-120.png 624w, https://blog.finxter.com/wp-content/uploads/2023/01/image-120-300x89.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<p>I got these results on my terminal after running the scripts. You can see from here that initially, the balances of all the accounts were 10000 eth. But after the transaction, more than one eth was deducted from each of the last three accounts. </p>



<p>It took more than one eth because of the transaction fee. At the same time, we can see the owner&#8217;s account (Account 0) is credited with exactly three eth.</p>



<p>In the last part, we also gathered all the info from the buyer&#8217;s receipt, including the time of the transaction and the address of the buyer.</p>



<h2 class="wp-block-heading">Thanks for Reading <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2665.png" alt="♥" class="wp-smiley" style="height: 1em; max-height: 1em;" /></h2>



<p>That&#8217;s all for today. You have learned how to build and test a smart contract. In the next part, we will deploy the smart contract on a testnet.</p>



<p><strong>GitHub</strong>: <a rel="noreferrer noopener" href="https://github.com/yassesh/bookSell" target="_blank">https://github.com/yassesh/bookSell</a></p>
<p>The post <a href="https://blog.finxter.com/project-react-dapp-for-selling-ebooks-in-a-decentralized-manner-1-4/">I Created a React Decentralized App to Sell eBooks &#8211; Here&#8217;s How (1/4)</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>I Created a Counter Smart Contract with Ether.js &#8212; Here&#8217;s How</title>
		<link>https://blog.finxter.com/i-created-a-counter-smart-contract-with-ether-js-heres-how/</link>
		
		<dc:creator><![CDATA[Yassin Mahmud Abdul Quddus]]></dc:creator>
		<pubDate>Mon, 26 Dec 2022 09:43:00 +0000</pubDate>
				<category><![CDATA[Ethereum]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Smart Contracts]]></category>
		<category><![CDATA[Solidity]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1002304</guid>

					<description><![CDATA[<p>One of the presiding JavaScript libraries for interacting with the Ethereum blockchain is ether.js. The ether.js library, only 88 KB compressed in size, is remarkably smaller than the web3.js library. Because of that, web apps load more quickly if you use the ether.js API. This constantly improving library has already been popular among developers for ... <a title="I Created a Counter Smart Contract with Ether.js &#8212; Here&#8217;s How" class="read-more" href="https://blog.finxter.com/i-created-a-counter-smart-contract-with-ether-js-heres-how/" aria-label="Read more about I Created a Counter Smart Contract with Ether.js &#8212; Here&#8217;s How">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/i-created-a-counter-smart-contract-with-ether-js-heres-how/">I Created a Counter Smart Contract with Ether.js &#8212; Here&#8217;s How</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="I Created a Counter Smart Contract with Ether.js -- Here&#039;s How" width="937" height="527" src="https://www.youtube.com/embed/BKmaahv2szM?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>One of the presiding JavaScript libraries for interacting with the <a href="https://blog.finxter.com/introduction-to-smart-contracts-and-solidity-part-3-blockchain-basics/" data-type="post" data-id="537705" target="_blank" rel="noreferrer noopener">Ethereum blockchain</a> is <code>ether.js</code>. </p>



<p>The <code>ether.js</code> library, only 88 KB compressed in size, is remarkably smaller than the <code>web3.js</code> library. Because of that, web apps load more quickly if you use the <code>ether.js</code> API. This constantly improving library has already been popular among developers for its developer-friendly modules.</p>



<p>Today we will see how <code>ether.js</code> interacts with the blockchain and the <a href="https://blog.finxter.com/learn-to-build-smart-contracts-in-react-with-web3-js-heres-how-1-2/" data-type="post" data-id="978706" target="_blank" rel="noreferrer noopener">smart contract</a>. We will not go for the theoretical explanation of <code>ether.js</code>. </p>



<p>Instead, we will deal with some <strong>practical use cases</strong> of <code>ether.js</code>.</p>



<h2 class="wp-block-heading">Interacting with the Blockchain</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="956" height="637" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-330.png" alt="" class="wp-image-1002352" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-330.png 956w, https://blog.finxter.com/wp-content/uploads/2022/12/image-330-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2022/12/image-330-768x512.png 768w" sizes="auto, (max-width: 956px) 100vw, 956px" /></figure>
</div>


<h3 class="wp-block-heading">Connecting to blockchain:</h3>



<p>We need to connect to a node first to interact with the blockchain. </p>



<p>Today we will use <a href="https://www.infura.io/" data-type="URL" data-id="https://www.infura.io/" target="_blank" rel="noreferrer noopener">Infura</a>, a powerful suite of high-availability blockchain APIs and developer tools. If you still need to make an account in Infura, then just sign up. </p>



<p>After signing in, click the &#8220;<code>create new key</code>&#8221; button to create a new project. Select the network as web3 API and enter the project name as you wish. A new page will open, and you need to move to the &#8220;<code>get started with the web3 Ethereum</code>&#8221; option. Just copy the main net link from there.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="412" height="281" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-324.png" alt="" class="wp-image-1002311" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-324.png 412w, https://blog.finxter.com/wp-content/uploads/2022/12/image-324-300x205.png 300w" sizes="auto, (max-width: 412px) 100vw, 412px" /></figure>
</div>


<p>Then move to the visual studio code. Make a new folder and install node modules and <code>ether.js</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">npm init -y
npm install –-save ethers
</pre>



<p>Create a new javascript file for writing our codes. I am naming it as “<code>etherBlockchain.js</code>”.</p>



<p>Now import <code>ether.js</code> inside the javascript file.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const { ethers } = require("ethers");</pre>



<p>Now to read data from the blockchain, we need to fix the provider.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const provider = new ethers.providers.JsonRpcProvider(  "https://mainnet.infura.io/v3/3148ece387d84a40b4a8c883b07c33c0"
);
</pre>



<p>We have pasted the Infura URL as the parameter for JSON RPC provider. This will connect us with the Infura node.</p>



<h3 class="wp-block-heading">Get the current block:</h3>



<p>Using the Infura mainnet, we can get the current block number with the help of <code>ether.js</code> provider.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const interactBlockchain = async () => {
  const currentBlock = await provider.getBlockNumber();
  console.log("You are using the block: ", currentBlock);

};
</pre>



<p>We have created an <code>async await</code> function to identify the block number. <code>getBlockNumber()</code> method of the provider will help us to get the block number. In the vscode terminal, run the script.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">node etherBlockchain.js</pre>



<p>If everything runs fine, you should get the block number on the screen. Now to verify if it is genuine, visit the <code>etherscan.io</code> website. The current block number must be displayed under the <code>Latest Blocks</code> section.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="355" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-325.png" alt="" class="wp-image-1002314" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-325.png 624w, https://blog.finxter.com/wp-content/uploads/2022/12/image-325-300x171.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<h3 class="wp-block-heading">Get the Balance:</h3>



<p>To get the balance, we will use the <code>provider.getBalance()</code> method of <code>ether.js</code>. You need to put the address of any Ethereum account to get the balance of that account.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const balance = await provider.getBalance(
    "0xF977814e90dA44bFA03b6295A0616a897441aceC"
  );
console.log(“Account Balance: ”, balance);
</pre>



<p>All the codes should be kept inside the <code>async await</code> function.</p>



<p>When you run the script, you will get a <code>BigNumber</code> object as a return. <a rel="noreferrer noopener" href="https://blog.finxter.com/ethereum-top-10-articles-to-get-started/" data-type="post" data-id="53284" target="_blank">Ethe</a>reum runs many operations on numbers outside the range of safe values to use in javascript. </p>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> A <code>BigNumber</code> is an object which safely allows mathematical operations on numbers of any magnitude.</p>



<p><strong>Reference</strong>: <a href="https://docs.ethers.org/v5/api/utils/bignumber/" target="_blank" rel="noreferrer noopener">https://docs.ethers.org/v5/api/utils/bignumber/</a></p>



<p>You need to convert this big number object to a readable format to get the balance of the account.</p>



<p>We will use the <code>formatEther</code> method of the utils library of the <code>ether.js</code> to get the balance in ether.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const balanceInEther = ethers.utils.formatEther(balance);
console.log("Account balance in ether:", balanceInEther);
</pre>



<p>Now, if you run the script, you should get the account balance in ether.</p>



<p>This utils library of the <code>ether.js</code> is a vast one. You can do so many things with that.</p>



<p><strong>Reference</strong>: <a href="https://docs.ethers.org/v5/api/utils/" target="_blank" rel="noreferrer noopener">https://docs.ethers.org/v5/api/utils/</a></p>



<p>Now to convert the balance in <a href="https://blog.finxter.com/introduction-to-ethereums-gas-in-solidity-development/" data-type="post" data-id="37644" target="_blank" rel="noreferrer noopener">wei</a> again, we will use this <code>utils</code> library.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const balanceInWei = ethers.utils.parseEther(balanceInEther);
console.log("Account balance in wei:", balanceInWei);
</pre>



<p>When you run the script, You will get the balance in wei.</p>



<p>In this way, you can run any query on the blockchain by using the methods of <code>ether.js</code>. We need to see how we can interact with a <a href="https://blog.finxter.com/top-solidity-smart-contract-examples-for-learning/" data-type="post" data-id="663675" target="_blank" rel="noreferrer noopener">smart contract</a> using <code>ether.js</code>.</p>



<h2 class="wp-block-heading">Interacting with Smart Contracts</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="977" height="637" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-331.png" alt="" class="wp-image-1002354" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-331.png 977w, https://blog.finxter.com/wp-content/uploads/2022/12/image-331-300x196.png 300w, https://blog.finxter.com/wp-content/uploads/2022/12/image-331-768x501.png 768w" sizes="auto, (max-width: 977px) 100vw, 977px" /></figure>
</div>


<p>We have our simple smart contract ready for deployment on the <a href="https://blog.finxter.com/solidity-remix-ide-quickstart/" data-type="post" data-id="946353" target="_blank" rel="noreferrer noopener">Remix IDE</a>. </p>



<p>I have made a simple <code>Counter</code> contract that will increase the count by ten whenever you call the <code>increment</code> function. </p>



<p>The <code>getCount()</code> method will return the count whenever you call the <code>getCount()</code> method. We will call those methods from the node terminal of vscode.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pragma solidity >= 0.5.0 &lt; 0.9.0;
contract Counter {
    uint count = 0;

    function setCount(uint _count) public {
        count=_count;
    }

    function increment() public {
    count = count + 10;
    }

    function getCount() public view returns (uint) {
    return count;
    }
}
</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="414" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-326.png" alt="" class="wp-image-1002328" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-326.png 624w, https://blog.finxter.com/wp-content/uploads/2022/12/image-326-300x199.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<p>We need to deploy the smart contract in a blockchain. </p>



<p>We will use the Goerli testnet to deploy the contract, and the <a rel="noreferrer noopener" href="https://blog.finxter.com/metamask-simple-tutorial/" data-type="post" data-id="38157" target="_blank">Metamask</a> will be used to establish communication with the testnet. </p>



<p>We need some money on the goerli account to bear the <a href="https://blog.finxter.com/introduction-to-ethereums-gas-in-solidity-development/" data-type="post" data-id="37644" target="_blank" rel="noreferrer noopener">Gas fee cost</a> for the smart contract deployment. If you need to learn how to add the goerli test network on the Meatamask wallet and how to add some free goerli eth on the Metamask wallet, then watch some videos on youtube. It is very easy to add some free eth through the goerli faucet.</p>



<p>Now back to Remix IDE. After doing the compilation, you move to the &#8220;DEPLOY AND RUN TRANSACTIONS” section of the Remix IDE. Select the environment as “Injected Provider-Metamask”.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="378" height="669" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-327.png" alt="" class="wp-image-1002329" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-327.png 378w, https://blog.finxter.com/wp-content/uploads/2022/12/image-327-170x300.png 170w" sizes="auto, (max-width: 378px) 100vw, 378px" /></figure>
</div>


<p>Now click on the <code>deploy</code> button. Metamask will pop up and ask to confirm the transaction. You can even check the transaction on the etherscan if you want.</p>



<p>We need the smart contract address and ABI afterward to create an instance of the smart contract on the node terminal.</p>



<p>For this part, we need to use <a href="https://blog.finxter.com/learn-to-build-smart-contracts-in-react-with-web3-js-heres-how-1-2/" data-type="post" data-id="978706" target="_blank" rel="noreferrer noopener">React</a> as the frontend. This frontend will establish a connection with Metamask. Open the command prompt and type the following to initiate a react app in your directory.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/learn-to-build-smart-contracts-in-react-with-web3-js-heres-how-1-2/" data-type="post" data-id="978706" target="_blank" rel="noreferrer noopener">Learn to Build Smart Contracts in React with web3.js: Here’s How!</a></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">npx create-react-app ether_smart_contract</pre>



<p>A react app on <code>localhost:3000</code> must be running on your browser. Now, move to the <code>app.js</code> on vscode, clear the code, and import <code>ether.js</code> first.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import { ethers } from "ethers";</pre>



<p>We need to use <code>useEffect()</code> hook of the react. Inside the <code>useEffect</code>, create an <code>async await</code> function to write the codes to call the smart contract.</p>



<p>Now again, call the provider; in this case, our provider would be Metamask.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const provider = new ethers.providers.Web3Provider(window.ethereum);</pre>



<p>The test goerli network on our Metamask is using the Infura node. Hence, we don’t need to connect to the Infura network manually. </p>



<p>This is one of the privileges of using Metamask. With Metamask wallet, you can connect to different networks easily.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="446" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-328.png" alt="" class="wp-image-1002330" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-328.png 624w, https://blog.finxter.com/wp-content/uploads/2022/12/image-328-300x214.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<h3 class="wp-block-heading">Difference between provider and signer:</h3>



<p>We need to introduce a signer for our contract. <strong><em>What is the difference between the provider and the signer? </em></strong></p>



<p>The provider is required whenever you are reading any data from blockchain or smart contract, but you are not changing the state of something on the smart contract; whenever you are changing the state of something on the smart contract, you need to use the signer.</p>



<p>Actually, when you write something on the smart contract, you are changing the state of something. Whenever you bring some change to the smart contract, you have to bear a cost for the transaction. </p>



<p>The signer will sign a transaction on your behalf to validate the transaction. Every time you click the confirm transaction button on the Metamask, a signer automatically signs a transaction on the backend and validates the transaction.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const signer = provider.getSigner();</pre>



<p>Create two variables for the contract ABI and the contract address.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ContractAddress = “Input the contract address”;
ContractABI = “Input the contract ABI”;</pre>



<p>Now we can create an instance of the smart contract with the help of <code>contractABI</code> and <code>contractAddress</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const contract = new ethers.Contract(
        contractAddress,
        contractABI,
        signer
      );
</pre>



<p>This ethers. The contract method requires the contract address, contract ABI, and the signer as a parameter to create an instance of the smart contract.</p>



<h3 class="wp-block-heading">Calling the constant methods:</h3>



<p>Now our contract instance is ready. Using the contract instance, we can call the readable methods from the smart contracts.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const count = await contract.getCount();
console.log(count); 
</pre>



<p>We have called the <code>getCount()</code> function of the smart contract, which returns a big number. We need to convert it to string. For that,</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">console.log("Current count is:", String(count));</pre>



<h3 class="wp-block-heading">Calling the non-constant methods:</h3>



<p>Now we should get the count in a readable format. We can set the count as we desire by calling the <code>setCount()</code> method from the smart contract.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">await contract.setCount(20);</pre>



<p>The count must be set as 20. You can call the <code>getCount()</code> methods again to check the count.</p>



<p>Now, if we want to increment the count by ten, then we can call the <code>increment()</code> function with the help of <code>contract.current()</code> method.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const tx = await contract.connect(signer).increment();
await tx.wait();
</pre>



<p>As we change the blockchain state, we need to connect the signer to approve the transaction. We did it here.</p>



<p>The transaction will take some time to be mined on the blockchain. So, you have to wait a bit to see the count increase.</p>



<p>If you call the <code>getCount()</code> method again after some time, I hope you will see the count has increased by 10.</p>



<p>So that are some ways you can connect to a blockchain and query data from it. You have also seen the way smart contract interacts with <code>ether.js</code>. That&#8217;s all for today. Thanks for the reading.</p>
<p>The post <a href="https://blog.finxter.com/i-created-a-counter-smart-contract-with-ether-js-heres-how/">I Created a Counter Smart Contract with Ether.js &#8212; Here&#8217;s How</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>I Sent My First SOL with Solana&#8217;s Phantom Wallet and web3.js: Here&#8217;s How</title>
		<link>https://blog.finxter.com/i-sent-my-first-sol-with-solanas-phantom-wallet-and-web3-js-heres-how/</link>
		
		<dc:creator><![CDATA[Yassin Mahmud Abdul Quddus]]></dc:creator>
		<pubDate>Thu, 22 Dec 2022 16:40:47 +0000</pubDate>
				<category><![CDATA[Crypto]]></category>
		<category><![CDATA[Solana]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=994973</guid>

					<description><![CDATA[<p>Solana, one of the blockchains that offer an incredibly low transaction fee, is well known for its speed and efficiency. Compared to Ethereum&#8216;s 15 transactions per second, Solana’s network can handle about 3,400 transactions per second. 🛑 Attention: There is no free lunch &#8212; Solana sacrifices decentralization to accomplish this speed. Still &#8212; many freelancing ... <a title="I Sent My First SOL with Solana&#8217;s Phantom Wallet and web3.js: Here&#8217;s How" class="read-more" href="https://blog.finxter.com/i-sent-my-first-sol-with-solanas-phantom-wallet-and-web3-js-heres-how/" aria-label="Read more about I Sent My First SOL with Solana&#8217;s Phantom Wallet and web3.js: Here&#8217;s How">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/i-sent-my-first-sol-with-solanas-phantom-wallet-and-web3-js-heres-how/">I Sent My First SOL with Solana&#8217;s Phantom Wallet and web3.js: Here&#8217;s How</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="I Sent My First SOL with Solana&#039;s Phantom Wallet and web3.js: Here&#039;s How" width="937" height="527" src="https://www.youtube.com/embed/Pm3QnZTSOew?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>Solana, one of the <a rel="noreferrer noopener" href="https://blog.finxter.com/the-bullish-case-on-blockchains/" data-type="post" data-id="30448" target="_blank">blockchains</a> that offer an incredibly low transaction fee, is well known for its speed and efficiency. Compared to <a rel="noreferrer noopener" href="https://blog.finxter.com/ethereum-top-10-articles-to-get-started/" data-type="post" data-id="53284" target="_blank">Ethereum</a>&#8216;s 15 transactions per second, Solana’s network can handle about 3,400 transactions per second. </p>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f6d1.png" alt="🛑" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Attention</strong>: There is no free lunch &#8212; Solana sacrifices decentralization to accomplish this speed.</p>



<p>Still &#8212; many <a href="https://blog.finxter.com/get-more-clients-as-a-freelance-developer-with-this-one-simple-trick/" data-type="post" data-id="3558" target="_blank" rel="noreferrer noopener">freelancing clients</a> will ask us to create Solana &#8220;decentralized&#8221; apps for them, so today, we will try out a transaction on Solana.</p>



<p>We will use Solana <a rel="noreferrer noopener" href="https://blog.finxter.com/learn-to-build-smart-contracts-in-react-with-web3-js-heres-how-1-2/" data-type="post" data-id="978706" target="_blank">web3.js</a>, which provides the interface for the developers to interact with the Solana blockchain using <a rel="noreferrer noopener" href="https://blog.finxter.com/javascript-developer-income-and-opportunity/" data-type="post" data-id="191233" target="_blank">JavaScript</a>. We will create two accounts on the phantom wallet. Then airdrop some balance on the first account, and we will send a transaction to the second account. All the things will be done from scratch in JavaScript.</p>



<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f30d.png" alt="🌍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <a rel="noreferrer noopener" href="https://docs.solana.com/developing/clients/javascript-api" data-type="URL" data-id="https://docs.solana.com/developing/clients/javascript-api" target="_blank">Reference</a></p>



<p>Here&#8217;s an example project description where this practical project would be useful. If you just want to know how it is done, feel free to skip the &#8220;Project Description&#8221;. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h2 class="wp-block-heading">Example Project Description</h2>



<p class="has-global-color-8-background-color has-background">This project will involve sending and receiving SOL tokens (Solana) over the Solana blockchain. The goal of this project is to facilitate a secure, fast, and reliable transfer of SOL tokens between two parties. </p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1001" height="563" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-278.png" alt="" class="wp-image-995058" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-278.png 1001w, https://blog.finxter.com/wp-content/uploads/2022/12/image-278-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2022/12/image-278-768x432.png 768w" sizes="auto, (max-width: 1001px) 100vw, 1001px" /></figure>
</div>


<p>First, the two parties involved in the transaction will need to set up Solana wallets in order to store and send SOL tokens. The wallets will need to be integrated with the Solana blockchain and will need to be used to create an address for each party. Each party will then need to securely store their wallet’s address and private key for safekeeping. </p>



<p>Second, the two parties will need to agree on the amount of SOL tokens to be transferred. Once agreed upon, the sender will need to enter the recipient’s address in the wallet’s send interface, enter the amount of SOL tokens to be sent, and click ‘send’. The wallet will then generate a transaction on the Solana blockchain and broadcast it to the entire network. </p>



<p>Third, the Solana blockchain will validate the transaction and add it to the blockchain ledger. After a few seconds, the transaction will be confirmed and the recipient will receive the SOL tokens in their wallet. The transaction will then be visible on the Solana blockchain explorer. </p>



<p>Finally, the two parties will need to keep track of the transaction by checking their wallets and the Solana blockchain explorer to ensure that the transaction has been completed successfully. </p>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Summary</strong>: This project will enable the two parties to securely, quickly, and reliably send and receive SOL tokens over the Solana blockchain.</p>



<h2 class="wp-block-heading">Step 1: Create a Phantom Wallet</h2>



<p>A very popular wallet for the Solana blockchain is the phantom wallet. The phantom extension is available for chrome, firefox, ios and other androids. Just add the extension on your browser if it still needs to be installed. Since we will build on a testing environment, we will change the network to <code>devnet</code>.</p>



<p>Now we need two create two wallets for the transaction purpose. Go to settings and click on the “add wallet&#8221; option to add a wallet. We use wallet 2 as our sender wallet and wallet 3 as our receiver wallet.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="377" height="562" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-267.png" alt="" class="wp-image-994985" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-267.png 377w, https://blog.finxter.com/wp-content/uploads/2022/12/image-267-201x300.png 201w" sizes="auto, (max-width: 377px) 100vw, 377px" /></figure>
</div>


<h2 class="wp-block-heading">Step 2: Set up Solana-web3.js</h2>



<p>First, create a folder and import node modules and package.json&nbsp; on it.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">npm init -y</pre>



<p>Now install Solana web3.js.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">npm install @solana/web3.js</pre>



<p>Now visit the <code>package.json</code> file to check if the dependencies of the Solana web3 are installed properly. You will get the version number for the Solana web3 included there.</p>



<p>Just add (“type”: “module”) in the dependencies list inside the “<code>package.json</code>&#8221; file. Otherwise, you will face problems in importing modules.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="333" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-268.png" alt="" class="wp-image-994993" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-268.png 624w, https://blog.finxter.com/wp-content/uploads/2022/12/image-268-300x160.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<p>Create a <code>soltransaction.js</code> file which will be used to write all the codes.&nbsp;</p>



<p>Inside the <code>soltransaction.js</code> file, import web3.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import solanaweb3 from "@solana/web3.js";
import bs58 from "bs58";</pre>



<p>We must import <code>bs58</code>, the javaScript component, to compute base 58 <a href="https://blog.finxter.com/python-base64/" data-type="post" data-id="327003" target="_blank" rel="noreferrer noopener">encoding</a>. We will require this thing soon.</p>



<h2 class="wp-block-heading">Step 3: Connect with My Phantom Wallet</h2>



<p>To establish a connection with the phantom wallet, we will call the Connection object of the <code>web3.js</code>. This <code>Connection</code> object will establish a connection with RPC API. Let&#8217;s create the connection instance.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const connection = new solanaweb3.Connection("https://api.devnet.solana.com");</pre>



<p>We used the <code>devnet</code> API URL as we will commit our transaction in the <code>devnet</code> network of the phantom wallet.</p>



<p>To commit the transaction on the Solana blockchain, we need to generate a keypair for the accounts. We need to generate Key pairs with public and private keys (used for signed transactions). </p>



<p>There are two ways to obtain a Keypair. </p>



<ul class="wp-block-list">
<li>Either you can generate a new Keypair with the help of <code>solanaweb3</code>, or </li>



<li>You can obtain a new Keypair using a secret key.</li>
</ul>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="361" height="503" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-269.png" alt="" class="wp-image-994998" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-269.png 361w, https://blog.finxter.com/wp-content/uploads/2022/12/image-269-215x300.png 215w" sizes="auto, (max-width: 361px) 100vw, 361px" /></figure>
</div>


<p>We will use the private key of our wallets to generate Keypair. Move to the phantom wallet extension. You will get an export private key option if you click on the wallet. Just copy the private key from there.</p>



<p>The &#8220;<code>Keypair.fromSecretKey</code>” method of <code>solanaweb3</code> will help us to generate Keypair from the private key.</p>



<p><code>Bs58</code> will decode the <code>uint8Array</code> from the private key of our wallets.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f30d.png" alt="🌍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <a rel="noreferrer noopener" href="https://www.npmjs.com/package/bs58" data-type="URL" data-id="https://www.npmjs.com/package/bs58" target="_blank">Reference</a></p>



<p>Let&#8217;s create two variables, <code>senderWallet</code> and <code>receiverWallet</code>, for our <code>wallet2</code> and <code>wallet3</code>, respectively.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">let senderWallet = solanaweb3.Keypair.fromSecretKey(
  bs58.decode(
    "4g2ij8ML3Jd42LJv33apPpQtFkyK5XV9dq3PGa7LiR6LL33ZmraXYbMg7kCQvTAXd7tJRp7mYL1LQ6HEvHL2DhQF"
  )
);
let receiverWallet = solanaweb3.Keypair.fromSecretKey(
  bs58.decode(
    "5MYvQVLAxJH9FWGf1feCPGC4PagBYcLecW5W8YAJoLLakR47iHVZW16aW2C6Pq6Zo8BHvdh1iCYigM9dUEU7RwyD"
  )
);
</pre>



<p>Now our sender and receiver wallet is ready. So we can get the balance from each account.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="311" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-270.png" alt="" class="wp-image-995000" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-270.png 624w, https://blog.finxter.com/wp-content/uploads/2022/12/image-270-300x150.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<h2 class="wp-block-heading">Step 4: Get the Balance From My Wallets</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">(async () => {
  let senderBalance = await connection.getBalance(senderWallet.publicKey);
  let receiverBalance = await connection.getBalance(receiverWallet.publicKey);

  console.log(
    `Sender Balance: ${senderBalance / solanaweb3.LAMPORTS_PER_SOL} SOL`
  );
  console.log(
    `Receiver Balance: ${receiverBalance / solanaweb3.LAMPORTS_PER_SOL} SOL`
  );
})();
</pre>



<p>These <code>senderBalance</code> and <code>receiverBalance</code> variables inside the <code>async await</code> function will use the <code>getBalance()</code> method of the <code>solanaweb3</code> to extract the balance from the sender and receiver accounts.</p>



<p>The <code>getBalance</code> method will take the public key of the wallet addresses as the parameter.</p>



<p>Then we “<code>console.log</code>” the sender and receiver balance to see It on the terminal. To express the balance in short, we used <code>LAMPORTS_PER_SOL</code>. Lamport is the smallest unit of Solana. A Lamport has a value of 0.000000001 SOL.</p>



<p>Now, if we run the script on the visual studio code terminal. We should get the balance of the two wallets.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">node soltransaction.js</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="142" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-271.png" alt="" class="wp-image-995004" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-271.png 624w, https://blog.finxter.com/wp-content/uploads/2022/12/image-271-300x68.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<h2 class="wp-block-heading">Step 5: Airdrop Solana in Sender Account</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="280" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-272.png" alt="" class="wp-image-995005" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-272.png 624w, https://blog.finxter.com/wp-content/uploads/2022/12/image-272-300x135.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<p>Now we will airdrop some balance to the sender account using the web3.js library through the <code>devnet</code> network.</p>



<p>Again, we will create an <code>async await</code> function and use the <code>requestAirdrop()</code> method of the web3 to request an airdrop on the sender account.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">(async()=>{
let txhash = await connection.requestAirdrop(senderWallet.publicKey, 1e9));
console.log(`Transaction hash : ${txhash}`)
})()
</pre>



<p>The “<code>connection.requestAirdrop</code>&#8221; method will take two parameters. The first one is the public key of the account that will be receiving the airdrop and the second one is the amount it will be receiving as an airdrop.</p>



<p>In this case, it will receive a billion lamport equal to a Solana.</p>



<p>This <code>txhash</code> variable will provide us with a transaction hash that we can track down later on the blockchain explorer, such as Solana beach or <code>solscan</code> or Solana explorer etc.</p>



<p>Then just run the script to get the transaction hash on the terminal.</p>



<p>Copy the transaction hash from the terminal and move to &#8220;<code>explorer.solana.com</code>&#8220;. Check the cluster is switched to <code>devnet</code> as we are using the <code>devnet</code> network. Now paste the transaction hash on the search query. You will get all the details of the transaction, and the sender account must be credited with one sol.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="280" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-273.png" alt="" class="wp-image-995007" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-273.png 624w, https://blog.finxter.com/wp-content/uploads/2022/12/image-273-300x135.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<p>You can visit the phantom wallet and check wallet 2. It must be credited with one sol. Now, if you want to airdrop more sol on the <code>wallet2</code>, you can change the figure on the <code>requestAirdrop</code> code and run the script again.</p>



<h2 class="wp-block-heading">Step 6: Transfer Solana from one account to another</h2>



<p>We have airdropped some balance in our sender wallet; now, Let’s try to transfer some sol from the sender wallet to the receiver wallet. Again we need to wrap all the function calls inside an <code>async()</code> function.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">(async () => {
  let transaction = new solanaweb3.Transaction().add(
    solanaweb3.SystemProgram.transfer({
      fromPubkey: senderWallet.publicKey,
      toPubkey: receiverWallet.publicKey,
      lamports: 2 * solanaweb3.LAMPORTS_PER_SOL,
    })
  );
  transaction.feePayer = senderWallet.publicKey;
  let transactionHash = await connection.sendTransaction(transaction, [
    senderWallet,
    receiverWallet,
  ]);
  console.log(`${transactionHash}`);
})();
</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="319" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-274.png" alt="" class="wp-image-995010" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-274.png 624w, https://blog.finxter.com/wp-content/uploads/2022/12/image-274-300x153.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<p>We need to create a new transaction first, and then we need to initiate the “<code>SystemProgram.transfer</code>” method. </p>



<p>SystemProgram is one of the native programs of Solana that is a handful for creating new accounts, allocating account data, assigning accounts to own programs, transferring lamports from System Program-owned accounts and paying transaction fees. </p>



<p>We will utilize the transfer method of the SystemProgram to transfer sol from the sender wallet to the receiver wallet.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f30d.png" alt="🌍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <a rel="noreferrer noopener" href="https://docs.solana.com/developing/runtime-facilities/programs" data-type="URL" data-id="https://docs.solana.com/developing/runtime-facilities/programs" target="_blank">Reference</a></p>



<p>This “<code>SystemProgram.transfer</code>” method asks for three parameters. They are the public key of the wallet that will be used for sending sol, the public key of the wallet that will receive the amount, and the amount of lamports you ask to transfer.</p>



<p>We need to confirm the feepayer for the transaction. Otherwise, the transaction will not take place. In this case, the sender wallet will pay the fee for the transaction.</p>



<p>Now we need to send this transaction to the <code>devnet</code> cluster. For that, we will call the <code>sendTransaction</code> method of the <code>solanaweb3</code> that takes two parameters. One is the transaction itself, and the next is an array consisting of the sender and receiver Keypair. This will return a transaction hash again when you “<code><a href="https://blog.finxter.com/javascript-intro-how-to-see-your-code-output/" data-type="post" data-id="175068" target="_blank" rel="noreferrer noopener">console.log</a></code>” on the terminal.</p>



<p>Before running the node, you need to bring the airdrop section under the comment or delete the portion if you want. Otherwise, this airdrop will again start executing. Let’s call the node on the terminal.</p>



<p>Copy the transaction hash from the terminal and paste it on the Solana explorer. You can see the transfer from the sender&#8217;s wallet to the receiver&#8217;s wallet.</p>



<p>Now, you move to the phantom wallet extension. Check the balance of wallet 2 and wallet 3. You must see that your wallet 3 is credited with two sol. And if you check wallet 2, you will see the transfer balance and the transfer fee have been debited from the wallet.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="361" height="619" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-275.png" alt="" class="wp-image-995012" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-275.png 361w, https://blog.finxter.com/wp-content/uploads/2022/12/image-275-175x300.png 175w" sizes="auto, (max-width: 361px) 100vw, 361px" /></figure>
</div>

<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="365" height="615" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-276.png" alt="" class="wp-image-995013" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-276.png 365w, https://blog.finxter.com/wp-content/uploads/2022/12/image-276-178x300.png 178w" sizes="auto, (max-width: 365px) 100vw, 365px" /></figure>
</div>


<p>So that’s all for today. You have seen how the Solana blockchain interacts with the Solana web3.js and how the transaction takes place on the Solana blockchain. I hope you enjoyed the tutorial. Thanks for being with me. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f64f.png" alt="🙏" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f30d.png" alt="🌍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <a rel="noreferrer noopener" href="https://stackoverflow.com/questions/68166964/how-can-you-transfer-sol-using-the-web3-js-sdk-for-solana" data-type="URL" data-id="https://stackoverflow.com/questions/68166964/how-can-you-transfer-sol-using-the-web3-js-sdk-for-solana" target="_blank">Reference</a></p>
<p>The post <a href="https://blog.finxter.com/i-sent-my-first-sol-with-solanas-phantom-wallet-and-web3-js-heres-how/">I Sent My First SOL with Solana&#8217;s Phantom Wallet and web3.js: Here&#8217;s How</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Learn to Build Smart Contracts in React with web3.js: Here&#8217;s How! (2/2)</title>
		<link>https://blog.finxter.com/learn-to-build-smart-contracts-in-react-with-web3-js-heres-how-2-2/</link>
		
		<dc:creator><![CDATA[Yassin Mahmud Abdul Quddus]]></dc:creator>
		<pubDate>Wed, 14 Dec 2022 10:40:55 +0000</pubDate>
				<category><![CDATA[dApp]]></category>
		<category><![CDATA[Ethereum]]></category>
		<category><![CDATA[Smart Contracts]]></category>
		<category><![CDATA[Solidity]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=978798</guid>

					<description><![CDATA[<p>Welcome to the second part of the series. In the first part, we have seen how web3.js helped the react frontend to connect to the smart contract. 👉 Recommended Tutorial: Learn to Build Smart Contracts in React with web3.js: Here’s How! (1/2) We explored the power of the &#8220;web3.eth&#8221; attribute to call the data from ... <a title="Learn to Build Smart Contracts in React with web3.js: Here&#8217;s How! (2/2)" class="read-more" href="https://blog.finxter.com/learn-to-build-smart-contracts-in-react-with-web3-js-heres-how-2-2/" aria-label="Read more about Learn to Build Smart Contracts in React with web3.js: Here&#8217;s How! (2/2)">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/learn-to-build-smart-contracts-in-react-with-web3-js-heres-how-2-2/">Learn to Build Smart Contracts in React with web3.js: Here&#8217;s How! (2/2)</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Learn to Build Smart Contracts in React with web3.js: Here&#039;s How! (2/2)" width="937" height="527" src="https://www.youtube.com/embed/ea4i96n0s7A?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>Welcome to the second part of the series. In the first part, we have seen how <code>web3.js</code> helped the react frontend to connect to the smart contract.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended Tutorial</strong>: <a rel="noreferrer noopener" href="https://blog.finxter.com/learn-to-build-smart-contracts-in-react-with-web3-js-heres-how-1-2/" data-type="post" data-id="978706" target="_blank">Learn to Build Smart Contracts in React with web3.js: Here’s How! (1/2)</a></p>



<p>We explored the power of the &#8220;<code>web3.eth</code>&#8221; attribute to call the data from the smart contract. But this time, we are not using React. </p>



<p>In this part, we will connect to localhost from <a rel="noreferrer noopener" href="https://blog.finxter.com/solidity-remix-ide-quickstart/" data-type="post" data-id="946353" target="_blank">Remix IDE</a> using <code>web3.js</code>. We will create our simple smart contract and deploy it from the Remix IDE. Then we will call the functions and methods from our deployed smart contracts.</p>



<h2 class="wp-block-heading">Write the Smart Contract</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1010" height="674" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-196.png" alt="" class="wp-image-978905" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-196.png 1010w, https://blog.finxter.com/wp-content/uploads/2022/12/image-196-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2022/12/image-196-768x513.png 768w" sizes="auto, (max-width: 1010px) 100vw, 1010px" /></figure>
</div>


<p>First, we need to create our smart contract and move to &#8220;<code>remix.ethereum.org</code>&#8220;, the Remix online IDE for web-based development. </p>



<p>Move to the contract folder and create a new <a rel="noreferrer noopener" href="https://blog.finxter.com/layout-of-a-solidity-source-file/" data-type="post" data-id="455693" target="_blank">Solidity file</a> named “<code>summation.sol</code>”. In the Solidity file, we will introduce a simple summation smart contract after declaring the <a href="https://blog.finxter.com/layout-of-a-solidity-source-file-spdx-license-identifier-and-version-pragmas/" data-type="post" data-id="703612" target="_blank" rel="noreferrer noopener">Solidity version</a>. </p>



<p>Inside our smart contract, we will create some functions that we will try to call afterward from the <strong><a rel="noreferrer noopener" href="https://blog.finxter.com/node-js-developer-income-and-opportunity/" data-type="post" data-id="189364" target="_blank">node.js</a></strong> terminal of the visual studio code. Web3 will again work as the mediator to establish a connection between Remix IDE and the locally running <a href="https://blog.finxter.com/how-to-deploy-a-smart-contract-to-the-ropsten-testnet-in-brownie/" data-type="post" data-id="63341">test blockcha</a><a href="https://blog.finxter.com/how-to-deploy-a-smart-contract-to-the-ropsten-testnet-in-brownie/" data-type="post" data-id="63341" target="_blank" rel="noreferrer noopener">i</a><a href="https://blog.finxter.com/how-to-deploy-a-smart-contract-to-the-ropsten-testnet-in-brownie/" data-type="post" data-id="63341">n ganache</a>.</p>



<p>First, declare three unsigned integers <code>x</code>, <code>y</code> and <code>z</code>. But let’s make it clear what our smart contract will do. The purpose of the smart contract is to add two numbers, <code>x</code> and <code>y</code>. After summing up, the result will be stored as the <code>z</code> variable. We will use two functions, <code>set()</code> and <code>get()</code>, to set the numbers and to get the result, respectively.</p>



<p>The <code>set()</code> function will take two integers, <code>i</code> and <code>j</code>, as parameters. These <code>i</code> and <code>j</code> will be the value of the <code>x</code> and <code>y</code> variables. The sum of <code>x</code> and <code>y</code> will be published as <code>z</code>.</p>



<p>We need to return the result as an integer to display it on the terminal. That’s why we created the <code>get()</code> function. The <code>get()</code> function will return the value of <code>z</code>, which stores the sum of <code>x</code> and <code>y</code>.</p>



<p>In short, we are adding two numbers to the smart contract. </p>



<p>We can set the numbers as we like from the node terminals of the visual studio code. Then we will get the result from the contract by accessing the <code>get()</code> function of the smart contract. </p>



<p>We will not set the numbers from the <a href="https://blog.finxter.com/solidity-remix-ide-quickstart/" data-type="post" data-id="946353" target="_blank" rel="noreferrer noopener">Remix IDE</a>; instead, we will be using the node terminal to access the <a href="https://blog.finxter.com/introduction-to-smart-contracts-and-solidity-part-3-blockchain-basics/" data-type="post" data-id="537705" target="_blank" rel="noreferrer noopener">smart contract</a> with the help of web3.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="624" height="324" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-188.png" alt="" class="wp-image-978806" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-188.png 624w, https://blog.finxter.com/wp-content/uploads/2022/12/image-188-300x156.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>
</div>


<h2 class="wp-block-heading">Deploy the Smart Contract in the Localhost</h2>



<p>Before deploying the smart contract, you need to compile the <a href="https://blog.finxter.com/layout-of-a-solidity-source-file-spdx-license-identifier-and-version-pragmas/" data-type="post" data-id="703612" target="_blank" rel="noreferrer noopener">Solidity file</a>. </p>



<p>To do that, move to the <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-install-the-solidity-compiler-overview-videos/" data-type="post" data-id="716526" target="_blank">SOLIDITY COMPILER</a> section of the Remix IDE. You will get a &#8220;<code>Compile summation.sol</code>&#8221; option available. Just click on that. </p>



<p>The compiler will compile the contract automatically if your code is correct. Otherwise, some red exclamation warning will appear on your contract with the possible solution for the mistakes of your codes. Just try to solve the issues. </p>



<p>Otherwise, the solidity compiler will not allow you to deploy the contract. Since there will be no chance to change the state of the contract once it is deployed, it is important to recheck the codes several times.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="431" height="597" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-189.png" alt="" class="wp-image-978810" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-189.png 431w, https://blog.finxter.com/wp-content/uploads/2022/12/image-189-217x300.png 217w" sizes="auto, (max-width: 431px) 100vw, 431px" /></figure>
</div>


<p>To deploy our smart contract in ganache, we need to connect our Remix IDE with Ganache first. Move to the <strong>deploy</strong> option and select the ganache provider from the environment drop-down.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="438" height="514" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-190.png" alt="" class="wp-image-978813" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-190.png 438w, https://blog.finxter.com/wp-content/uploads/2022/12/image-190-256x300.png 256w" sizes="auto, (max-width: 438px) 100vw, 438px" /></figure>
</div>


<p>An external node request window will pop up and ask for the Web3 provider endpoint. Here we will provide the URL of our Ganache local host.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="615" height="416" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-191.png" alt="" class="wp-image-978817" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-191.png 615w, https://blog.finxter.com/wp-content/uploads/2022/12/image-191-300x203.png 300w" sizes="auto, (max-width: 615px) 100vw, 615px" /></figure>
</div>


<p>If the Ganache is appropriately connected, you will be able to see all the accounts of ganache under the ACCOUNT drop-down. Now ganache is connected. Let’s deploy the contract by clicking the deploy menu.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="409" height="376" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-192.png" alt="" class="wp-image-978818" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-192.png 409w, https://blog.finxter.com/wp-content/uploads/2022/12/image-192-300x276.png 300w" sizes="auto, (max-width: 409px) 100vw, 409px" /></figure>
</div>


<p>Just under the environment drop-down, you can see the custom network is 5777. That is the network ID of the ganache. It also indicates that you are connected with the correct local host.</p>



<h2 class="wp-block-heading">Calling the Functions from Node Using Web3</h2>



<p>Let’s move to the visual studio code and open the terminal. Make sure you are in the directory where web3 is installed already. To activate the node terminal just type:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Node</pre>



<p>You will get the node version number in return. Now the node terminal is running, and we will import our web3 now.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">let Web3 = require ("web3");</pre>



<p>Let&#8217;s create an instance of the web3 and connect to ganache with the HTTP provider.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">let web3 = new Web3(new Web3.providers.HttpProvider(http://127.0.0.1:7545));</pre>



<p>Now again, we will create an instance of the contract with the help of <code>web3.eth.contract</code> method. This will take the ABI and address of the contract as the parameter. To get the ABI, move to the Remix IDE and visit the &#8220;solidity compiler&#8221; section. </p>



<p>You will get the ABI at the bottom left corner. Move to the &#8220;deploy and run transactions&#8221; section for the <a href="https://blog.finxter.com/data-types-in-solidity-smart-contract-part-21-contract-types-fixed-size-byte-arrays-dynamically-sized-byte-arrays-address-literals-rational-and-integer-literals/" data-type="post" data-id="753297" target="_blank" rel="noreferrer noopener">contract address</a>. You will get the contract address under the deployed contracts. Just copy the ABI and address to use it for building the contract instance.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const contract = new web3.eth.Contract(ABI, Address);</pre>



<p>I did not write the ABI and contract address from the code as it is too long to copy. You must replace the code with your own ABI and contract address.</p>



<p>A copy of our deployed smart contract is available now. We can call the methods and functions from the contracts now. “<code>contracts.method</code>” attribute will help us to call the functions we want.</p>



<p>Now we will set the value of <code>x</code> and <code>y</code> by calling the <code>set()</code> function from the contract.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">contract.methods.set(90,10).send({from:"0x367Ea75b206ECfc52712154CCd18c88488a465cA"});</pre>



<p>We set the value for <code>x</code> and <code>y</code> as 90 and 10, respectively. The <code>send</code> method mentions the account address we use for the transaction. This account address is mainly required to bear the gas price cost for the transaction. </p>



<p>You can use any account of the ganache for the transaction. It should not cause any problems.</p>



<p>Now, if everything works well, you can call the <code>get()</code> function from the contract and check what it returns.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">contract.methods.get().call().then(console.log);</pre>



<p>After calling the <code>get()</code> function through “<code>contract.methods()</code>&#8221; you need to &#8220;<code>console.log</code>&#8221; the output. Otherwise, the terminal will return a promise.</p>



<p>If the terminal returns 100, then it means our function is working well.</p>



<p>Let&#8217;s try to get the value of the <code>x</code> integer from the <a href="https://blog.finxter.com/mastering-the-ethereum-virtual-machine-evm-for-solidity-smart-contracts/" data-type="post" data-id="572801" target="_blank" rel="noreferrer noopener">smart contract</a>. Again we will use the &#8220;<code>contract.methods</code>” attribute to call the variable from the smart contract.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">contract.methods.x().call().then(console.log);</pre>



<p>If everything works well, then you will get 90 as an output. So, you can easily estimate the power of the &#8220;<code>contract.methods</code>&#8221; attribute of the web3 in case of fetching data from the smart contract. It is really easy to call any method or function by using <code>web3.js</code>.</p>



<p>That concludes the two-part series. You have learned how the smart contract interacts with the node terminal and how web3 helps us to communicate with the smart contract. thanks for being with me.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Reference</strong>: <a rel="noreferrer noopener" href="https://web3js.readthedocs.io/en/v1.2.11/web3-eth-contract.html#id26" target="_blank">https://web3js.readthedocs.io/en/v1.2.11/web3-eth-contract.html#id26</a></p>
<p>The post <a href="https://blog.finxter.com/learn-to-build-smart-contracts-in-react-with-web3-js-heres-how-2-2/">Learn to Build Smart Contracts in React with web3.js: Here&#8217;s How! (2/2)</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 
Minified using Disk

Served from: blog.finxter.com @ 2026-06-21 05:50:57 by W3 Total Cache
-->