web3js 以太坊 监听合约事件event

启动geth

./geth --datadir walker/ --miner.etherbase 0x15208e586d12e5c40c5865cbfdc0057827238e84 --mine --miner.threads 1 --http --http.vhosts "*" --http.addr 0.0.0.0 --http.port 8545 --rpccorsdomain "*" --http.api "db,eth,net,web3,personal,debug" 
--ws --ws.addr 0.0.0.0 --ws.port 8546 --ws.api "db,eth,net,web3,personal,debug"

启动console

./geth attach walker/geth.ipc

部署合约

var _myStr = "geely";
var greetingContract = web3.eth.contract([{"inputs":[{"internalType":"string","name":"_myStr","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"_str","type":"string"}],"name":"EventNewStr","type":"event"},{"constant":true,"inputs":[],"name":"getMystring","outputs":[{"internalType":"string","name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"string","name":"_myStr","type":"string"}],"name":"setMyString","outputs":[],"payable":true,"stateMutability":"payable","type":"function"}]);
var greeting = greetingContract.new(
   _myStr,
   {
     from: web3.eth.accounts[0], 
     data: '0x608060405234801561001057600080fd5b506040516105883803806105888339818101604052602081101561003357600080fd5b810190808051604051939291908464010000000082111561005357600080fd5b8382019150602082018581111561006957600080fd5b825186600182028301116401000000008211171561008657600080fd5b8083526020830192505050908051906020019080838360005b838110156100ba57808201518184015260208101905061009f565b50505050905090810190601f1680156100e75780820380516001836020036101000a031916815260200191505b50604052505050806000908051906020019061010492919061010b565b50506101b0565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061014c57805160ff191683800117855561017a565b8280016001018555821561017a579182015b8281111561017957825182559160200191906001019061015e565b5b509050610187919061018b565b5090565b6101ad91905b808211156101a9576000816000905550600101610191565b5090565b90565b6103c9806101bf6000396000f3fe6080604052600436106100295760003560e01c80637307a3491461002e57806382180568146100be575b600080fd5b34801561003a57600080fd5b50610043610179565b6040518080602001828103825283818151815260200191508051906020019080838360005b83811015610083578082015181840152602081019050610068565b50505050905090810190601f1680156100b05780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b610177600480360360208110156100d457600080fd5b81019080803590602001906401000000008111156100f157600080fd5b82018360208201111561010357600080fd5b8035906020019184600183028401116401000000008311171561012557600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f82011690508083019250505050505050919291929050505061021b565b005b606060008054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156102115780601f106101e657610100808354040283529160200191610211565b820191906000526020600020905b8154815290600101906020018083116101f457829003601f168201915b5050505050905090565b80600090805190602001906102319291906102ef565b507f72d7616f3edfa86157d7e5db9c93891f92331afc736663bf4da5e83712fa27ba600060405180806020018281038252838181546001816001161561010002031660029004815260200191508054600181600116156101000203166002900480156102de5780601f106102b3576101008083540402835291602001916102de565b820191906000526020600020905b8154815290600101906020018083116102c157829003601f168201915b50509250505060405180910390a150565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061033057805160ff191683800117855561035e565b8280016001018555821561035e579182015b8281111561035d578251825591602001919060010190610342565b5b50905061036b919061036f565b5090565b61039191905b8082111561038d576000816000905550600101610375565b5090565b9056fea265627a7a7231582020fc0760b3581a0f1960447fe09912384afeaf8c8ed98a16483b35a0cba725f964736f6c634300050d0032', 
     gas: '4700000'
   }, function (e, contract){
    console.log(e, contract);
    if (typeof contract.address !== 'undefined') {
         console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);
    }
 })

启动js

使用schedule持续的监听event

node event.js

event.js源码如下

const schedule =require("node-schedule");
const Web3     =require("web3");

const web3 = new Web3(new Web3.providers.WebsocketProvider("ws://localhost:8546"));

web3.eth.defaultAccount =web3.eth.accounts[0];

var abi = [{"inputs":[{"internalType":"string","name":"_myStr","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"_str","type":"string"}],"name":"EventNewStr","type":"event"},{"constant":true,"inputs":[],"name":"getMystring","outputs":[{"internalType":"string","name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"string","name":"_myStr","type":"string"}],"name":"setMyString","outputs":[],"payable":true,"stateMutability":"payable","type":"function"}];
var contractId ="0xafe5d688fe670cbe5fcda00c1c9faeff497f1eb2";
var greet =new web3.eth.Contract(abi,contractId);


// var myEvent = greet.events.EventNewStr({
//  filter:{},
//  fromBlock:0,
// },function(error,event){})
//      .on('data',function(event){
//          console.log(event);
//      })
//      .on("changed",function(event){
//          //
//      })
//      .on('error',console.error);



// var myEvent = greet.getPastEvents('allEvents',{fromBlock:0,toBlock: 4180} ,async (error, events) => {
//     for (const event of events){  
//      console.log( event)
//     }
// })


let PrintEvents = async (fromBlock, toBlock) =>{
    console.log('fromBlock:',fromBlock,'toBlock:',toBlock);
    var myEvent = greet.getPastEvents('allEvents',{
        fromBlock:fromBlock,
        toBlock: toBlock,
    },
        async (error, events) => {

            for (const event of events){  
                console.log(event)
            }
        })
 }
schedule.scheduleJob("5 * * * * *",async() => {
    var blockHeight = await web3.eth.getBlockNumber();
    console.log("schedule","blockHeight:",blockHeight);
    
    await PrintEvents(blockHeight-10,blockHeight);
})

合约源码为

pragma solidity ^0.5.12;

contract greeting {
    string myStr;
    event EventNewStr(string _str);
    
    constructor(string memory _myStr) public{
        myStr = _myStr;
    }
    
    function getMystring() view public returns (string memory){
        return myStr;
    }
    
    function setMyString(string memory _myStr)public payable{
        myStr =_myStr;
        emit EventNewStr(myStr);
    }
}  

发送交易

> greeting.setMyString.sendTransaction("walker from asa",{from:eth.accounts[0]})
"0xdb4603462bcf713218d1a4c3dd2e7ca74f730d1a18a53ace8eec5587c789f7bc"

获得event

{
  address: '0xaFE5d688Fe670cBE5Fcda00C1C9FAeff497f1eb2',
  blockNumber: 4343,
  transactionHash: '0xdb4603462bcf713218d1a4c3dd2e7ca74f730d1a18a53ace8eec5587c789f7bc',
  transactionIndex: 1,
  blockHash: '0x43c011eeddddd9d0258749e8503d226a0691a133c63145aa5062725af423c855',
  logIndex: 1,
  removed: false,
  id: 'log_38c57665',
  returnValues: Result { '0': 'walker from asa', _str: 'walker from asa' },
  event: 'EventNewStr',
  signature: '0x72d7616f3edfa86157d7e5db9c93891f92331afc736663bf4da5e83712fa27ba',
  raw: {
    data: '0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000f77616c6b65722066726f6d206173610000000000000000000000000000000000',
    topics: [
      '0x72d7616f3edfa86157d7e5db9c93891f92331afc736663bf4da5e83712fa27ba'
    ]
  }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,445评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,889评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,047评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,760评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,745评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,638评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,011评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,669评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,923评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,655评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,740评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,406评论 4 320
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,995评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,961评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,197评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,023评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,483评论 2 342

推荐阅读更多精彩内容