Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] I Created a Counter Smart Contract with Ether.js — Here’s How

#1
I Created a Counter Smart Contract with Ether.js — Here’s How

<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload='{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;1002304&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;1&quot;,&quot;legendonly&quot;:&quot;&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;starsonly&quot;:&quot;&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}'>
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (1 vote) </div>
</p></div>
</p>
<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>Interacting with the Blockchain</h2>
<h3>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 “<code>create new key</code>” 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 “<code>get started with the web3 Ethereum</code>” 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/uplo...00x205.png 300w" sizes="(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>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 decoding="async" loading="lazy" 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/uplo...00x171.png 300w" sizes="(max-width: 624px) 100vw, 624px" /></figure>
</div>
<h3>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/14.0.0/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>Interacting with Smart Contracts</h2>
<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 decoding="async" loading="lazy" 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/uplo...00x199.png 300w" sizes="(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 “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 decoding="async" loading="lazy" 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/uplo...70x300.png 170w" sizes="(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/14.0.0/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 decoding="async" loading="lazy" 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/uplo...00x214.png 300w" sizes="(max-width: 624px) 100vw, 624px" /></figure>
</div>
<h3>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>
<h2>Calling the constant methods:</h2>
<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>
<h2>Calling the non-constant methods:</h2>
<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’s all for today. Thanks for the reading.</p>
</div>


https://www.sickgaming.net/blog/2022/12/...heres-how/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016