Skip to content

Commit

Permalink
Merge pull request #742 from eth-brownie/feat-block-iter
Browse files Browse the repository at this point in the history
Block iterator
  • Loading branch information
iamdefinitelyahuman authored Sep 7, 2020
2 parents 00cd214 + 2ccb7c8 commit e6b6183
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
32 changes: 32 additions & 0 deletions brownie/network/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,38 @@ def __getitem__(self, block_number: int) -> BlockData:
self._block_gas_time = block["timestamp"]
return block

def new_blocks(self, height_buffer: int = 0, poll_interval: int = 5) -> Iterator:
"""
Generator for iterating over new blocks.
Arguments
---------
height_buffer : int, optional
The number of blocks behind "latest" to return. A higher value means
more delayed results but less likelihood of uncles.
poll_interval : int, optional
Maximum interval between querying for a new block, if the height has
not changed. Set this lower to detect uncles more frequently.
"""
if height_buffer < 0:
raise ValueError("Buffer cannot be negative")

last_block = None
last_height = 0
last_poll = 0.0

while True:
if last_poll + poll_interval < time.time() or last_height != web3.eth.blockNumber:
last_height = web3.eth.blockNumber
block = web3.eth.getBlock(last_height - height_buffer)
last_poll = time.time()

if block != last_block:
last_block = block
yield last_block
else:
time.sleep(1)

@property
def height(self) -> int:
return web3.eth.blockNumber
Expand Down
16 changes: 16 additions & 0 deletions docs/api-network.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1619,6 +1619,22 @@ Chain Methods
>>> chain.get_transaction(0xf598d43ef34a48478f3bb0ad969c6735f416902c4eb1eb18ebebe0fca786105e)
<Transaction '0xf598d43ef34a48478f3bb0ad969c6735f416902c4eb1eb18ebebe0fca786105e'>
.. py:method:: Chain.new_blocks(height_buffer, poll_interval)
Generator for iterating over new blocks.

``height_buffer``: The number of blocks behind "latest" to return. A higher value means more delayed results but less likelihood of uncles.
``poll_interval``: Maximum interval between querying for a new block, if the height has not changed. Set this lower to detect uncles more frequently.

.. code-block:: python
count = 0
for block in chain.new_blocks():
print(block.number)
count += 1
if count == 5:
break
.. py:method:: Chain.time()
Return the current epoch time in the RPC as an integer.
Expand Down

0 comments on commit e6b6183

Please sign in to comment.