跳至主要内容

協助翻譯本頁面

🌏

由於尚未翻譯,本頁面內容以英文顯示。協助我們翻譯內容。

翻譯本頁面

這裡沒有漏洞!🐛

此頁面未翻譯,目前特意維持英文原文。

Logging data from smart contracts with events

smart contracts
remix
solidity
events
Intermediate
✍jdourlens
📚EthereumDev
📆2020年4月3日
⏱️2 minute read
Tip author 0x19dE91Af973F404EDF5B4c093983a7c6E3EC8ccE

In Solidity, events are dispatched signals the smart contracts can fire. Dapps, or anything connected to Ethereum JSON-RPC API, can listen to these events and act accordingly. An event can also be indexed so that the event history is searchable later.

Events

The most common event on the Ethereum blockchain at the time of writing this article is the Transfer event that is emitted by ERC20 tokens when someone transfers tokens.

1event Transfer(address indexed from, address indexed to, uint256 value);
2
📋 複製

The event signature is declared inside of the contract code and can be emitted with the emit keyword. For example, the transfer event logs who sent the transfer (from), to who (to) and how much tokens were transferred (value).

If we get back to our Counter smart contract and decide to log every time the value is changed. As this contract is not meant to be deployed but serve as a base for building another contract by extending it: it’s called an abstract contract. In the case of our counter example, it would look like this:

1pragma solidity 0.5.17;
2
3contract Counter {
4
5 event ValueChanged(uint oldValue, uint256 newValue);
6
7 // Private variable of type unsigned int to keep the number of counts
8 uint256 private count = 0;
9
10 // Function that increments our counter
11 function increment() public {
12 count += 1;
13 emit ValueChanged(count - 1, count);
14 }
15
16 // Getter to get the count value
17 function getCount() public view returns (uint256) {
18 return count;
19 }
20
21}
22
顯示全部
📋 複製

Notice that:

  • Line 5: we declare our event and what it contains, the old value and the new value.

  • Line 13: When we increment our count variable, we emit the event.

If we now deploy the contract and call the increment function, we’ll see that Remix will automatically display it if you click on the new transaction inside an array named logs.

Remix screenshot

Logs are really useful for debugging your smart contracts but they are also important if you build applications used by different people and make it easier to make analytics to track and understand how your smart contract is used. The logs generated by transactions are displayed in popular block explorers and you can also for example use them to create off chain scripts for listening to specific events and taking action when they occur.

最後編輯: , Invalid DateTime
編輯頁面

這個頁面對您有幫助嗎?

網站上次更新: 2022年10月4日

使用以太坊

  • 尋找錢包
  • 取得以太幣
  • 去中心化應用程式 (dapp)
  • 第二層
  • 執行節點
  • 穩定幣
  • Stake ETH

生態系統

  • 社群中心
  • 以太坊基金會
  • 以太坊基金會部落格
  • 生態系統支援計畫
  • 以太坊漏洞懸賞計畫
  • 生態系統獎助金計畫
  • 以太坊品牌資產
  • Devcon