事件是合约外部通知,在logs中查看。一般用于dapp监听使用。
事件在合约中可被继承。当他们被调用时,会使参数被存储到交易的日志中 —— 一种区块链中的特殊数据结构。
成本较低
event Set(uint value);
emit Set(x); //触发事件
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract EventTest {
event LogEvent(string indexed a, uint8 b);
event TestEvent(string a);
function eventFunction() public{
emit LogEvent("hello", 101);
}
function test() public{
emit TestEvent("world");
}
function getSig() public pure returns(bytes32, bytes32){
bytes32 r1 = keccak256("TestEvent(string)"); //事件topic的值
bytes32 r2 = keccak256("LogEvent(string,uint8)");
return(r1, r2);
}
}
其中 keccak256("TestEvent(string)"),即事件的签名,也是事件topic的值。
//logs-LogEvent
{
"from": "0xa514f9ce4ceed99e4731b437123073f2d0c1745c",
"topic": "0x449e54c0703954de7e4a92b7f921b71b2574e355474bdcfe8461f34d63e1e542",
"event": "LogEvent",
"args": {
"0": {
"hash": "0x1c8aff950685c2ed4bc3174f3472287b56d9517b9c948127319a09a7a36deac8",
"type": "Indexed"
},
"1": 101,
"a": {
"hash": "0x1c8aff950685c2ed4bc3174f3472287b56d9517b9c948127319a09a7a36deac8",
"type": "Indexed"
},
"b": 101,
"length": 2
}
}
//logs-TestEvent
{
"from": "0xa514f9ce4ceed99e4731b437123073f2d0c1745c",
"topic": "0xe75028ff36bb6473da3731a30e1aeeae9988e2415dba2c4e91e0357955065fba",
"event": "TestEvent",
"args": {
"0": "world",
"a": "world",
"length": 1
}
}
RE: Solidity开发指南