Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Revert web3py 7 #125

Merged
merged 2 commits into from
Nov 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/release.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ name: Release

on:
release:
types: [released]
types: [published]

jobs:
checks:
Expand Down
3,093 changes: 1,464 additions & 1,629 deletions poetry.lock

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "sw-utils"
version = "v0.6.28"
version = "v0.6.29"
description = "StakeWise Python utils"
authors = ["StakeWise Labs <[email protected]>"]
license = "GPL-3.0-or-later"
Expand All @@ -9,12 +9,12 @@ readme = "README.md"
[tool.poetry.dependencies]
python = "^3.10"
sw-milagro-bls-binding = "==1.9.0"
py-ecc = "^6.0.0"
ipfshttpclient = "^0.8.0a2"
web3 = "==6.15.1"
tenacity = "==8.2.3"
pyjwt = "==2.8.0"
ssz = "==0.5.0"
web3 = "==7.4.0"
py-ecc = "^7.0.1"

[tool.poetry.group.dev.dependencies]
pylint = "^3.0.1"
Expand Down
25 changes: 10 additions & 15 deletions sw_utils/consensus.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import logging
from enum import Enum
from typing import TYPE_CHECKING, Any, Optional, Sequence
from typing import TYPE_CHECKING, Any, Sequence

import aiohttp
from aiohttp import ClientResponseError
from eth_typing import URI, BlockNumber, HexStr
from web3 import AsyncWeb3, Web3
from web3._utils.request import async_json_make_get_request
from web3.beacon import AsyncBeacon
from web3.beacon.api_endpoints import GET_VOLUNTARY_EXITS
from web3.exceptions import BlockNotFound
Expand Down Expand Up @@ -64,12 +65,12 @@ class ExtendedAsyncBeacon(AsyncBeacon):
def __init__(
self,
base_urls: list[str],
request_timeout: int = 60,
timeout: int = 60,
retry_timeout: int = 0,
log_uri_max_len: int | None = None,
) -> None:
self.base_urls = base_urls
self.request_timeout = request_timeout
self.timeout = timeout
self.retry_timeout = retry_timeout
self.log_uri_max_len = log_uri_max_len or 100
super().__init__('') # hack origin base_url param
Expand Down Expand Up @@ -122,9 +123,7 @@ async def get_consensus_fork(self, state_id: str = 'head') -> ConsensusFork:
epoch=int(fork_data['epoch']),
)

async def _async_make_get_request(
self, endpoint_uri: str, params: Optional[dict[str, str]] = None
) -> dict[str, Any]:
async def _async_make_get_request(self, endpoint_uri: str) -> dict[str, Any]:
if self.retry_timeout:

def custom_before_log(retry_state: 'RetryCallState') -> None:
Expand All @@ -138,9 +137,9 @@ def custom_before_log(retry_state: 'RetryCallState') -> None:
self.retry_timeout,
before=custom_before_log,
)
return await retry_decorator(self._async_make_get_request_inner)(endpoint_uri, params)
return await retry_decorator(self._async_make_get_request_inner)(endpoint_uri)

return await self._async_make_get_request_inner(endpoint_uri, params)
return await self._async_make_get_request_inner(endpoint_uri)

