0Pricing
Web3 & DApp Development Fundamentals · 课时

监听事件

订阅日志

监听事件 是 CoddyKit 上的免费 Web3 & DApp Development Fundamentals 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Web3 & DApp Development Fundamentals 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Web3 & DApp Development Fundamentals 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

What Are Events

Smart contracts emit events to log that something happened — a transfer, an approval, a vote. Events are written to the transaction's logs.

  • They are cheaper than storage.
  • Off-chain apps subscribe to them to stay in sync.

Events in the ABI

To decode events, ethers needs their definitions in the ABI:

const abi = [ "event Transfer(address indexed from, address indexed to, uint256 value)", ]; const contract = new ethers.Contract(address, abi, provider);

The indexed keyword marks fields you can filter on.

const abi = [
  "event Transfer(address indexed from, address indexed to, uint256 value)",
];
const contract = new ethers.Contract(address, abi, provider);

Listening Live

Subscribe to new events with on. The callback fires whenever the event is emitted:

contract.on("Transfer", (from, to, value, event) => { console.log(from, "->", to, value); });

This needs a provider that supports subscriptions, such as a WebSocket connection.

contract.on("Transfer", (from, to, value, event) => {
  console.log(from, "->", to, value);
});

WebSocket Providers

Live subscriptions work best over a persistent connection. Use a WebSocket provider:

const provider = new ethers.WebSocketProvider( "wss://mainnet.example-rpc.io/KEY" );

HTTP providers can poll for events but a WebSocket pushes them in real time.

const provider = new ethers.WebSocketProvider(
  "wss://mainnet.example-rpc.io/KEY"
);

Listening Once

If you only care about the first occurrence, use once:

contract.once("Approval", (owner, spender, value) => { console.log("First approval seen"); });

The listener automatically removes itself after firing a single time.

contract.once("Approval", (owner, spender, value) => {
  console.log("First approval seen");
});

Querying Past Events

To read historical events, use queryFilter over a block range:

const logs = await contract.queryFilter( "Transfer", 19000000, 19000100 ); for (const log of logs) { console.log(log.args.from, log.args.value); }

Each log exposes decoded args.

const logs = await contract.queryFilter(
  "Transfer",
  19000000,
  19000100
);
for (const log of logs) {
  console.log(log.args.from, log.args.value);
}

Filtering by Indexed Fields

Build a filter to match specific indexed values — for example transfers to one address:

const filter = contract.filters.Transfer(null, myAddress); const logs = await contract.queryFilter(filter);

Passing null means match any value for that position.

const filter = contract.filters.Transfer(null, myAddress);
const logs = await contract.queryFilter(filter);

Live Filtered Listening

You can also pass a filter to on to react only to relevant events:

const filter = contract.filters.Transfer(null, myAddress); contract.on(filter, (from, to, value) => { console.log("Received:", value); });

This avoids processing events you do not care about.

const filter = contract.filters.Transfer(null, myAddress);
contract.on(filter, (from, to, value) => {
  console.log("Received:", value);
});

Removing Listeners

Long-running apps should clean up listeners to avoid leaks:

contract.off("Transfer", myHandler); // or remove all listeners for an event contract.removeAllListeners("Transfer");

Always remove listeners when a component unmounts or a job finishes.

contract.off("Transfer", myHandler);
// or remove all listeners for an event
contract.removeAllListeners("Transfer");

Handling Reorgs

Recent events can be reverted if the chain reorganizes. For reliable indexing:

  • Wait several confirmations before treating an event as final.
  • Track the block number and re-process if a reorg is detected.

This keeps your off-chain database consistent with the chain.

Provider-Level Log Filters

You can also subscribe at the provider level without a contract instance, using a raw log filter by topic:

provider.on({ address: tokenAddress, topics: [ethers.id("Transfer(address,address,uint256)")], }, (log) => { console.log("Raw log:", log); });

This is lower-level but works across many contracts at once.

provider.on({
  address: tokenAddress,
  topics: [ethers.id("Transfer(address,address,uint256)")],
}, (log) => {
  console.log("Raw log:", log);
});

Quick Check

Test your understanding of event handling.

Recap

You learned to work with contract events.

  • Events log on-chain activity to transaction logs.
  • on subscribes live (best over a WebSocket provider); once fires a single time.
  • queryFilter reads historical events over a block range.
  • Build filters from indexed fields; pass null to match any.
  • Remove listeners to avoid leaks and wait for confirmations against reorgs.

常见问题解答

「监听事件」课时是免费的吗?

是的 — 「监听事件」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Web3 & DApp Development Fundamentals 课程的其余内容,请升级到 CoddyKit PRO。 Web3 & DApp Development Fundamentals 课程共包含 4 节课。

「监听事件」这节课中我会学到什么?

订阅日志 你通过在浏览器中直接运行的动手代码来练习 Web3 & DApp Development Fundamentals,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Web3 & DApp Development Fundamentals 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Web3 & DApp Development Fundamentals 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「监听事件」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Web3 & DApp Development Fundamentals 课中编写并运行代码吗?

能。每节 Web3 & DApp Development Fundamentals 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 连接到提供者
  2. 读取合约数据
  3. 发送交易
  4. 监听事件
← 返回 Web3 & DApp Development Fundamentals