def deploy_contract(ethereum_client: EthereumClient, deployer_account: LocalAccount) -> EthereumTxSent: """ Deploy proxy factory contract :param ethereum_client: :param deployer_account: Ethereum Account :return: deployed contract address """ contract = get_multi_send_contract(ethereum_client.w3) tx = contract.constructor().buildTransaction( {"from": deployer_account.address}) tx_hash = ethereum_client.send_unsigned_transaction( tx, private_key=deployer_account.key) tx_receipt = ethereum_client.get_transaction_receipt(tx_hash, timeout=120) assert tx_receipt assert tx_receipt["status"] contract_address = tx_receipt["contractAddress"] logger.info( "Deployed and initialized Proxy Factory Contract=%s by %s", contract_address, deployer_account.address, ) return EthereumTxSent(tx_hash, tx, contract_address)
def __new__(cls): if not hasattr(cls, 'instance'): from django.conf import settings if settings.ETH_INTERNAL_NO_FILTER: cls.instance = InternalTxIndexerWithTraceBlock(EthereumClient(settings.ETHEREUM_TRACING_NODE_URL), block_process_limit=settings.ETH_INTERNAL_TXS_BLOCK_PROCESS_LIMIT) else: cls.instance = InternalTxIndexer(EthereumClient(settings.ETHEREUM_TRACING_NODE_URL), block_process_limit=settings.ETH_INTERNAL_TXS_BLOCK_PROCESS_LIMIT) return cls.instance
def _deploy_proxy_factory_contract(ethereum_client: EthereumClient, deployer_account: LocalAccount, contract: Contract) -> EthereumTxSent: tx = contract.constructor().buildTransaction({'from': deployer_account.address}) tx_hash = ethereum_client.send_unsigned_transaction(tx, private_key=deployer_account.key) tx_receipt = ethereum_client.get_transaction_receipt(tx_hash, timeout=120) assert tx_receipt assert tx_receipt['status'] contract_address = tx_receipt['contractAddress'] logger.info("Deployed and initialized Proxy Factory Contract=%s by %s", contract_address, deployer_account.address) return EthereumTxSent(tx_hash, tx, contract_address)
def test_token_eth_value(self): mainnet_node = just_test_if_mainnet_node() price_service = PriceService(EthereumClient(mainnet_node), self.redis) gno_token_address = "0x6810e776880C02933D47DB1b9fc05908e5386b96" token_eth_value = price_service.get_token_eth_value(gno_token_address) self.assertIsInstance(token_eth_value, float) self.assertGreater(token_eth_value, 0)
def test_node_exceptions(self): node_urls = settings.ETHEREUM_TEST_NODES_URLS for node_url in node_urls: random_address = Account.create().address random_sender_account = Account.create() ethereum_service = EthereumClient(node_url) with self.assertRaises(InsufficientFunds): ethereum_service.send_unsigned_transaction( { 'to': random_address, 'value': 0, 'data': b'', 'gas': 25000, 'gasPrice': 1 }, private_key=random_sender_account.key)
def test_zerion_client(self): mainnet_node = just_test_if_mainnet_node() client = ZerionUniswapV2TokenAdapterClient( EthereumClient(mainnet_node)) owl_pool_address = '0xBA6329EAe69707D6A0F273Bd082f4a0807A6B011' expected = [ UniswapComponent( address='0x1A5F9352Af8aF974bFC03399e3767DF6370d82e4', tokenType='ERC20', rate=0), UniswapComponent( address='0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', tokenType='ERC20', rate=0) ] components = client.get_components(owl_pool_address) for component in components: self.assertGreaterEqual(component.rate, 0) component.rate = 0 self.assertEqual(components, expected) metadata = client.get_metadata(owl_pool_address) expected = ZerionPoolMetadata( address='0xBA6329EAe69707D6A0F273Bd082f4a0807A6B011', name='OWL/USDC Pool', symbol='UNI-V2', decimals=18) self.assertEqual(metadata, expected) random_address = Account.create().address self.assertIsNone(client.get_components(random_address)) self.assertIsNone(client.get_metadata(random_address))
def __new__(cls): if not hasattr(cls, 'instance'): from django.conf import settings cls.instance = ProxyFactoryIndexer( EthereumClient(settings.ETHEREUM_NODE_URL)) return cls.instance
def __init__(self, ethereum_client: EthereumClient): self.ethereum_client = ethereum_client self.cache_token_info: Dict[str, Tuple[str, str]] = {} # Cache forever self.cache_uri_metadata = TTLCache(maxsize=1024, ttl=60 * 60 * 24) # 1 day of caching self.ens_service: EnsClient = EnsClient( ethereum_client.get_network().value)
def __new__(cls): if not hasattr(cls, "instance"): from django.conf import settings cls.instance = Erc20EventsService( EthereumClient(settings.ETHEREUM_NODE_URL)) return cls.instance
def __new__(cls): if not hasattr(cls, 'instance'): from django.conf import settings cls.instance = InternalTxService( EthereumClient(settings.ETHEREUM_TRACING_NODE_URL), block_process_limit=settings.INTERNAL_TXS_BLOCK_PROCESS_LIMIT) return cls.instance
def test_node_exceptions(self): node_urls = settings.ETHEREUM_TEST_NODES_URLS for node_url in node_urls: random_address = Account.create().address random_sender_account = Account.create() ethereum_service = EthereumClient(node_url) with self.assertRaises(InsufficientFunds): ethereum_service.send_unsigned_transaction( { "to": random_address, "value": 0, "data": b"", "gas": 25000, "gasPrice": ethereum_service.w3.eth.gas_price, }, private_key=random_sender_account.key, )
def __init__(self, address: str, node_url: str): self.address = address self.node_url = node_url self.ethereum_client = EthereumClient(self.node_url) self.ens = ENS.fromWeb3(self.ethereum_client.w3) self.network: EthereumNetwork = self.ethereum_client.get_network() self.network_name: str = self.network.name self.network_number: int = self.network.value self.etherscan = Etherscan.from_network_number(self.network_number) self.safe_tx_service_url = TransactionService.from_network_number(self.network_number) self.safe_relay_service_url = RelayService.from_network_number(self.network_number) self.safe = Safe(address, self.ethereum_client) self.safe_contract = self.safe.get_contract() self.accounts: Set[Account] = set() self.default_sender: Optional[Account] = None self.executed_transactions: List[str] = [] self._safe_cli_info: Optional[SafeCliInfo] = None # Cache for SafeCliInfo
def test_gas_station(self): gas_price_oldest = GasPriceFactory() gas_price_newest = GasPriceFactory() gas_station = GasStation( EthereumClient(settings.ETHEREUM_NODE_URL), settings.GAS_STATION_NUMBER_BLOCKS, ) self.assertEqual(gas_station.get_gas_prices(), gas_price_newest)
def setUp(self) -> None: self.ethereum_client = EthereumClient("http://localhost:8545") with mock.patch.object(EthereumClient, "get_network", return_value=EthereumNetwork.RINKEBY): self.transaction_service = TransactionServiceApi.from_ethereum_client( self.ethereum_client) # Rinkeby self.safe_address = "0x7552Ed65a45E27740a15B8D5415E90d8ca64C109"
def __new__(cls): if not hasattr(cls, "instance"): from django.conf import settings node_url = (settings.ETHEREUM_TRACING_NODE_URL if settings.ETHEREUM_TRACING_NODE_URL else settings.ETHEREUM_NODE_URL) cls.instance = SafeTxProcessor(EthereumClient(node_url)) return cls.instance
def __init__(self, address, ethereum_client: EthereumClient = None): """ Create an ApeSafe from an address or a ENS name and use a default connection. """ if not web3.isChecksumAddress(address): address = web3.ens.resolve(address) if ethereum_client is None: ethereum_client = EthereumClient() super().__init__(address, ethereum_client)
def test_token_eth_value(self): mainnet_node = just_test_if_mainnet_node() balance_service = BalanceService(EthereumClient(mainnet_node), settings.ETH_UNISWAP_FACTORY_ADDRESS, settings.ETH_KYBER_NETWORK_PROXY_ADDRESS) gno_token_address = '0x6810e776880C02933D47DB1b9fc05908e5386b96' token_eth_value = balance_service.get_token_eth_value(gno_token_address) self.assertIsInstance(token_eth_value, float) self.assertGreater(token_eth_value, 0)
def get(self, request, format=None): """ Get information about the Ethereum Tracing RPC node used by the service (if any configured) """ if not settings.ETHEREUM_TRACING_NODE_URL: return Response(status=status.HTTP_404_NOT_FOUND) else: ethereum_client = EthereumClient( settings.ETHEREUM_TRACING_NODE_URL) return Response(self._get_info(ethereum_client))
def __new__(cls): if not hasattr(cls, "instance"): from django.conf import settings tracing_enabled = bool(settings.ETHEREUM_TRACING_NODE_URL) node_url = (settings.ETHEREUM_TRACING_NODE_URL if tracing_enabled else settings.ETHEREUM_NODE_URL) cls.instance = SafeService(EthereumClient(node_url), tracing_enabled) return cls.instance
def __init__(self, ethereum_client: EthereumClient): self.ethereum_client = ethereum_client self.ens_service: EnsClient = EnsClient( ethereum_client.get_network().value) self.cache_uri_metadata = TTLCache(maxsize=1024, ttl=60 * 60 * 24) # 1 day of caching self.cache_token_info: Dict[str, Tuple[str, str]] = {} self.cache_token_uri: Dict[Tuple[str, int], str] = {} self.http_session = requests.session()
def __init__(self, ethereum_client: EthereumClient, redis: Redis): self.ethereum_client = ethereum_client self.ethereum_network = ethereum_client.get_network() self.redis = redis self.ens_service: EnsClient = EnsClient(self.ethereum_network.value) self.cache_uri_metadata = TTLCache(maxsize=4096, ttl=60 * 60 * 24) # 1 day of caching self.cache_token_info: TTLCache[str, Erc721InfoWithLogo] = TTLCache( maxsize=4096, ttl=60 * 30) # 2 hours of caching self.cache_token_uri: Dict[Tuple[str, int], str] = {}
def test_kleros_client(self): mainnet_node = just_test_if_mainnet_node() kleros_client = KlerosClient(EthereumClient(mainnet_node)) token_ids = kleros_client.get_token_ids() self.assertGreater(len(token_ids), 100) kleros_tokens = kleros_client.get_token_info(token_ids[:5]) self.assertEqual(len(kleros_tokens), 5) for kleros_token in kleros_tokens: self.assertTrue(is_checksum_address(kleros_token.address)) self.assertTrue(kleros_token.symbol_multihash.startswith('/ipfs/'))
def __new__(cls): if not hasattr(cls, "instance"): from django.conf import settings block_process_limit: int = settings.ETH_INTERNAL_TXS_BLOCK_PROCESS_LIMIT trace_txs_batch_size: int = settings.ETH_INTERNAL_TRACE_TXS_BATCH_SIZE blocks_to_reindex_again = 6 if settings.ETH_INTERNAL_NO_FILTER: cls.instance = InternalTxIndexerWithTraceBlock( EthereumClient(settings.ETHEREUM_TRACING_NODE_URL), block_process_limit=block_process_limit, blocks_to_reindex_again=blocks_to_reindex_again, trace_txs_batch_size=trace_txs_batch_size, ) else: cls.instance = InternalTxIndexer( EthereumClient(settings.ETHEREUM_TRACING_NODE_URL), block_process_limit=block_process_limit, blocks_to_reindex_again=blocks_to_reindex_again, trace_txs_batch_size=trace_txs_batch_size, ) return cls.instance
def setUpClass(cls) -> None: cls.ethereum_node_url = cls.ETHEREUM_NODE_URL cls.ethereum_client = EthereumClient(cls.ethereum_node_url) cls.w3 = cls.ethereum_client.w3 cls.ethereum_test_account = Account.from_key(cls.ETHEREUM_ACCOUNT_KEY) cls.safe_contract_address = Safe.deploy_master_contract(cls.ethereum_client, cls.ethereum_test_account).contract_address cls.safe_old_contract_address = Safe.deploy_master_contract_v1_0_0(cls.ethereum_client, cls.ethereum_test_account).contract_address cls.proxy_factory = ProxyFactory( ProxyFactory.deploy_proxy_factory_contract(cls.ethereum_client, cls.ethereum_test_account).contract_address, cls.ethereum_client)
def test_gas_station_mock(self): gas_station = GasStation(EthereumClient(), number_of_blocks=0) with self.assertRaises(NoBlocksFound): gas_station.calculate_gas_prices() number_of_blocks = 50 gas_station = GasStation(EthereumClient(), number_of_blocks=number_of_blocks) w3 = gas_station.w3 account1 = w3.eth.accounts[-1] account2 = w3.eth.accounts[-2] if w3.eth.block_number < number_of_blocks and w3.eth.accounts: # Ganache # Mine some blocks eth_balance = w3.toWei(0.00001, "ether") for _ in range(number_of_blocks - w3.eth.block_number + 2): w3.eth.wait_for_transaction_receipt( w3.eth.send_transaction({ "from": account1, "to": account2, "value": eth_balance })) w3.eth.wait_for_transaction_receipt( w3.eth.send_transaction({ "from": account2, "to": account1, "value": eth_balance })) gas_prices = gas_station.calculate_gas_prices() self.assertIsNotNone(gas_prices) self.assertGreaterEqual(gas_prices.lowest, 1) self.assertGreaterEqual(gas_prices.safe_low, 1) self.assertGreaterEqual(gas_prices.standard, 1) self.assertGreaterEqual(gas_prices.fast, 1) self.assertGreaterEqual(gas_prices.fastest, 1)
def __init__(self, address: str, node_url: str): self.address = address self.node_url = node_url self.ethereum_client = EthereumClient(self.node_url) self.ens = ENS.fromWeb3(self.ethereum_client.w3) self.network: EthereumNetwork = self.ethereum_client.get_network() self.etherscan = EtherscanApi.from_ethereum_client( self.ethereum_client) self.safe_relay_service = RelayServiceApi.from_ethereum_client( self.ethereum_client) self.safe_tx_service = TransactionServiceApi.from_ethereum_client( self.ethereum_client) self.safe = Safe(address, self.ethereum_client) self.safe_contract = self.safe.get_contract() self.safe_contract_1_1_0 = get_safe_V1_1_1_contract( self.ethereum_client.w3, address=self.address) self.accounts: Set[LocalAccount] = set() self.default_sender: Optional[LocalAccount] = None self.executed_transactions: List[str] = [] self._safe_cli_info: Optional[ SafeCliInfo] = None # Cache for SafeCliInfo self.require_all_signatures = ( True # Require all signatures to be present to send a tx )
def test_token_eth_value(self): if not MAINNET_NODE: pytest.skip("Mainnet node not defined, cannot test oracles", allow_module_level=True) elif requests.get(MAINNET_NODE).status_code == 404: pytest.skip("Cannot connect to mainnet node", allow_module_level=True) balance_service = BalanceService( EthereumClient(MAINNET_NODE), settings.ETH_UNISWAP_FACTORY_ADDRESS, settings.ETH_KYBER_NETWORK_PROXY_ADDRESS) gno_token_address = '0x6810e776880C02933D47DB1b9fc05908e5386b96' token_eth_value = balance_service.get_token_eth_value( gno_token_address) self.assertIsInstance(token_eth_value, float) self.assertGreater(token_eth_value, 0)
def test_check_proxy_code_mainnet(self): mainnet_node = just_test_if_mainnet_node() ethereum_client = EthereumClient(mainnet_node) last_proxy_factory_address = "0xa6B71E26C5e0845f74c812102Ca7114b6a896AB2" proxy_factory = ProxyFactory(last_proxy_factory_address, ethereum_client) # Random Safes deployed by the proxy_factory safes = [ "0x7f2722741F997c63133e656a70aE5Ae0614aD7f5", # v1.0.0 "0x655A9e6b044d6B62F393f9990ec3eA877e966e18", # v1.1.1 # '', # v1.2.0 "0xDaB5dc22350f9a6Aff03Cf3D9341aAD0ba42d2a6", # v1.3.0 ] for safe in safes: with self.subTest(safe=safe): self.assertTrue(proxy_factory.check_proxy_code(safe))
def _get_info(self, ethereum_client: EthereumClient) -> Dict[str, Any]: try: client_version = ethereum_client.w3.clientVersion except (IOError, ValueError): client_version = "Error getting client version" try: syncing = ethereum_client.w3.eth.syncing except (IOError, ValueError): syncing = "Error getting syncing status" ethereum_network = ethereum_client.get_network() return { "version": client_version, "block_number": ethereum_client.current_block_number, "chain_id": ethereum_network.value, "chain": ethereum_network.name, "syncing": syncing, }
from gevent.pool import Pool from gnosis.eth import EthereumClient @contextmanager def timing(function: str = ""): start = time.time() yield print(function, "Elapsed:", time.time() - start) if __name__ == "__main__": from gevent import monkey monkey.patch_all() # noqa pool = Pool(200) e = EthereumClient("http://localhost:8545") blocks_to_fetch = list(range(12773522 - 10000, 12773522)) with timing("Batch get blocks"): e.get_blocks(blocks_to_fetch) # with timing('Secuential get blocks'): # for block in blocks_to_fetch: # e.get_block(block) with timing("Parallel get blocks"): jobs = [pool.spawn(e.get_block, block) for block in blocks_to_fetch] pool.join()