Let's build a web frontend to a smart contract! This is a followup to my previous post about creating a simple smart contract with Solidity and Hardhat. The instructions here assume you are picking up up with the same contract that we just deployed to our Hardhat environment.
In the last post we created and tested a contract that will increment a counter stored in a state variable. Using the Hardhat console we called the incrementCount() and getCount() functions. In the real world, interfacing with a contract won't be through a development console. One way to create an application that calls these functions will be via Javascript (via the ethers.js library) in a web page - a Web3 application!
As stated in the previous post, interacting with web3 applications requires a browser that has a built in wallet. In this simple example we'll use Metamask. Metmask comes pre-configured for Etherium and maybe a few other EVM based blockchains, but not our simulated blockchain in the Hardhat environment. To get this all running, we are going to first setup Metmask, then create the HTML/Javascript needed to call our contract.
Metamask / Web3 Browser
-
Install Metamask. I'll use the Chrome extension found here. If you are a Chrome user, this will let you now view and interact with web3 content.
I won't walk you through the initial setup, but you will probably be prompted to import an existing private key or generate a new one and write down the recovery phrase. Do that.
-
Next we'll add the Hardhat network to Metamask. Metamask supports any EVM you'd like, but it needs to be configured to do so. Usually this is just a matter of adding the chain ID and RPC URL. From inside Metamask (you might need to start it by clicking on your Chrome plugins and selecting it) you should see your public address in the top middle. To the left of your address there will be a dropdown that shows the current network. Click that to see what other networks are available:
Click "Add Custom Network". Fill in the Network Name with something like "Hardhat", the Network RPC URL with the IP address and Port of your Hardhat Node, probably something like this if you are running it locally:
http://127.0.0.1:8545/Enter the Chain ID of 1337 and the symbol can just be ETH for now. Note that we are not dealing with real ETH on the real Ethereum network, but be very careful to stay on our Hardhat network if you have real ETH in your wallet.
Now switch to the Hardhat Network that we just added in the Metamask plugin. In your terminal that is monitoring your running Hardhat node, you should see some activity as your wallet connects.
-
Since your Metamask wallet doesn't currently have any (fake) ETH, let's send it some. Get your public address from Metamask (at the top of the Metamask window, under the wallet's name, click the copy button). From your terminal window that is running the Hardhat console, do:
const [owner, feeCollector, operator] = await ethers.getSigners(); await owner.sendTransaction({ to: "PasteYourMetamaskAddressHere", value: ethers.parseEther("0.1") });
If you go back to Metamask, you should see that you now have some ETH in your Hardhat wallet! Now we are ready to do some web3 transactions on our Hardhat network.
Create a Web3 Webpage
-
Let's create a simple webpage to view and increment our counter. I'm not going to use any heavy frameworks, just plain old HTML, Javascript and the ethers.js library. However, you won't be able to just point the browser to a .htm document, you'll need to be running a webserver somewhere for the Metamask plugin to work. Depending on your OS, you might be able to use a lightweight server like http-server or something locally.
We'll need a few things from when we deployed our contract in the previous post. Refer back to the last post and grab the contract address and contract's ABI JSON array from the artifacts directory. We don't need the rest of the JSON from that file, just what is in the "abi" property, it should start with a [ and end with a ] and look something like this:
[ { "inputs": [], "stateMutability": "nonpayable", "type": "constructor" }, { "inputs": [], "name": "getCount", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "incrementCount", "outputs": [], "stateMutability": "nonpayable", "type": "function" } ]
-
Let's put this into some HTML and Javascript:
<html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/ethers/5.2.0/ethers.umd.min.js" type="application/javascript"></script> </head> <body> <h2>The counter is at: <span> </li> <li> <p>We should now be able to view our HTML document in a web browser with the Metamask plugin installed. I won't go through the Javascript, but if you are familiar with JavaScript and following the concepts and what we did in the Hardhat terminal previously, what is happening in the code should be fairly straight-forward. Metamask should prompt you that you are connecting to the site and you'll need to select the Hardnet network that we set up earlier. You should see something like this in the browser:</p> <p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173282167151033.jpg" class="lazy" alt="WebI For Simple Smart Contract" /></p> </li> <li><p>If all went well, you can click on the "Increment" button. Metamask will let you know that you are about to make a transaction and inform you of the gas fee. You can Confirm this transaction in Metamask and see the count increment on both the website and in the terminal where you have the hardhat node running!</p></li> <li><p>Congratulations, we are interacting with our contract through a web UI!</p></li> </ol> <p>A few notes as you dive deeper into Hardhat and Metamask for development:</p> <ul> <li><p>Each transaction has an nonce. When you reset your hardhat node, that nonce gets reset and you might loose sync with what Metamask thinks is a unique nonce. When that happens, Metmask has an option to set a custom nonce with the transaction, or you can reset Metamask's nonces in Settings->Advanced->Clear Activity Tab data.
You'll need to redeploy your smart contract every time you restart your Hardhat node.
-
If you are writing contracts that will keep track of users by their public address and want to experiment in the Hardhat console with transactions form different users, you can impersonate different addresses in the console that were displayed when you first started the Hardhat node with something like this before you connect to the contract:
const signers = await ethers.getSigners(); const newSigner = signers[1]; // Change the 1 to a different number that corolates with one of the pre-generated testing addresses const newMain = await main.connect(newSigner); newMain.setContractAddress("test","0xYourContractAddress");
The above is the detailed content of WebI For Simple Smart Contract. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

Java and JavaScript are different programming languages. 1.Java is a statically typed and compiled language, suitable for enterprise applications and large systems. 2. JavaScript is a dynamic type and interpreted language, mainly used for web interaction and front-end development.
