def get_w3() -> Web3: """Set up the web3 provider for serving transactions to the ethereum network. >>> w3 = get_w3() >>> type(w3) <class 'web3.main.Web3'> >>> type(w3.provider) <class 'web3.providers.rpc.HTTPProvider'> >>> os.environ["HMT_ETH_SERVER"] = "wss://localhost:8546" >>> w3 = get_w3() >>> type(w3) <class 'web3.main.Web3'> >>> type(w3.provider) <class 'web3.providers.websocket.WebsocketProvider'> >>> del os.environ["HMT_ETH_SERVER"] Returns: Web3: returns the web3 provider. """ endpoint = os.getenv("HMT_ETH_SERVER", "http://localhost:8545") if not endpoint: LOG.error("Using EthereumTesterProvider as we have no HMT_ETH_SERVER") provider = (load_provider_from_uri(URI(endpoint)) if endpoint else EthereumTesterProvider()) w3 = Web3(provider) w3.middleware_onion.inject(geth_poa_middleware, layer=0) return w3
def create_provider_from_config(rpc_config: MutableMapping): uri = rpc_config.get("uri", None) if uri is not None: logger.info(f"Autodetect provider from uri {uri}") provider = load_provider_from_uri(uri) logger.info(f"Autodetected {provider.__class__.__name__}") return provider provider_type = rpc_config["type"] if provider_type is ProviderType.HTTP: url = "{}://{}:{}".format( "https" if rpc_config["use_ssl"] else "http", rpc_config["host"], rpc_config["port"], ) logger.info("Using HTTP provider with URL {}".format(url)) return HTTPProvider(URI(url)) elif provider_type is ProviderType.WEBSOCKET: url = "{}://{}:{}".format( "wss" if rpc_config["use_ssl"] else "ws", rpc_config["host"], rpc_config["port"], ) logger.info("Using websocket provider with URL {}".format(url)) return WebsocketProvider(URI(url)) elif provider_type is ProviderType.IPC: file_path = rpc_config["file_path"] logger.info("Using IPC provider with file path {}".format(file_path)) return IPCProvider(file_path) else: raise ValueError(f"Unknown web3 provider type: {provider_type}")
def handle(self, *args, **options): slug = options['event_slug'] no_dry_run = options['no_dry_run'] uri = options['web3_provider_uri'] token_address = options['token_address'] w3 = Web3(load_provider_from_uri(uri)) token_contract = w3.eth.contract(abi=TOKEN_ABI, address=token_address) try: with scope(organizer=None): event = Event.objects.get(slug=slug) except Event.DoesNotExist: raise ValueError(f'Event with slug "{slug}" not found') unconfirmed_addresses = WalletAddress.objects.all().for_event(event).unconfirmed_orders() for wallet_address in unconfirmed_addresses: hex_address = wallet_address.hex_address checksum_address = w3.toChecksumAddress(hex_address) order_payment = wallet_address.order_payment full_id = order_payment.full_id info = order_payment.info_data expected_currency_type = info['currency_type'] expected_amount = info['amount'] eth_amount = w3.eth.getBalance(checksum_address) token_amount = token_contract.functions.balanceOf(checksum_address).call() if eth_amount > 0 or token_amount > 0: logger.info(f'Payments found for {full_id} at {checksum_address}:') if expected_currency_type == 'ETH': if token_amount > 0: logger.warning(f' * Found unexpected payment of {token_amount} DAI') if eth_amount < expected_amount: logger.warning(f' * Expected payment of at least {expected_amount} ETH') # noqa: E501 logger.warning(f' * Given payment was {eth_amount} ETH') # noqa: E501 logger.warning(f' * Skipping') # noqa: F541 continue elif expected_currency_type == 'DAI': if eth_amount > 0: logger.warning(f' * Found unexpected payment of {eth_amount} ETH') if token_amount < expected_amount: logger.warning(f' * Expected payment of at least {expected_amount} DAI') # noqa: E501 logger.warning(f' * Given payment was {token_amount} DAI') # noqa: E501 logger.warning(f' * Skipping') # noqa: F541 continue if no_dry_run: logger.info(f' * Confirming order payment {full_id}') with scope(organizer=None): order_payment.confirm() else: logger.info(f' * DRY RUN: Would confirm order payment {full_id}') else: logger.info(f'No payments found for {full_id}')
def handle(self, *args, **options): slug = options['event_slug'] no_dry_run = options['no_dry_run'] uri = options['web3_provider_uri'] token_address = options['token_address'] w3 = Web3(load_provider_from_uri(uri)) token_contract = w3.eth.contract(abi=TOKEN_ABI, address=token_address) try: with scope(organizer=None): event = Event.objects.get(slug=slug) except Event.DoesNotExist: raise ValueError(f'Event with slug "{slug}" not found') unconfirmed_addresses = WalletAddress.objects.all().for_event( event).unconfirmed_refunds() for wallet_address in unconfirmed_addresses: hex_address = wallet_address.hex_address checksum_address = w3.toChecksumAddress(hex_address) order_refund = OrderRefund.objects.get( payment=wallet_address.order_payment) full_id = order_refund.full_id info = order_refund.info_data expected_currency_type = info['currency_type'] eth_amount = w3.eth.getBalance(checksum_address) token_amount = token_contract.functions.balanceOf( checksum_address).call() if (eth_amount == 0 and expected_currency_type == 'ETH') or ( token_amount == 0 and expected_currency_type == 'DAI'): logger.info( f'Refund found for {full_id} at {checksum_address}:') if no_dry_run: logger.info(f' * Confirming refund payment {full_id}') with scope(organizer=None): order_refund.done() else: logger.info( f' * DRY RUN: Would confirm order payment {full_id}') else: logger.info(f'No refund process started for {full_id}')
def setup_w3(chain_id: int, private_key: str = None) -> Web3: if chain_id not in SUPPORTED_CHAIN_IDS.keys(): raise ValidationError( f"Chain ID: {chain_id} is invalid. Currently supported chain ids " f"include: {list(SUPPORTED_CHAIN_IDS.keys())}.") infura_url = f"{SUPPORTED_CHAIN_IDS[chain_id]}.infura.io" headers = build_http_headers() infura_url = build_infura_url(infura_url) w3 = Web3(load_provider_from_uri(infura_url, headers)) if private_key is not None: owner_address = Account.from_key(private_key).address signing_middleware = construct_sign_and_send_raw_middleware( private_key) w3.middleware_onion.add(signing_middleware) w3.eth.defaultAccount = to_checksum_address(owner_address) cli_logger.debug( "In-flight tx signing has been enabled for address: {owner_address}." ) w3.enable_unstable_package_management_api() return w3
from web3 import Web3 from web3.middleware import ( geth_poa_middleware, ) from web3.providers.auto import ( load_provider_from_uri, ) from .endpoints import ( INFURA_RINKEBY_DOMAIN, build_infura_url, ) _infura_url = build_infura_url(INFURA_RINKEBY_DOMAIN) w3 = Web3(load_provider_from_uri(_infura_url)) w3.middleware_onion.inject(geth_poa_middleware, layer=0)
from web3 import Web3 from web3.providers.auto import ( load_provider_from_uri, ) from .endpoints import ( INFURA_ROPSTEN_DOMAIN, build_http_headers, build_infura_url, ) _infura_url = build_infura_url(INFURA_ROPSTEN_DOMAIN) _headers = build_http_headers() w3 = Web3(load_provider_from_uri(_infura_url, _headers))
from web3 import Web3 from web3.providers.auto import ( load_provider_from_uri, ) from .endpoints import ( INFURA_MAINNET_DOMAIN, build_infura_url, ) _infura_url = build_infura_url(INFURA_MAINNET_DOMAIN) w3 = Web3(load_provider_from_uri(_infura_url))
from eth_account import Account from web3.auto.infura.endpoints import build_infura_url from web3.providers.auto import load_provider_from_uri from web3.middleware import construct_sign_and_send_raw_middleware from web3 import Web3 DR_PK = <insert_private_key_here> DR_ADDRESS = Account.privateKeyToAccount(DR_PK).address COOP_PK = <insert_private_key_here> COOP_ADDRESS = Account.privateKeyToAccount(COOP_PK).address GMA_PK = <insert_private_key_here> GMA_ADDRESS = Account.privateKeyToAccount(GMA_PK).address coop_w3 = Web3(load_provider_from_uri(build_infura_url('mainnet.infura.io'))) coop_middleware = construct_sign_and_send_raw_middleware(COOP_PK) coop_w3.middleware_onion.add(coop_middleware) coop_w3.eth.defaultAccount = COOP_ADDRESS coop_w3.enable_unstable_package_management_api() def print_balances(w3, multisig): print(f"Grandma: {w3.fromWei(w3.eth.getBalance(GMA_ADDRESS), 'ether')} ETH") print(f"Multisig: {w3.fromWei(w3.eth.getBalance(multisig), 'ether')} ETH") print(f"Coop: {w3.fromWei(w3.eth.getBalance(COOP_ADDRESS), 'ether')} ETH")
def __init__(self, endpoint=1, public_key=None, keyfile_path=None, password=None, origin=None): """ Endpoint: 1 - Ethereum Mainnet 4 - Ethereum testnet Rinkeby """ # Check the selected endpoint, if its not in the allowed list raise an exception if endpoint == 1: if origin is None: from web3.auto.infura import w3 # If origin is set I add it to headers else: from web3 import Web3 from web3.providers.auto import ( load_provider_from_uri, ) from web3.auto.infura.endpoints import ( INFURA_MAINNET_DOMAIN, build_http_headers, build_infura_url, ) _headers = build_http_headers() _infura_url = build_infura_url(INFURA_MAINNET_DOMAIN) _headers["Origin"] = origin w3 = Web3(load_provider_from_uri(_infura_url, _headers)) elif endpoint == 4: if origin is None: from web3.auto.infura.rinkeby import w3 # If origin is set I add it to headers else: from web3 import Web3 from web3.middleware import ( geth_poa_middleware, ) from web3.providers.auto import ( load_provider_from_uri, ) from web3.auto.infura.endpoints import ( INFURA_RINKEBY_DOMAIN, build_http_headers, build_infura_url, ) _headers = build_http_headers() _infura_url = build_infura_url(INFURA_RINKEBY_DOMAIN) _headers["Origin"] = origin w3 = Web3(load_provider_from_uri(_infura_url, _headers)) w3.middleware_onion.inject(geth_poa_middleware, layer=0) else: raise Exception("Endpoint not allowed.") self.w3 = w3 # Check if we are connected to the net if not self.w3.isConnected(): raise Exception( "Not connected to the net. Check your API SECRET and PROJECT ID" ) # Open the keyfile and store the private key in the attribute private_key if public_key is not None and keyfile_path is not None and password is not None: self.openKeyFile(public_key, keyfile_path, password)
def __init__(self) -> None: os.environ.setdefault("INFUFA_API_KEY", INFURA_API_KEY) infura_url = f"wss://mainnet.infura.io/ws/v3/{INFURA_API_KEY}" self.w3 = Web3(load_provider_from_uri(infura_url))
def create_web3(uri: str): provider = load_provider_from_uri(uri, {"timeout": 60}) return Web3(provider=provider)