【问题标题】:Calling a smart contract function using metamask with ether.js使用带有 ether.js 的元掩码调用智能合约函数
【发布时间】:2023-02-07 08:30:58
【问题描述】:

我对区块链和 JavaScript 都是全新的。

我正在尝试创建一个简单的网页,人们可以在其中生成一个基本上存储他们 2 个名字的“婚礼”智能合约。为此,我创建了一个 WeddingCerficate 合约,它存储名称并具有 getter 函数,以及一个 WeddingCertificateFactory 使我能够生成 WeddingCertificate。您可以在下面的 solidity 中找到智能合约的代码。

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.0 <0.9.0;

contract WeddingCertificate{
  string private spouse1;
  string private spouse2;

  constructor(string memory _spouse1, string memory _spouse2) {
      spouse1 = _spouse1;
      spouse2 = _spouse2;
  }

  function getSpouses() public view returns (string memory,string memory) {
  return (spouse1,spouse2);
  } 

}

contract WeddingCertificateFactory{


   event Wedding(string _spouse1, string _spouse2, address indexed contract_adress );

   function Unite(string memory _spouse1, string memory _spouse2)public returns (bool success) {
           WeddingCertificate wedding = new WeddingCertificate(_spouse1, _spouse2);
           emit Wedding(_spouse1,_spouse2 , address(wedding));
           return true ;

   }


}

我在 Goerli Tesnet 上部署了 WeddingCertificateFactory。现在我正尝试在 javascript 中创建一个函数(使用 ether.js),使用户能够直接在 Web 界面上创建自己的 weddingCertificate。

为此,我编写了下面的函数,但由于某些原因,这只生成了 20 次新的婚礼证书。即使它确实有效,最后两个打印在控制台中也看不到。

当我测试该功能并且没有任何反应时,我没有收到任何错误(至少我可以在控制台中看到)。

我不熟悉 JavaScript 中的异步,我也尝试了 .then( 语法,但我没有发现任何区别。

async function CreateWedding(){
    const spouse1 = document.getElementById("spouse1").value;
    const spouse2 = document.getElementById("spouse2").value;
    if (spouse1.length > 0 && spouse2.length >0) {
      console.log(`spouse 1: ${spouse1} , spouse2 : ${spouse2} `);

      const ethereum = window.ethereum ;
      const accounts = await ethereum.request({
      method: "eth_requestAccounts",
      });

      const provider = new ethers.providers.Web3Provider(ethereum, "any");
      const walletAddress = accounts[0];
      const signer = provider.getSigner(walletAddress);

      let abi = [
          " function Unite(string memory _spouse1, string memory _spouse2)"
      ];


      const contractAddress = "0x2556Ff7f7F1c013bBB60bD120E1828032Cd84cc4"; //WeddingFactory Contract

      const contract = new ethers.Contract(contractAddress, abi, signer);

      console.log("sending the contract");

      tx = await contract.Unite(spouse1,spouse2);
      console.log(tx);
      console.log("finished");



    } else {
        alert("Please enter 2 names");
    }

  
}

【问题讨论】:

    标签: javascript solidity smartcontracts web3js ethers.js


    【解决方案1】:

    尝试在web3client.app 中创建您的 abi 方法。

    它有 ether.js 的代码生成器,您可以直接在您的应用程序中使用它。

    如果您的合同中存在实际问题,它本身就会失败。

    【讨论】:

      猜你喜欢
      • 2022-10-01
      • 2017-08-07
      • 2019-01-24
      • 2023-01-30
      • 2020-04-08
      • 1970-01-01
      • 2022-09-29
      • 2019-12-26
      • 2019-08-27
      相关资源
      最近更新 更多