2

Say I have a contract that emits multiple events, how do I to get a list of all events emitted in brownie and sort them by event type?

contract SimpleContract {
  
  event Deposit(address indexed _from, bytes32 indexed _id, uint _value);
  event Withdraw(address indexed _to, bytes32 indexed _id, uint _value);

  function deposit(bytes32 _id) external {
    emit Deposit(msg.sender, _id, msg.value);
  }

  function withdraw(bytes32 _id, uint value) external {
    emit Withdraw(msg.sender, _id, value);
  }
}

2 Answers 2

3

When calling a function (creating a transaction) you can check that transactions events with the events attribute.

simple_contract = SimpleContract.deploy({"from": account})
tx = simple_contract.deposit(bytes_arg, {"from": account})
print(tx.events)
print(tx.events[0]["Deposit"])
1
  • But what if I dont have the tx? what if I just wanna monitor a specific contract for incoming events in general?
    – J3STER
    Commented Feb 3, 2023 at 15:15
0

In addition to being able to access the events of a transaction, one can also use the deployed contract's events attribute.

get_sequence takes a block range and optionally an event type and returns event data from that block range:

    from brownie import SimpleContract, accounts
    from hexbytes import HexBytes
    
    
    def main():
        account = accounts[0]
        contract = SimpleContract.deploy({"from": account})
        contract.deposit(HexBytes(0x0), {"from": account, "value": 10**18})
        events = contract.events.get_sequence(
            from_block=0, to_block=100, event_type="Deposit"
        )
        print(dict(events[0]))

Output:

{'args': AttributeDict({'_from': '0xEaCB93242793B013Ec51D672bBEF3Ee2b95A081B', '_id': b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', '_value': 1000000000000000000}),
    'event': 'Deposit',
    'logIndex': 0,
    'transactionIndex': 0,
    'transactionHash': HexBytes('0x9d5a21d9011cbbb3978e78c8e9d158237ce4a7a4f3f69acb5bccf44e7345a10b'),
    'address': '0xa0e9a03Bf2243Bbe0f62c851888A9308D722fbEe',
    'blockHash': HexBytes('0xbe36423466db6bf34e73f8ec6eeae076a4197aa36f97b98f1f71ba68d110c38d'),
    'blockNumber': 14}

And subscribe lets one pass a callback for when the event fires:

   contract.events.subscribe(
        "Withdraw",
        lambda event: print(f"{event['event']} at block {event['blockNumber']}"),
        delay=8,
    )

And listen returns a coroutine which resolves to the event object and a timeout bool.

   co = contract.events.listen("Withdraw",timeout = 20)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.