【问题标题】:Retrieving Solidity Event Data with Ethers.js使用 Ethers.js 检索 Solidity 事件数据
【发布时间】:2022-08-02 18:02:33
【问题描述】:

我是 Solidity 和 Ethers.js 的新手,所以如果有任何业余错误,那就是原因。

我正在尝试构建一个 dApp,它在我的智能合约上运行一个函数,检索从事件发出的数据,然后将其显示在我的前端。到目前为止,我已经让它在 Localhost 上运行。目前,MetaMask 连接到我的前端,但是当我尝试确认与合约的交易时它会引发错误。

创建函数(JS):

    async function create() {
        ///Acquiring values
        postBody = document.getElementById(\"in-1-pbd\").value;
        postSubcat = document.getElementById(\"in-2-sc\").value;
        console.log(postBody + \", \" + postSubcat);
        ///Connecting with Ethereum
        await requestAccount()
        if (typeof window.ethereum != \'undefined\') {
          const provider = new ethers.providers.Web3Provider(window.ethereum);
          const signer = provider.getSigner();
          const contract = new ethers.Contract(blokracyAddress, Blokracy.abi, signer)
          const transaction = await contract.createBallot(postSubcat, postBody)
          await transaction.wait()
        ///Building and presenting the ballot
        contract.on(\"Creation\", (message, idnum ) => {
          console.log(\"Creation Event Data: \", message, idnum);
          buildBallot(Wallet.publicKey, idnum, postBody);
          });
        } else {
          window.alert(\"Non-Ethereum browser detected. You should consider installing MetaMask.\")
        }
      }

申请账户功能:

      async function requestAccount() {
        await window.ethereum.request({ method: \'eth_requestAccounts\' });
      }

创建函数(Solidity):

///Event Declaration
    event Creation(string message, uint idnum);
///Functionality
///Creating a Ballot:
    function createBallot(
        string memory _subcategory, string memory _post
    ) public {

        ///Set Operator
        operator = msg.sender;

        ///Increment ballotNum
        ballotNum ++;

        ///Apply specifics to ballot
        ballot[ballotNum] = Ballot(
            ballotNum, _subcategory, operator,
            _post, 0, 0, 0, 0
        );

        ///return string and ballotNum
        emit Creation(\"Ballot was successfully posted!\", ballotNum);
        
    }

任何洞察力都会令人惊叹。就像我说的,我是新手,并试图通过构建这个项目尽可能多地了解 dApp。

    标签: javascript ethereum solidity metamask ethers.js


    【解决方案1】:

    您可以尝试这种方法在 web3 的帮助下在前端调用智能合约的功能。

    const web3 = new Web3(sNetworkRPCURL);
    const oDefaultWeb3 = new Web3(window.ethereum);
    let oContractObject;
    let sWalletAddress;
    async function create() {
            ///Acquiring values
            postBody = document.getElementById("in-1-pbd").value;
            postSubcat = document.getElementById("in-2-sc").value;
            console.log(postBody + ", " + postSubcat);
            ///Connecting with Ethereum
    
            if(typeof window.ethereum=="undefined"){
                console.log("METAMASK IS NOT FOUND");
                return;
            }
    
            oContractObject = new web3.eth.Contract(aContractABI,sContractAddress);
            let oNewContractObject = new oDefaultWeb3.eth.Contract(aContractABI,sContractAddress);
    
            const aReqAccount = await window.ethereum.request({
                method: "eth_requestAccounts",
            });
            sWalletAddress=aReqAccount[0];
    
            let estimatedGas;      
        
            try {
                estimatedGas = await oNewContractObject.methods
                    .createBallot(postSubcat, postBody)
                    .estimateGas({
                        from: sWalletAddress                    
                    });
        
                console.log("Estimated Gas: ", estimatedGas);
            } catch (error){          
        
                console.log(error);   
        
                return;
            }
            try {
                await oNewContractObject.methods
                    .createBallot(postSubcat, postBody)
                    .send({
                        from: sWalletAddress,                   
                        gas: estimatedGas,
                    })
                    .on("transactionHash", (txHash) => {
                        console.log("Transaction Hash: ", txHash);                    
                    })
                    .on("receipt", async (txReceipt) => {
                        console.log("Receipt: ", txReceipt);   
                       
                    })
                    .catch("error", (err) => {
                        console.error(err);
                        
                    });
            } catch (err) {
                console.error(err);
               
            }
        }
    

    在这段代码中,您可以创建单独的函数来访问元掩码帐户并存储在全局变量中。

    我只想澄清我在代码中采用的 web3 对象和 oDefaultWeb3 对象。第一个 web3 对象,我将使用它来查看或调用()方法。另一个对 send() 方法很有用。

    所以,现在我希望这种方法对您开发 dApp 等有帮助。

    【讨论】:

      猜你喜欢
      • 2022-08-17
      • 2022-08-04
      • 2018-03-21
      • 1970-01-01
      • 1970-01-01
      • 2017-11-08
      • 1970-01-01
      • 2022-08-03
      • 1970-01-01
      相关资源
      最近更新 更多