当前位置:   article > 正文

智能合约开发笔记--html页面使用ethers.js与合约交互_html 引入ethers

html 引入ethers

本文提供一个例子,演示在html页面中如何使用ethers.js,并通过metamask钱包连接,与区块链进行交互。包含的内容有:

1.查询metamask钱包的账户地址,账户金额;

2.与样例合约 Greeter进行交互, 调用查询方法;调用修改状态变量的方法; 监听事件,对修改后的状态进行回调。

直接上代码:

示例合约: Greeter.sol #选用hardhat项目的默认示例,加了一个event

  1. //SPDX-License-Identifier: Unlicense
  2. pragma solidity ^0.8.0;
  3. import "hardhat/console.sol";
  4. contract Greeter {
  5. string private greeting;
  6. constructor(string memory _greeting) {
  7. console.log("Deploying a Greeter with greeting:", _greeting);
  8. greeting = _greeting;
  9. }
  10. function greet() public view returns (string memory) {
  11. return greeting;
  12. }
  13. function setGreeting(string memory _greeting) public {
  14. console.log("Changing greeting from '%s' to '%s'", greeting, _greeting);
  15. greeting = _greeting;
  16. emit SetGreet(_greeting,msg.sender);
  17. }
  18. event SetGreet(string _greeting,address sender);
  19. }

html页面代码:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>webapp</title>
  7. <style>
  8. body div {
  9. margin-bottom: 30px;
  10. }
  11. .wallet, .interact_to_contract{
  12. width: 450px;
  13. margin-top: 30px;
  14. }
  15. .wallet button{
  16. width: 100%;
  17. }
  18. .dogreet{
  19. width: 100%;
  20. }
  21. </style>
  22. </head>
  23. <body>
  24. <div class="wallet">
  25. <button onclick="connect_to_metamask()">连接metamask钱包</button><br /><br>
  26. 账户地址:<span id="txt_curent_addr"></span><br /><br>
  27. 账户余额:<span id="txt_balance"></span><br />
  28. </div>
  29. <hr style="border:solid #987cb9;" width="100%">
  30. <div class="interact_to_contract">
  31. <button onclick="doGreet()" class="dogreet">Greeter合约greet函数</button><br /><br>
  32. <input id="input_greeting"><button onclick="doSetGreeting()">Greeter合约setGreeting</button><br/><br>
  33. <span id="txt_greet_log"></span>
  34. </div>
  35. </body>
  36. </html>
  37. <script src="https://cdn.ethers.io/lib/ethers-5.2.umd.min.js" type="application/javascript"></script>
  38. <script>
  39. //创建一个Provider
  40. const provider = new ethers.providers.Web3Provider(window.ethereum)
  41. const greet_addr="0x5fbdb2315678afecb367f032d93f642f64180aa3";
  42. //Greeter合约的ABI
  43. const greetAbi= [
  44. {
  45. "inputs": [
  46. {
  47. "internalType": "string",
  48. "name": "_greeting",
  49. "type": "string"
  50. }
  51. ],
  52. "stateMutability": "nonpayable",
  53. "type": "constructor"
  54. },
  55. {
  56. "anonymous": false,
  57. "inputs": [
  58. {
  59. "indexed": false,
  60. "internalType": "string",
  61. "name": "_greeting",
  62. "type": "string"
  63. },
  64. {
  65. "indexed": false,
  66. "internalType": "address",
  67. "name": "sender",
  68. "type": "address"
  69. }
  70. ],
  71. "name": "SetGreet",
  72. "type": "event"
  73. },
  74. {
  75. "inputs": [],
  76. "name": "greet",
  77. "outputs": [
  78. {
  79. "internalType": "string",
  80. "name": "",
  81. "type": "string"
  82. }
  83. ],
  84. "stateMutability": "view",
  85. "type": "function"
  86. },
  87. {
  88. "inputs": [
  89. {
  90. "internalType": "string",
  91. "name": "_greeting",
  92. "type": "string"
  93. }
  94. ],
  95. "name": "setGreeting",
  96. "outputs": [],
  97. "stateMutability": "nonpayable",
  98. "type": "function"
  99. }
  100. ]
  101. /**
  102. * 连接metamask钱包,获取余额
  103. */
  104. async function connect_to_metamask() {
  105. //向钱包发送授权请求
  106. const accounts = await provider.send("eth_requestAccounts", []);
  107. //获取账户余额信息
  108. if (accounts && accounts.length > 0) {
  109. let myAccountAddr = accounts[0];
  110. let balance = ethers.utils.formatEther(await provider.getBalance(myAccountAddr));
  111. let network = await provider.getNetwork();
  112. //显示在界面上;
  113. document.getElementById('txt_curent_addr').innerText = myAccountAddr;
  114. document.getElementById('txt_balance').innerText = balance;
  115. console.log("当前账户地址:", myAccountAddr);
  116. console.log("金额:", balance);
  117. console.log("Chain Info;", network.chainId, network.name);
  118. }
  119. }
  120. /**
  121. *访问合约的查询函数
  122. */
  123. async function doGreet(){
  124. const greet = new ethers.Contract(greet_addr, greetAbi, provider);
  125. //与合约交互;
  126. const wd = await greet.greet();
  127. document.getElementById("txt_greet_log").innerText='greeting:'+wd;
  128. }
  129. /*
  130. 修改合约的状态变量
  131. */
  132. async function doSetGreeting(){
  133. let str=document.getElementById('input_greeting').value;
  134. console.log(str);
  135. const signer=provider.getSigner();
  136. const greet = new ethers.Contract(greet_addr, greetAbi, signer);
  137. //与合约交互;
  138. await greet.setGreeting(str);
  139. //监控事件,对结果进行处理
  140. greet.on("SetGreet",(greeting,sender)=>{
  141. if(greeting==str){
  142. console.log("修改完成!",sender,greeting);
  143. document.getElementById("txt_greet_log").innerText='greeting:'+greeting//"Greeting 已经修改成了:"+greeting+"</br>修改者:"+sender;
  144. }
  145. })
  146. }
  147. </script>

演示方法说明:

1.使用hardhat 开启一个本地节点;  不熟悉的可以看我的上一篇hardhat使用入门

2.将上面的合约发布到本在环境;

3.在chrome中打开metamask 连接到本地环境;

4.将上面的html代码保存成html文件,放到本地web服务器根目录下,然后在chrome打开;  可以在页面中进行测试;

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/天景科技苑/article/detail/877828
推荐阅读
  • 相关标签
      

    闽ICP备14008679号