Solidity
如何在松露控制台中獲取所有已發出事件的列表?
我寫了一個非常簡單的智能合約,每次我呼叫它的一個函式時都會發出一個事件:
pragma solidity ^0.8.0; contract MyContract { event Score( uint date, string player, string team ); function goalScored(string memory _player, string memory _team) external { emit Score(block.timestamp, _player, _team); } }
然後我使用
truffle migrate
. 最後我在truffle console
. 為此,我使用以下程式碼行載入契約:MyContract.deployed().then(function(i) { contract=i;}) contract.goalScored('messi','inter')
基本上每次梅西對一支球隊得分時,我都會啟動函式來發出一個得分事件。
這是我的問題:如何視覺化 truffle 控制台中所有事件的列表?
我嘗試了什麼:我使用不同的輸入執行了*goalScored()*函式 4 次,然後我嘗試使用以下命令:
contract.allEvents()
但我得到的只是:
EventEmitter { _events: [Object: null prototype] {}, _eventsCount: 0, _maxListeners: undefined, [Symbol(kCapture)]: false } truffle(development)> Uncaught [Error: The current provider doesn't support subscriptions: HttpProvider] { domainEmitter: EventEmitter { _events: [Object: null prototype] {}, _eventsCount: 0, _maxListeners: undefined, [Symbol(kCapture)]: false }, domainThrown: false }
您能否提出一種聰明而優雅的方式來實現我的目標?
從松露開發你可以嘗試類似
let c = await MyContract.deployed() await c.goalScored('a','b') let events = await c.getPastEvents('Score',{ fromBlock:0, toBlock:'latest'}) events
此外,如果您需要所有事件,您可以使用
c.getPastEvents('allEvents',{ fromBlock:0, toBlock:'latest'})
全松露開發輸入:
migrate let c = await Messi.deployed() await c.goalScored('first','inter') await c.getPastEvents('allEvents',{fromBlock:0})
範例輸出:
[ { logIndex: 0, transactionIndex: 0, transactionHash: '0x3b09d2d01dd03c5bea61e84cc43529b9676a0be8d895b780aee00a42a7c0971d', blockHash: '0x05cfc5a9204adb909dd4870ceb39c2376fc894fe06a8d6491888041bc91e1810', blockNumber: 5, address: '0x8D595a50a2F4cA295784fC2FFde8De6EE3346ca6', type: 'mined', id: 'log_fda64066', returnValues: Result { '0': '1633018291', '1': 'first', '2': 'inter', date: '1633018291', player: 'first', team: 'inter' }, event: 'Score', signature: '0xba74004ad4978cd3d2ecfe8c15e7c5f91bd7da14e199e9ae8638f20f378a7293', raw: { data: '0x000000000000000000000000000000000000000000000000000000006155e1b3000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000566697273740000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005696e746572000000000000000000000000000000000000000000000000000000', topics: [Array] }, args: Result { '0': [BN], '1': 'first', '2': 'inter', __length__: 3, date: [BN], player: 'first', team: 'inter' } }]