async def _async_make_post_request(
self, endpoint_uri: str, data: list | dict
Expand Down Expand Up @@ -172,15 +171,11 @@ def _format_uri(self, uri: str) -> str:

return f'{uri[:max_len]}...'

async def _async_make_get_request_inner(
self, endpoint_uri: str, params: Optional[dict[str, str]]
) -> dict[str, Any]:
async def _async_make_get_request_inner(self, endpoint_uri: str) -> dict[str, Any]:
for i, url in enumerate(self.base_urls):
try:
uri = URI(urljoin(url, endpoint_uri))
return await self._request_session_manager.async_json_make_get_request(
uri, params=params, timeout=aiohttp.ClientTimeout(self.request_timeout)
)
return await async_json_make_get_request(uri, timeout=self.timeout)

except Exception as error:
if not can_be_retried_aiohttp_error(error):
Expand All @@ -204,7 +199,7 @@ def get_consensus_client(
) -> ExtendedAsyncBeacon:
return ExtendedAsyncBeacon(
base_urls=endpoints,
request_timeout=timeout,
timeout=timeout,
retry_timeout=retry_timeout,
log_uri_max_len=log_uri_max_len,
)
Expand Down
35 changes: 16 additions & 19 deletions sw_utils/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@
from eth_typing import URI
from web3 import AsyncWeb3
from web3.eth import AsyncEth
from web3.middleware import async_geth_poa_middleware, async_simple_cache_middleware
from web3.net import AsyncNet
from web3.providers.rpc.async_rpc import AsyncHTTPProvider
from web3.types import RPCEndpoint, RPCResponse
from web3.providers.async_rpc import AsyncHTTPProvider
from web3.types import AsyncMiddleware, RPCEndpoint, RPCResponse

from sw_utils.decorators import can_be_retried_aiohttp_error, retry_aiohttp_errors

Expand All @@ -36,12 +37,14 @@ class ExtendedAsyncHTTPProvider(AsyncHTTPProvider):
_providers: list[AsyncHTTPProvider] = []
_locker_provider: AsyncHTTPProvider | None = None

# Turn off `async_http_retry_request_middleware`
_middlewares: tuple[AsyncMiddleware, ...] = ()

def __init__(
self,
endpoint_urls: list[str],
request_kwargs: Any | None = None,
retry_timeout: int = 0,
use_cache: bool = True,
):
self._endpoint_urls = endpoint_urls
self._providers = []
Expand All @@ -52,14 +55,7 @@ def __init__(

for host_uri in endpoint_urls:
if host_uri.startswith('http'):
self._providers.append(
AsyncHTTPProvider(
host_uri,
request_kwargs,
retry_configuration=None, # disable built-in retries
cache_allowed_requests=use_cache,
)
)
self._providers.append(AsyncHTTPProvider(host_uri, request_kwargs))
else:
protocol = host_uri.split('://')[0]
raise ProtocolNotSupported(f'Protocol "{protocol}" is not supported.')
Expand Down Expand Up @@ -116,16 +112,11 @@ def lock_endpoint(self, endpoint_uri: URI | str) -> Iterator:
def set_retry_timeout(self, retry_timeout: int) -> None:
self.retry_timeout = retry_timeout

async def connect(self) -> None:
raise NotImplementedError('Persistent connection providers must implement this method')

async def disconnect(self) -> None:
raise NotImplementedError('Persistent connection providers must implement this method')


# pylint: disable-next=too-many-arguments, too-many-positional-arguments
# pylint: disable-next=too-many-arguments
def get_execution_client(
endpoints: list[str],
is_poa: bool = False,
timeout: int = 60,
retry_timeout: int = 0,
use_cache: bool = True,
Expand All @@ -144,13 +135,19 @@ def get_execution_client(
endpoint_urls=endpoints,
request_kwargs={'timeout': timeout, 'headers': headers},
retry_timeout=retry_timeout,
use_cache=use_cache,
)
client = AsyncWeb3(
provider,
modules={'eth': (AsyncEth,), 'net': AsyncNet},
)

if is_poa:
client.middleware_onion.inject(async_geth_poa_middleware, layer=0)
logger.debug('Injected POA middleware')

if use_cache:
client.middleware_onion.add(async_simple_cache_middleware)

return client


Expand Down
2 changes: 1 addition & 1 deletion sw_utils/ipfs.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ async def _iter_pins(self) -> AsyncIterator[dict]:
page_number += 1
total_pages = pin_results['totalPages']

# pylint: disable-next=too-many-arguments, too-many-positional-arguments
# pylint: disable-next=too-many-arguments
async def _call(
self,
http_method: str,
Expand Down
5 changes: 5 additions & 0 deletions sw_utils/networks.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ class BaseNetworkConfig:
GNO_TOKEN_CONTRACT_ADDRESS: ChecksumAddress
GENESIS_VALIDATORS_IPFS_HASH: str
CHAIN_ID: int
IS_POA: bool
FAR_FUTURE_EPOCH: int
SHAPELLA_FORK_VERSION: bytes
SHAPELLA_EPOCH: int
Expand Down Expand Up @@ -100,6 +101,7 @@ def SHAPELLA_FORK(self) -> ConsensusFork:
GNO_TOKEN_CONTRACT_ADDRESS=Web3.to_checksum_address(EMPTY_ADDR_HEX),
GENESIS_VALIDATORS_IPFS_HASH='bafybeigzq2ntq5zw4tdym5vckbf66mla5q3ge2fzdgqslhckdytlmm7k7y',
CHAIN_ID=1,
IS_POA=False,
FAR_FUTURE_EPOCH=18446744073709551615,
SHAPELLA_FORK_VERSION=Web3.to_bytes(hexstr=HexStr('0x03000000')),
SHAPELLA_EPOCH=194048,
Expand Down Expand Up @@ -139,6 +141,7 @@ def SHAPELLA_FORK(self) -> ConsensusFork:
),
GENESIS_FORK_VERSION=Web3.to_bytes(hexstr=HexStr('0x01017000')),
CHAIN_ID=17000,
IS_POA=False,
FAR_FUTURE_EPOCH=18446744073709551615,
SHAPELLA_FORK_VERSION=Web3.to_bytes(hexstr=HexStr('0x04017000')),
SHAPELLA_EPOCH=256,
Expand Down Expand Up @@ -182,6 +185,7 @@ def SHAPELLA_FORK(self) -> ConsensusFork:
),
GENESIS_FORK_VERSION=Web3.to_bytes(hexstr=HexStr('0x00000064')),
CHAIN_ID=100,
IS_POA=False,
FAR_FUTURE_EPOCH=18446744073709551615,
SHAPELLA_FORK_VERSION=Web3.to_bytes(hexstr=HexStr('0x03000064')),
SHAPELLA_EPOCH=648704,
Expand Down Expand Up @@ -223,6 +227,7 @@ def SHAPELLA_FORK(self) -> ConsensusFork:
),
GENESIS_FORK_VERSION=Web3.to_bytes(hexstr=HexStr('0x0000006f')),
CHAIN_ID=10200,
IS_POA=False,
FAR_FUTURE_EPOCH=18446744073709551615,
SHAPELLA_FORK_VERSION=Web3.to_bytes(hexstr=HexStr('0x0300006f')),
SHAPELLA_EPOCH=244224,
Expand Down
2 changes: 1 addition & 1 deletion sw_utils/tests/factories.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def wei_amount(self, start: int = 10, stop: int = 1000) -> Wei:
faker.add_provider(Web3Provider)


# pylint: disable=too-many-arguments, too-many-positional-arguments
# pylint: disable=too-many-arguments
def get_mocked_protocol_config(
oracles: list[Oracle] | None = None,
oracles_count: int = 1,
Expand Down
Loading