官术网_书友最值得收藏!

  • Mastering Ethereum
  • Merunas Grincalaitis
  • 292字
  • 2021-06-24 15:01:06

Events

Events are a special type of function. Their purpose is to log data on the blockchain and actions that you want to retrieve at a later date. They can be subscribed to to receive an update whenever a new event is generated, almost in real time.

Essentially, you want them to keep a registry of the things that are happening inside your smart contract to later analyze them in order to fix bugs and to understand what happened if you need to read the past in an easy way.

Here's how you declare events inside your smart contract in Solidity:

pragma solidity 0.5.0
contract EventsExample {
event LogUserAddress(address userAddress);
function registerUser() public {
emit LogUserAddress(msg.sender);
}
}

In this example, you can see how an event is declared and emitted. When you declare your event, you have to decide the parameters that it will be able to receive; all of them are always optional, so you can omit them.

When you emit the event inside a function, you must make sure that they are of the right type. In the declaration, you can add a name for each parameter, or you can leave it with just the type, as follows:

event LogUserAddress(address);

It's good practice to name the parameters inside the event, to help others understand the purpose of each of those parameters.

You can also add an optional keyword called indexed. It's a modifier to the parameter of the event that allows you to search past events for that specific event. Think of indexed parameters as searchable entries in a database:

event LogUserAddress(address indexed userAddress);

Note that you must name the parameters that are indexed. Later you'll see how to retrieve those events and search for specific ones with web3.js.

主站蜘蛛池模板: 北宁市| 遵义市| 辽源市| 平舆县| 岳阳市| 亳州市| 霍城县| 巫山县| 阳泉市| 双柏县| 铅山县| 石台县| 神农架林区| 阳谷县| 新安县| 介休市| 亚东县| 无棣县| 曲周县| 扶沟县| 雷山县| 柞水县| 泰顺县| 鲁甸县| 临湘市| 呼玛县| 通城县| 通江县| 行唐县| 安义县| 敖汉旗| 璧山县| 两当县| 丹江口市| 葫芦岛市| 莱州市| 潍坊市| 武川县| 顺义区| 拜城县| 天柱县|