Skip to content

Commit

Permalink
feat: remove most bal_addresses deps
Browse files Browse the repository at this point in the history
  • Loading branch information
gosuto-inzasheru committed Jan 10, 2025
1 parent 7b974db commit 145d335
Show file tree
Hide file tree
Showing 5 changed files with 38 additions and 24 deletions.
17 changes: 13 additions & 4 deletions bal_tools/drpc.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
from web3 import Web3
from bal_addresses import AddrBook

DRPC_NAME_OVERRIDES = {
"mainnet": "ethereum",
"zkevm": "polygon-zkevm",
}


class Web3RpcByChain:
def __init__(self, DRPC_KEY):
self.DRPC_KEY = DRPC_KEY
Expand Down Expand Up @@ -41,16 +41,25 @@ def values(self):
def items(self):
return self._w3_by_chain.items()


class Web3Rpc:
def __init__(self, chain, DRPC_KEY):
drpc_chain = DRPC_NAME_OVERRIDES.get(chain, chain)
self.w3 = Web3(Web3.HTTPProvider(f"https://lb.drpc.org/ogrpc?network={drpc_chain}&dkey={DRPC_KEY}"))
self.w3 = Web3(
Web3.HTTPProvider(
f"https://lb.drpc.org/ogrpc?network={drpc_chain}&dkey={DRPC_KEY}"
)
)
if not self.w3.is_connected():
raise ConnectionError(f"Unable to connect to {drpc_chain} network with provided DRPC_KEY.")
raise ConnectionError(
f"Unable to connect to {drpc_chain} network with provided DRPC_KEY."
)
try:
self.w3.eth.block_number
except Exception as e:
raise ConnectionError(f"Error fetching latest block number: {e}, chain: {chain}, url: {self.w3.provider.endpoint_uri}")
raise ConnectionError(
f"Error fetching latest block number: {e}, chain: {chain}, url: {self.w3.provider.endpoint_uri}"
)

def __getattr__(self, name):
return getattr(self.w3, name)
22 changes: 12 additions & 10 deletions bal_tools/safe_tx_builder/safe_tx_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from bal_addresses import AddrBook

from .models import *
from ..utils import is_address
from ..utils import is_address, chain_ids_by_name


class SafeTxBuilder:
Expand All @@ -23,17 +23,17 @@ def __new__(
if cls._instance is None:
cls._instance = super(SafeTxBuilder, cls).__new__(cls)
cls._instance._initialized = False

if safe_address is not None or cls._last_config is None:
cls._last_config = {
'safe_address': safe_address,
'chain_name': chain_name,
'version': version,
'timestamp': timestamp,
'tx_builder_version': tx_builder_version
"safe_address": safe_address,
"chain_name": chain_name,
"version": version,
"timestamp": timestamp,
"tx_builder_version": tx_builder_version,
}
cls._instance._initialize(**cls._last_config)

return cls._instance

def _initialize(
Expand All @@ -45,8 +45,10 @@ def _initialize(
tx_builder_version: str,
):
self.chain_name = chain_name
self.chain_id = str(AddrBook.chain_ids_by_name[chain_name])
self.addr_book = AddrBook(AddrBook.chain_names_by_id[int(self.chain_id)]).flatbook
self.chain_id = str(chain_ids_by_name()[chain_name])
self.addr_book = AddrBook(
AddrBook.chain_names_by_id[int(self.chain_id)]
).flatbook
self.safe_address = self._resolve_address(safe_address)
self.version = version
self.timestamp = timestamp if timestamp else datetime.now(timezone.utc)
Expand Down
5 changes: 2 additions & 3 deletions bal_tools/subgraph.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,9 @@
from gql import Client, gql
from gql.transport.requests import RequestsHTTPTransport
from web3 import Web3
from bal_addresses import AddrBook

from typing import Union, List, Callable, Dict
from .utils import get_abi, flatten_nested_dict
from .utils import get_abi, flatten_nested_dict, chain_ids_by_name
from .models import *
from .errors import NoPricesFoundError

Expand All @@ -35,7 +34,7 @@

class Subgraph:
def __init__(self, chain: str = "mainnet", silence_warnings: bool = False):
if chain not in AddrBook.chain_ids_by_name.keys():
if chain not in chain_ids_by_name().keys():
raise ValueError(f"Invalid chain: {chain}")
self.chain = chain
self.subgraph_url = {}
Expand Down
11 changes: 9 additions & 2 deletions bal_tools/utils.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from web3 import Web3
from typing import Union, List, Dict
import json
import os
from importlib.resources import files

import requests


### These functions are to deal with differing web3 versions and the need to use 5.x for legacy brownie code
def to_checksum_address(address: str):
Expand All @@ -30,7 +31,13 @@ def flatten_nested_dict(d):
result = d.copy()
for key, value in list(result.items()):
if isinstance(value, dict):
if key not in ['dynamicData', 'staking']:
if key not in ["dynamicData", "staking"]:
result.pop(key)
result.update(value)
return result


def chain_ids_by_name():
chains_raw = "https://raw.githubusercontent.com/BalancerMaxis/bal_addresses/main/extras/chains.json"
chains = requests.get(chains_raw).json()
return chains["CHAIN_IDS_BY_NAME"]
7 changes: 2 additions & 5 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from bal_tools.subgraph import Subgraph
from bal_tools.ecosystem import Aura
from bal_tools.safe_tx_builder import SafeTxBuilder
from bal_tools.utils import chain_ids_by_name

from web3 import Web3
from dotenv import load_dotenv
Expand All @@ -15,11 +16,7 @@
load_dotenv()

exempt_chains = ["fantom", "goerli"]
chains = [
chain
for chain in list(AddrBook.chains["CHAIN_IDS_BY_NAME"])
if chain not in exempt_chains
]
chains = [chain for chain in list(chain_ids_by_name()) if chain not in exempt_chains]


@pytest.fixture(scope="module")
Expand Down

0 comments on commit 145d335

Please sign in to comment.