Smart contract development based on Ethereum Solidity (events & logs)

//声明版本号(程序中的版本号要和编译器版本号一致)
pragma solidity ^0.5.17;
//合约
contract EventTest
{

    //状态变量
    uint public Variable;

    //构造函数
    constructor() public
    {
        Variable = 100;
    }

    event ValueChanged(uint newValue);  //事件声明
    event Log(string, uint);

    //调用该函数,修改状态变量的值并触发事件
    function setValue(uint newValue) public 
    {
        Variable = newValue;
        emit ValueChanged(newValue);  //触发事件
        emit Log("New_Variable = ", newValue);  //记录日志
    }
    
}

(1) Events are used to record specific activities on the blockchain. The "emit ValueChanged(newValue);" statement is used to trigger the ValueChanged event (the event needs to be declared first).

① After the event is triggered, the corresponding log will be generated. The yellow box in the above picture is the log generated by the "emit ValueChanged(newValue);" statement, where "form" refers to the contract account that triggered the event.

②Events are mainly for external applications to monitor. External applications can monitor events to obtain notifications of specific activities in the contract.

(2) The function of the log is to record important information in the smart contract. The function of the "emit Log("New_Variable = ", newValue);" statement is to generate a log (it also needs to be declared first, ). The recorded log information can be viewed through the Ethereum blockchain browser or specific tools. Logs can be composed of data types such as strings and integers

(3) Triggering events and recording logs are actually the same thing.Use the keyword event when declaring, and use the keyword emit when triggering, but the purpose of the two is different. The event name is generally named according to the actual behavior, and the log is often declared as "Log" or "log".

Guess you like

Origin blog.csdn.net/Zevalin/article/details/134900916