• 6.DApp-用Web3实现前端与智能合约的交互


    题记

            用Web3实现前端与智能合约的交互,以下是操作流程和代码。

    准备ganache环境

            文章地址:4.DApp-MetaMask怎么连接本地Ganache-CSDN博客 

    准备智能合约 

            文章地址: 2.DApp-编写和运行solidity智能合约-CSDN博客

    编写index.html文件

            

        Name Contract Demo

       

       

       

       

    设置姓名

       

       

       

       

       

       

       

    1. html>
    2. <html>
    3. <head>
    4. <title>Name Contract Demotitle>
    5. <script src="https://cdn.jsdelivr.net/npm/web3@1.5.2/dist/web3.min.js">script>
    6. <script>
    7. // 检查Metamask是否已安装
    8. if (typeof window.ethereum !== 'undefined') {
    9. console.log('Metamask已安装');
    10. }
    11. // 设置Web3.js提供者为Metamask
    12. const provider = window.ethereum;
    13. const web3 = new Web3(provider);
    14. // 请求Metamask连接到以太坊网络
    15. provider.request({ method: 'eth_requestAccounts' })
    16. .then(() => {
    17. console.log('Metamask已连接到以太坊网络');
    18. })
    19. .catch((err) => {
    20. console.error('无法连接到以太坊网络', err);
    21. });
    22. function setName() {
    23. // 合约地址
    24. const contractAddress = '0x32FDC4E86421143b1c27dE49542Bc8ECE2B162a0';
    25. // 合约ABI
    26. const contractABI = [
    27. {
    28. "inputs": [
    29. {
    30. "internalType": "string",
    31. "name": "_name",
    32. "type": "string"
    33. }
    34. ],
    35. "name": "setName",
    36. "outputs": [],
    37. "stateMutability": "nonpayable",
    38. "type": "function"
    39. },
    40. {
    41. "inputs": [],
    42. "name": "getName",
    43. "outputs": [
    44. {
    45. "internalType": "string",
    46. "name": "",
    47. "type": "string"
    48. }
    49. ],
    50. "stateMutability": "view",
    51. "type": "function"
    52. }
    53. ];
    54. const contract = new web3.eth.Contract(contractABI, contractAddress);
    55. const name = document.getElementById('name').value;
    56. // 替换为您的账户地址web3.eth.defaultAccount
    57. const fromAddress = '0x4e8eB4d1C203929074A3372F3703E556820fEA57';
    58. //contract.methods.setName(name).send({from: fromAddress})
    59. contract.methods.setName(name).send({from: fromAddress})
    60. .on('transactionHash', function(hash){
    61. console.log('Transaction Hash:', hash);
    62. })
    63. .on('receipt', function(receipt){
    64. console.log('Transaction Receipt:', receipt);
    65. })
    66. .on('error', function(error){
    67. console.error('Error:', error);
    68. });
    69. }
    70. function getName() {
    71. // 合约地址
    72. const contractAddress = '0x32FDC4E86421143b1c27dE49542Bc8ECE2B162a0';
    73. // 合约ABI
    74. const contractABI = [
    75. {
    76. "inputs": [
    77. {
    78. "internalType": "string",
    79. "name": "_name",
    80. "type": "string"
    81. }
    82. ],
    83. "name": "setName",
    84. "outputs": [],
    85. "stateMutability": "nonpayable",
    86. "type": "function"
    87. },
    88. {
    89. "inputs": [],
    90. "name": "getName",
    91. "outputs": [
    92. {
    93. "internalType": "string",
    94. "name": "",
    95. "type": "string"
    96. }
    97. ],
    98. "stateMutability": "view",
    99. "type": "function"
    100. }
    101. ];
    102. const contract = new web3.eth.Contract(contractABI, contractAddress);
    103. contract.methods.getName().call()
    104. .then(function(result) {
    105. console.log('Name:', result);
    106. document.getElementById('nameValue').innerText = result;
    107. })
    108. .catch(function(error) {
    109. console.error('Error:', error);
    110. });
    111. }
    112. script>
    113. head>
    114. <body>
    115. <h1>设置姓名h1>
    116. <label for="name">姓名:label>
    117. <input type="text" id="name">
    118. <button onclick="setName()">设置姓名button>
    119. <br>
    120. <button onclick="getName()">得到姓名button>
    121. <br>
    122. <span id="nameValue">span>
    123. body>
    124. html>

    执行程序 

           使用vscode的Live Server打开网页

           参考这篇文章的执行方法:1.Vue-在独立页面实现Vue的增删改查-CSDN博客 

    展示图 

    发起交易 

    完成交易 

     后记

            觉得有用可以点赞或收藏!

  • 相关阅读:
    主机jvisualvm连接到tomcat服务器查看jvm状态
    elasticsearch常用接口和基本操作
    Redis的RDB持久化
    90后小伙以这196道MySQL面试题,实力吊打面试官,生生挤进大厂
    .NET应用系统的国际化-整体设计思路
    SpringBoot 项目使用 Sa-Token 完成登录认证
    使用 Gin 框架实现 HTTP 路由注册的 Go 语言工具函数详解
    zabbix监控项
    ansible中的hostvars
    [JS高级程序设计] ES6 新增的集合对象总结
  • 原文地址:https://blog.csdn.net/m0_70819559/article/details/133892708