pon*_*lot 5 javascript onflow-cadence onflow-fcl
我使用了一些服务来监听以太坊上智能合约中的事件。但我找不到任何与使用 Flow Blockchain 时类似的文档。我怎样才能做到这一点?
小智 3
对于一项常见任务来说,这是一个非常好的问题!
@onflow/fcl包为您提供了一个有用的方法events
,可用于“订阅”特定事件。您可以在 Flow Docs 站点上查看事件描述。或者您可以复制/粘贴下面的代码并使用它:
import * as fcl from "@onflow/fcl";
// We need to point FCL to some access node.
// We will use Mainnet REST endpoint for this, as the contract
// we want to listen to is deployed there
fcl.config({
"accessNode.api": "https://rest-mainnet.onflow.org",
// we will set the poll rate for events to 3 seconds
"fcl.eventPollRate": 3000
});
// FlowFees is the most active contract, since every transaction will
// trigger "FeesDeducted" event, so it will be easier to see that our code
// is working correctly
const contractAddress = "f919ee77447b7497";
const contractName = "FlowFees";
const eventName = "FeesDeducted";
// Event name consist of 2 or 4 parts
// 2 part event name have only system events
// For deployed contract, event should be constructed from 4 parts
// - "A" prefix, stands for "account"
// - address where contract, holding definition of event is deployed
// - contract name
// - event name
const event = `A.${contractAddress}.${contractName}.${eventName}`;
console.log(
`Listening for event "${eventName}" from "${contractName}" deployed on account 0x${contractAddress}`
);
fcl.events(event).subscribe((eventData) => {
console.log(eventData);
});
Run Code Online (Sandbox Code Playgroud)
您还可以尝试使用Codesandbox 示例