我如何从流区块链上的智能合约中侦听事件?



我使用了一些服务来侦听以太坊智能合约中的事件。但我找不到任何类似的文件,当与流动区块链工作。我该怎么做呢?

对于一个常见的任务,这是一个非常好的问题!@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);
});

你也可以试着玩一下Codesandbox的工作示例

有多种方法可以做到这一点。我认为最简单的方法是使用服务。我们目前在.find中使用的是https://graffle.io.

您也可以使用其中一个sdk制作自己的sdk。Kitty-items在javascript中有一个https://github.com/onflow/kitty-items/的例子。

如果你喜欢golang我有一些事件获取代码在溢出https://github.com/bjartek/overflow/blob/main/overflow/event.go。下面是一个如何使用它的例子:https://github.com/bjartek/overflow/blob/main/overflow/event_integration_test.go#L13

最新更新