使用web3.js監聽以太坊智能合約event


傳送門: 柏鏈項目學院


使用web3.js監聽以太坊智能合約event



  當我們在前端頁面調用合約時發現有些數據不會立即返回,這時還需要再調用更新數據的函數。那么這樣的方法使用起來非常不便,監聽event就可以很好的解決這樣的問題,下面我們來看看如何監聽event。以下內容基於web3.js1.0版本,版本不同可能會代碼差異。

1. 修改geth啟動參數

  • 全部參數如下
geth --datadir ./data --networkid 15 --port 30303 --rpc --rpcaddr 0.0.0.0 --rpcport 8545 --rpcvhosts "*" --rpcapi 'db,net,eth,web3,personal' --rpccorsdomain "*" --ws --wsaddr "localhost" --wsport "8546" --wsorigins "*" --nat "any" --nodiscover --dev --dev.period 1 console 2> 1.log

  • 主要增加了下列參數
--ws --wsaddr "localhost" --wsport "8546" --wsorigins "*"

2. 在geth上部署map3合約

  • 合約代碼如下
pragma solidity ^0.4.24;

contract Map3 {
 
    mapping(string => string) map;
    
    event orderlog(string indexed action, string indexed key, string value);
    
    function getvalue(string key) public constant returns (string) {
        return map[key];
    }
    
    function setvalue(string key, string value) public {
        emit orderlog("setvalue haha", key, value);
        map[key] = value;
    }
}

3. 編寫用於監聽合約event的js代碼

  • map_event.js代碼如下
var Web3 = require("web3")

var web3;

if (typeof web3 !== 'undefined') {
    web3 = new Web3(web3.currentProvider);
} else {
    web3 = new Web3(new Web3.providers.WebsocketProvider("ws://127.0.0.1:8546"));
}
        
var contractAbi = [
        {
                "constant": false,
                "inputs": [
                        {
                                "name": "key",
                                "type": "string"
                        },
                        {
                                "name": "value",
                                "type": "string"
                        }
                ],
                "name": "setvalue",
                "outputs": [],
                "payable": false,
                "stateMutability": "nonpayable",
                "type": "function"
        },
        {
                "constant": true,
                "inputs": [
                        {
                                "name": "key",
                                "type": "string"
                        }
                ],
                "name": "getvalue",
                "outputs": [
                        {
                                "name": "",
                                "type": "string"
                        }
                ],
                "payable": false,
                "stateMutability": "view",
                "type": "function"
        },
        {
                "anonymous": false,
                "inputs": [
                        {
                                "indexed": true,
                                "name": "action",
                                "type": "string"
                        },
                        {
                                "indexed": true,
                                "name": "key",
                                "type": "string"
                        },
                        {
                                "indexed": false,
                                "name": "value",
                                "type": "string"
                        }
                ],
                "name": "orderlog",
                "type": "event"
        }
];

var contractaAddress = "0x31bd7af45b90811f23fa748fbf1940dc8b3d9dcb";
        
MyContract = new web3.eth.Contract(contractAbi, contractaAddress);
                //console.log(MyContract.events.orderlog);
        
var myEvent = MyContract.events.orderlog({
        filter:{},
        fromBlock: 0
}, function(error, event){})
        .on('data', function(event){
        console.log(event); // same results as the optional callback above
})
        .on('changed', function(event){
                    // remove event from local database
        })        
    .on('error', console.error);
    

/*
    MyContract.getPastEvents('allEvents', {
        filter: {},
        fromBlock: 0,
        toBlock: 'latest'
    }, function(error, events){ console.log(events); })
    .then(function(events){
        console.log(events) // same results as the optional callback above
    });
*/

4. 運行map_event.js監聽event

  • 方法如下
npm init -y
npm install web3 --save
node map_event.js

5. 調用map3合約中的setvalue函數觸發event

  • 在remix中調用setvalue時的監聽效果 事件監聽效果

當合約被調用時,前端頁面需要立即更新數據,監聽event就可以實現這樣的效果。

  • 全部代碼地址:https://github.com/zhenyuss/eth_event.git
  • Solidity Event是如何實現的:https://www.liangzl.com/get-article-detail-11825.html





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM