1. event 的作用
event 事件 非常重要,可以让我们方便的访问EVM的日志,他是合约与外部沟通的桥梁。
例如,我们发送交易来调用某个合约,交易的处理是需要时间的,我们无法立即获得返回值,交易打包后,事件才真正发生,我们的前端就可以通过监听事件进行响应处理。
2. 示例
(1)创建项目
mkdir event_test
cd evnet_test
# 初始化
truffle init
# 安装 web3
npm install --save [email protected]
启动 Ganache,修改配置文件 truffle.js:
module.exports = {
networks: {
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*"
}
}
};
(2)合约代码
contracts/Coursetro.sol
pragma solidity ^0.4.22;
contract Coursetro {
string fName;
uint age;
event Instructor(
string name,
uint age);
function setInstructor(string _fName, uint _age) public {
fName = _fName;
age = _age;
emit Instructor(_fName, _age);
}
function getInstructor() view public returns (string, uint) {
return (fName, age);
}
}
(3)编译发布
迁移脚本 migrations/2_deploy_Coursetro.js
var Coursetro = artifacts.require("Coursetro");
module.exports = function(deployer) {
deployer.deploy(Coursetro);
};
truffle compile
truffle migrate # 输出信息中会有合约ID,需要记住
(4)测试代码
test/test.js
var Web3 = require("web3");
var web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider("http://localhost:7545"));
web3.eth.defaultAccount = web3.eth.accounts[0];
// 合约的ABI,在 build/Coursetro.json 中
var abi = [{"anonymous":false,"inputs":[{"indexed":false,"name":"name","type":"string"},{"indexed":false,"name":"age","type":"uint256"}],"name":"Instructor","type":"event"},{"constant":false,"inputs":[{"name":"_fName","type":"string"},{"name":"_age","type":"uint256"}],"name":"setInstructor","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getInstructor","outputs":[{"name":"","type":"string"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}];
var CoursetroContract = web3.eth.contract(abi);
// 合约ID,执行迁移命令的输出信息中有,Ganache 交易列表中也可以找到
var contractId = '0xDF32B5BAC77C2998587E81F787667B869fd06190';
var Coursetro = CoursetroContract.at(contractId);
var instructorEvent = Coursetro.Instructor();
instructorEvent.watch(function(error, result) {
if (!error) {
// 查看业务信息
console.info(result.args.name + ' (' + result.args.age + ' years old)');
// 查看全部信息
console.info(result);
} else {
console.log(error);
}
});
Coursetro.setInstructor("gates", "28");
(5)运行
$ node test/test.js
gates (28 years old)
{ logIndex: 0,
transactionIndex: 0,
transactionHash: '0x9867ac98df022d6a2c40eb101904a018b0069c1b06892144dd1cef98bb0d4721',
blockHash: '0x6ca8abf99dc5295d5a742998c901372c3772499e77a371d7ebb2fc2b1fd41f14',
blockNumber: 18,
address: '0xa50246a6e751aeed6c0c101bb89e9890dd493908',
type: 'mined',
event: 'Instructor',
args: { name: 'gates', age: BigNumber { s: 1, e: 1, c: [Array] } } }
Web3 Event 文档