- Solidity 教程
- Solidity - 首页
- Solidity - 概述
- Solidity - 环境设置
- Solidity - 基本语法
- Solidity - 第一个应用程序
- Solidity - 注释
- Solidity - 数据类型
- Solidity - 变量
- Solidity - 变量作用域
- Solidity - 运算符
- Solidity - 循环
- Solidity - 决策
- Solidity - 字符串
- Solidity - 数组
- Solidity - 枚举
- Solidity - 结构体
- Solidity - 映射
- Solidity - 类型转换
- Solidity - 以太坊单位
- Solidity - 特殊变量
- Solidity - 样式指南
- Solidity 函数
- Solidity - 函数
- Solidity - 函数修饰符
- Solidity - View 函数
- Solidity - Pure 函数
- Solidity - 回退函数
- 函数重载
- 数学函数
- 加密函数
- Solidity 常用模式
- Solidity - 提款模式
- Solidity - 限制访问
- Solidity 高级
- Solidity - 合约
- Solidity - 继承
- Solidity - 构造函数
- Solidity - 抽象合约
- Solidity - 接口
- Solidity - 库
- Solidity - 汇编
- Solidity - 事件
- Solidity - 错误处理
- Solidity 有用资源
- Solidity - 快速指南
- Solidity - 有用资源
- Solidity - 讨论
Solidity - 事件
事件是合约的可继承成员。当事件被触发时,它会将传递的参数存储在交易日志中。这些日志存储在区块链上,并且可以使用合约地址访问,直到合约存在于区块链上。生成的事件无法从合约内部访问,即使是创建和触发它们的合约也无法访问。
可以使用 event 关键字声明事件。
//Declare an Event event Deposit(address indexed _from, bytes32 indexed _id, uint _value); //Emit an event emit Deposit(msg.sender, _id, msg.value);
示例
尝试以下代码来了解事件如何在 Solidity 中工作。
首先创建一个合约并触发一个事件。
pragma solidity ^0.5.0;
contract Test {
event Deposit(address indexed _from, bytes32 indexed _id, uint _value);
function deposit(bytes32 _id) public payable {
emit Deposit(msg.sender, _id, msg.value);
}
}
然后在 JavaScript 代码中访问合约的事件。
var abi = /* abi as generated using compiler */;
var ClientReceipt = web3.eth.contract(abi);
var clientReceiptContract = ClientReceipt.at("0x1234...ab67" /* address */);
var event = clientReceiptContract.Deposit(function(error, result) {
if (!error)console.log(result);
});
它应该打印类似以下内容的详细信息 -
输出
{
"returnValues": {
"_from": "0x1111...FFFFCCCC",
"_id": "0x50...sd5adb20",
"_value": "0x420042"
},
"raw": {
"data": "0x7f...91385",
"topics": ["0xfd4...b4ead7", "0x7f...1a91385"]
}
}
广告