Skip to content

Commit

Permalink
Handle exception when getting block timestamp (#792)
Browse files Browse the repository at this point in the history
* Handle exception when getting block timestamp

* Return 0 on error

* Test error handling

* Prettier naming

* Fix order

* Fix test
  • Loading branch information
trizin authored Jan 17, 2024
1 parent 55b6d47 commit f8ed89e
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
6 changes: 5 additions & 1 deletion df_py/util/blocktime.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,11 @@ def __init__(self, target_timestamp):
self.target_timestamp = target_timestamp

def timeSinceTimestamp(self, block_i):
block_timestamp = web3.eth.get_block(int(block_i)).timestamp
try:
block_timestamp = web3.eth.get_block(int(block_i)).timestamp
except Exception as e:
print(f"An exception occurred while getting block {block_i}, {e}")
return 0
return block_timestamp - self.target_timestamp

f = C(timestamp).timeSinceTimestamp
Expand Down
26 changes: 26 additions & 0 deletions df_py/util/test/test_blocktime_eth_mainnet.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import random
from datetime import datetime

from enforce_typing import enforce_types
Expand Down Expand Up @@ -28,6 +29,31 @@ def test_eth_timestamp_to_block(monkeypatch):
assert guess == approx(block, 10)


@enforce_types
def test_eth_timestamp_to_block_error_handling(monkeypatch):
monkeypatch.setenv("WEB3_INFURA_PROJECT_ID", "9aa3d95b3bc440fa88ea12eaa4456161")
monkeypatch.setenv("MAINNET_RPC_URL", "https://mainnet.infura.io/v3/")
monkeypatch.setenv("INFURA_NETWORKS", "mainnet")
web3 = get_web3(get_rpc_url("mainnet"))
_get_block = web3.eth.get_block

def random_error_get_block(number):
if random.randint(1, 6) == 1 and number != "latest":
raise Exception("Random error occurred!")
return _get_block(number)

current_block = web3.eth.get_block("latest").number
blocks_ago = web3.eth.get_block(current_block - 5000)

ts = blocks_ago.timestamp
block = blocks_ago.number

web3.eth.get_block = random_error_get_block
guess = eth_timestamp_to_block(web3, ts)

assert guess == approx(block, 10)


def test_timestr_to_block_eth_1(monkeypatch):
monkeypatch.setenv("WEB3_INFURA_PROJECT_ID", "9aa3d95b3bc440fa88ea12eaa4456161")
monkeypatch.setenv("MAINNET_RPC_URL", "https://mainnet.infura.io/v3/")
Expand Down

0 comments on commit f8ed89e

Please sign in to comment.