0Pricing
Blockchain Smart Contracts with Solidity · 课时

事件与日志数据

学习使用事件在区块链上记录信息,从而支持外部应用进行高效监控和索引。

事件与日志数据 是 CoddyKit 上的免费 Blockchain Smart Contracts with Solidity 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Blockchain Smart Contracts with Solidity 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Blockchain Smart Contracts with Solidity 课程共包含 4 节课。

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

What are Solidity Events?

Smart contracts often need to communicate with the outside world. This is where events come in!

Events are a special feature in Solidity that allow your smart contracts to publish information to the blockchain log.

Think of them as notifications that external applications can listen for.

The Power of Event Logs

Events are crucial because directly reading contract state from off-chain applications can be inefficient and costly.

  • Cost-Effective: Storing data in events is cheaper than storing it in contract state.
  • Indexable History: They provide a historical record of actions, easily searchable by off-chain tools.
  • Monitoring: Wallets, explorers, and dApps can "subscribe" to events to react to changes.

Defining Your First Event

Declaring an event is similar to defining a function, but you use the event keyword.

You specify a name for the event and a list of parameters it will carry, just like function arguments.

These parameters define the data that will be logged when the event is emitted.

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

contract EventExample {
    // Declares an event named 'LogMessage'
    // It takes a string and a number as parameters
    event LogMessage(string message, uint256 timestamp);
}

Triggering an Event

Once an event is declared, you can "trigger" it using the emit keyword within any function of your contract.

When emit is called, the event's data is recorded in the transaction's log, but not directly in the contract's storage.

This makes events a lightweight way to signal information.

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

contract EventExample {
    event LogMessage(string message, uint256 timestamp);

    function doSomethingAndLog(string memory _msg) public {
        // Emits the LogMessage event
        // current timestamp is block.timestamp
        emit LogMessage(_msg, block.timestamp);
    }
}

Making Events Searchable

You can add the indexed keyword to up to three event parameters. This makes them searchable and filterable by off-chain applications.

  • indexed parameters: Stored in a special part of the log called "topics."
  • Non-indexed parameters: Stored in the "data" part of the log.
  • Benefit: Off-chain tools can quickly find transactions related to specific indexed values.

Event with Indexed Parameters

Let's see how to declare and emit an event with an indexed parameter.

Notice how `sender` is marked `indexed`, making it easy to filter for all events from a specific address.

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

contract IndexedEventExample {
    event Transfer(address indexed from, address indexed to, uint256 amount);

    function transferTokens(address _to, uint256 _amount) public {
        // Imagine some transfer logic here
        // Then emit the event
        emit Transfer(msg.sender, _to, _amount);
    }
}

Logs are Not State

It's important to understand that event logs are not stored within the contract's state.

  • State: Data stored directly in the contract, readable by other contracts and functions. Expensive.
  • Logs: Part of the blockchain's transaction receipts. They are immutable and persistent, but not directly accessible by other contracts. Cheaper.

Events are primarily for off-chain consumption.

Practical Event Applications

Events are used everywhere in smart contracts. Here are some common applications:

  • Token Transfers: ERC-20 and ERC-721 standards heavily rely on `Transfer` and `Approval` events.
  • Ownership Changes: Notifying when a contract's owner is updated.
  • Data Updates: Signalling when important contract variables have changed.
  • User Interface Feedback: DApps listen for events to update UI in real-time.

Off-Chain Interaction

While Solidity contracts can't directly read events, off-chain applications (like web dApps) use web3 libraries (e.g., Web3.js, Ethers.js) to:

  • Filter Past Events: Query historical blockchain data for specific events.
  • Subscribe to New Events: Listen for events as they are emitted in real-time.

This enables powerful, responsive decentralized applications.

Event Concepts Check

Consider the following Solidity event declaration:

event UserRegistered(
    address indexed userAddress,
    string userName,
    uint256 indexed registrationTime
);

Which parameters are indexed and therefore easily searchable by off-chain tools?

Recap: Events & Logging

You've learned about the power of events in Solidity!

  • Events are emitted by contracts to log data on the blockchain.
  • They are crucial for off-chain monitoring, indexing, and dApp interaction.
  • Use the `event` keyword to declare and `emit` to trigger them.
  • `indexed` parameters make events easily searchable.

This mechanism is vital for building responsive and data-driven decentralized applications.

常见问题解答

「事件与日志数据」课时是免费的吗?

是的 — 「事件与日志数据」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Blockchain Smart Contracts with Solidity 课程的其余内容,请升级到 CoddyKit PRO。 Blockchain Smart Contracts with Solidity 课程共包含 4 节课。

「事件与日志数据」这节课中我会学到什么?

学习使用事件在区块链上记录信息,从而支持外部应用进行高效监控和索引。 你通过在浏览器中直接运行的动手代码来练习 Blockchain Smart Contracts with Solidity,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Blockchain Smart Contracts with Solidity 需要有经验吗?

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

「事件与日志数据」课时需要多长时间?

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

我能在这节 Blockchain Smart Contracts with Solidity 课中编写并运行代码吗?

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

此课程中的所有课时

  1. 状态变量与存储布局
  2. 映射与动态数组
  3. 事件与日志数据
  4. 存储槽与 Gas 优化
← 返回 Blockchain Smart Contracts with Solidity