国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Web Front-end JS Tutorial WebI For Simple Smart Contract

WebI For Simple Smart Contract

Nov 29, 2024 am 03:21 AM

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

  1. 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.

  2. 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:

    WebI For Simple Smart Contract

    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.

  3. 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

  1. 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"
        }
      ]
    
  2. 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. 
  3. You'll need to redeploy your smart contract every time you restart your Hardhat node.

  4. 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java vs. JavaScript: Clearing Up the Confusion Java vs. JavaScript: Clearing Up the Confusion Jun 20, 2025 am 12:27 AM

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.

Javascript Comments: short explanation Javascript Comments: short explanation Jun 19, 2025 am 12:40 AM

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

How to work with dates and times in js? How to work with dates and times in js? Jul 01, 2025 am 01:27 AM

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.

Why should you place  tags at the bottom of the ? Why should you place tags at the bottom of the ? Jul 02, 2025 am 01:22 AM

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

JavaScript vs. Java: A Comprehensive Comparison for Developers JavaScript vs. Java: A Comprehensive Comparison for Developers Jun 20, 2025 am 12:21 AM

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

JavaScript: Exploring Data Types for Efficient Coding JavaScript: Exploring Data Types for Efficient Coding Jun 20, 2025 am 12:46 AM

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

What is event bubbling and capturing in the DOM? What is event bubbling and capturing in the DOM? Jul 02, 2025 am 01:19 AM

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.

What's the Difference Between Java and JavaScript? What's the Difference Between Java and JavaScript? Jun 17, 2025 am 09:17 AM

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.

See all articles