Solidity

從 React 獲取來自 Solidity 合約的事件呼叫

  • July 27, 2022

我正在尋找做某事,如果一個事件是從solidity合約中產生的。

Here's my solidity contract::

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

contract QuoteV2{
string private quote;

event quoteUploaded(string newQuote);

// mapping(address => string) public users;
struct userQuoteTime {
   mapping(address => string) u;

   string _quote;
   string _time ;        
   

}

struct newUser {
       string userName;
       address walletAddress;
}
mapping (uint256 => newUser) public users;

   event newUserCame(uint256 indexed _userId);
uint256 public userCount;

function setQuote(string memory _quote) public {
   quote = _quote;

   emit quoteUploaded(_quote);
}
function getQuote() public view returns(string memory){
   return quote;
}
function newUserF(address _walletAddress, string memory _userName) public {
   newUser memory User;

   User.userName = _userName;
   User.walletAddress = _walletAddress;
   users[userCount] = newUser(_userName, _walletAddress);
   userCount++;

}
// function getUsers() public view returns(newUser memory) {
   
//     return users;
// }
function getUsers() public view returns (newUser[] memory){
 newUser[] memory id = new newUser[](userCount);
 for (uint i = 0; i < userCount; i++) {
     newUser storage user = users[i];
     id[i] = user;
 }
 return id;
 }

我想趕上quoteUploaded活動。我正在使用反應打字稿。請幫我。

繼承人你需要什麼:

  1. 首先創建新的javascript文件。例如:eventListener.js
  2. 在此處複製和修改程式碼,使其適合您的contractAbi、contractAddress 和providerURL,確保其以“wss”開頭。
  3. 執行listenOnQuoteUploadedEvent函式。(腳本會一直保持打開,所以你不需要關閉它)
  4. 從solidity 發出你需要的事件。

確保您通過 NPM 或 YARN 安裝了 ethers。

   const ethers = require("ethers");

let contractAbi;
let contractAddress;
let provider;
let CONTRACT;

const listenOnQuoteUploadedEvent = (_contractAbi, _contractAddress, 
websocketProviderURL) => {
   contractAbi = _contractAbi;
   contractAddress = _contractAddress;
   provider = new ethers.providers.WebSocketProvider(websocketProviderURL);
   CONTRACT = new ethers.Contract(contractAddress, contractAbi, provider);
   CONTRACT.on("quoteUploaded",(newQuote)=>{
   console.info(newQuote);
   })
}

我希望它有所幫助。

引用自:https://ethereum.stackexchange.com/questions/132477