web3开发:前端开发 ethers.js

web3开发:前端使用ethers.js调用Hello智能合约。

hello.sol 智能合约文件:

// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;

contract Hello {
    function greet() external pure returns(string memory) {
        return "Hello web3";
    }
}

dapp.html  前端文件:

<html>
  <head>
    <script src="https://cdn.ethers.io/lib/ethers-5.2.umd.min.js" type="text/javascript"></script>
    <script src="./contract.js" type="text/javascript"></script>
  </head>
  <body>
    <div style="text-align:center">
      <div style="text-align: center; margin-top: 30px;">
        <button onclick="connectWallet()">Connect Wallet</button>
        <button onclick="runContract()">Run Contract</button>
      </div>
      <div style="margin-top: 10px;" id="account">Account:</div>
      <div style="margin-top:10px;" id="contract">Contract:</div>
    </div>
    <script type="text/javascript">
      async function connectWallet() {
        if (typeof window.ethereum === "undefined") {
          alert("please install wallet first!");
          return;
        }

        let accounts = await window.ethereum.request({method:'eth_requestAccounts'});
        if (accounts.length > 0 ) {
          document.getElementById("account").innerText = "Account: " + accounts[0];
        }
      }

      async function runContract() {
        if (typeof window.ethereum === "undefined") {
          alert("please install wallet first!");
          return;
        }

        let provider = new ethers.providers.Web3Provider(window.ethereum);
        let contract = new ethers.Contract(contractAddress, contractAbi, provider.getSigner());
        let result = await contract.greet();
        document.getElementById("contract").innerText = result;
      }
    </script>
  </body>
</html>

contract.js文件:

const contractAddress = "0x620D0eA50aa8Cae1c3C55006793412272De9E8Ed";
const contractAbi = [
{
"inputs": [],
"name": "greet",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "pure",
"type": "function"
}
];

下一章:香港发表《有关虚拟资产在港发展的政策宣言》

下载链接:有关虚拟资产在港发展的政策宣言10月31日,在香港金融科技周上,香港特区政府正式发表《有关虚拟资产在港发展的政策宣言》(下称《宣言》),阐明政府为在香港发展具活力的虚拟资产行业和生态系统 ...