Solidity

如何獲得實際的工作流程(事件)

  • July 16, 2022

我有幾個可靠的列舉:

enum  WorkflowStatus {
       RegisteringVoters,
       ProposalsRegistrationStarted,
       ProposalsRegistrationEnded,
       VotingSessionStarted,
       VotingSessionEnded,
       VotesTallied
   }

在我的前面,我可以點擊一個按鈕來呼叫我的函式:

function startProposalsRegistering() external onlyOwner {
       require(workflowStatus == WorkflowStatus.RegisteringVoters, 'Registering proposals cant be started now');
       workflowStatus = WorkflowStatus.ProposalsRegistrationStarted;
       emit WorkflowStatusChange(WorkflowStatus.RegisteringVoters, WorkflowStatus.ProposalsRegistrationStarted);
   }

正如你所看到的,當我呼叫這個函式時工作流發生了變化。我想創建一個顯示目前工作流的另一個按鈕,我如何使用 Moralis 來做到這一點?

最後我找到了怎麼做:)

const {
       runContractFunction: voting,
       data: enterTxResponse,
       isLoading,
       isFetching,
   } = useWeb3Contract({
       abi: [
           {
               "inputs": [],
               "name": "workflowStatus",
               "outputs": [
                   {
                       "internalType": "enum Voting.WorkflowStatus",
                       "name": "",
                       "type": "uint8"
                   }
               ],
               "stateMutability": "view",
               "type": "function",
               "constant": true
           },
       ],
       contractAddress: 'contractAddress',
       functionName: "workflowStatus",
       params: {},
   })

<button
               onClick={async () =>
                   await voting({
                       onSuccess: (mess) => {
                           handleSuccess()
                           console.log(mess)
                       },
                       onError: (err) => {
                           console.log(err)
                       }
                   })
               }
           >
               Change status
           </button>

console.log 給了我正確的事件:)

謝謝你們的時間!

假設 workflowStatus 在契約狀態下成功更新,您可以像這樣監聽您的事件(來自文件https://docs.moralis.io/moralis-dapp/automatic-transaction-sync/smart-contract-events#觀看新的智能合約事件

// 從雲程式碼創建同步事件的程式碼範例

let options = {
 chainId: "0x1",
 address: "0x5c69bee701ef814a2b6a3edd4b1652cb9cc5aa6f",
 topic: "PairCreated(address, address, address, uint256)",
 abi: {
   anonymous: false,
   inputs: [
     {
       indexed: true,
       internalType: "address",
       name: "token0",
       type: "address",
     },
     {
       indexed: true,
       internalType: "address",
       name: "token1",
       type: "address",
     },
     {
       indexed: false,
       internalType: "address",
       name: "pair",
       type: "address",
     },
     {
       indexed: false,
       internalType: "uint256",
       name: "test",
       type: "uint256",
     },
   ],
   name: "PairCreated",
   type: "event",
 },
 limit: 500000,
 tableName: "UniPairCreated",
 sync_historical: false,
};

Moralis.Cloud.run("watchContractEvent", options, { useMasterKey: true });

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