header-langage
简体中文
繁體中文
English
Tiếng Việt
Scan to Download the APP
Partnered With:

Introduction to Solidity | Lecture 12: Events

Read this article in 5 Minutes
This article uses the transfer of ERC20 tokens as an example to illustrate events in solidity.
原文标题:《 Solidity 极简入门: 12. 事件 》
Original author: 0xA&NBsp;    


I have been reworking solidity to consolidate the details and also writing a "Solidity Minimalism Primer" for nerds (find another tutorial for programmers) with weekly updates of 1-3 sessions.


All code open source in making: github.com/AmazingAng/WTFSolidity


In this session we use the transfer of ERC20 Token as an example to illustrate solidity events.


The event


Events in Solidity are abstractions of logs on EVM and have two characteristics:


Response: The application (ether.js) can subscribe to and listen to these events through the RPC interface and respond in the front end.


Economy: Events are a relatively economical way to store data on EVM, each consuming approximately 2,000-5,000  Gas range. By comparison, storing a new variable requires at least 20,000  Gas.


The rules


事件的声明由 event 关键字开头,然后跟事件名称,括号里面写好事件需要记录的变量类型和变量名。以 ERC20 Token 合约的 Transfer 事件为例:



我们可以看到,Transfer 事件共记录了 3 个变量 from,to 和 value,分别对应 Token 的转账地址,接收地址和转账数量。同时 from 和 to 前面带着 indexed 关键字,表示很重要,程序可以轻松的筛选出特定转账地址和接收地址的转账事件。每个事件最多有 3 个带 indexed 的变量。


We can release events in functions. In the following example, each time a Transfer operation is performed using the _transfer() function, the Transfer event is released and the corresponding variables are recorded.



Query for events on EtherScan


我们尝试用_transfer() 函数在 Rinkeby 测试网络上转账 100 Token ,可以在 etherscan 上查询到相应的 tx:https://rinkeby.etherscan.io/tx/0x8cf87215b23055896d93004112bbd8ab754f081b4491cb48c37592ca8f8a36c7

Click the Logs button to see the event details:


The Event details


Topics has three elements in Topics, [0] is the hash of the event, [1] and [2] are the information of the two indexed variables we defined, that is, the forwarding address and receiving address of the transfer. Data contains the remaining variable without indexed, which is the amount of transfer.


conclusion


In this tutorial we show you how to use and query events in Solidity. Many on-chain Analysis tools, including Nansen and Dune Analysis, work based on events.


The original link


Welcome to join the official BlockBeats community:

Telegram Subscription Group: https://t.me/theblockbeats

Telegram Discussion Group: https://t.me/BlockBeats_App

Official Twitter Account: https://twitter.com/BlockBeatsAsia

举报 Correction/Report
Choose Library
Add Library
Cancel
Finish
Add Library
Visible to myself only
Public
Save
Correction/Report
Submit