예제 #1
0
def get_web3(network: str = config["network"],
             provider: str = config["provider"]) -> Web3:
    """
    Get XinFin Web3 instance.

    :param network: XinFin network, defaults to ``mainnet``.
    :type network: str
    :param provider: XinFin network provider, defaults to ``http``.
    :type provider: str

    :returns: Web3 -- XinFin Web3 instance.

    >>> from swap.providers.xinfin.rpc import get_web3
    >>> get_web3(network="testnet", provider="http")
    <web3.main.Web3 object at 0x000001DDECCD0640>
    """

    # Check parameter instances
    if not is_network(network=network):
        raise NetworkError(
            f"Invalid XinFin '{network}' network",
            "choose only 'mainnet', 'apothem' or 'testnet' networks.")

    if provider == "http":
        web3: Web3 = Web3(
            HTTPProvider(endpoint_uri=URI(config[network]["http"]),
                         request_kwargs={"timeout": config["timeout"]}))
        return web3
    elif provider == "websocket":
        web3: Web3 = Web3(
            WebsocketProvider(endpoint_uri=URI(config[network]["websocket"])))
        return web3
    else:
        raise ValueError(f"Invalid XinFin '{provider}' provider",
                         "choose only 'http' or 'websocket' providers.")
예제 #2
0
파일: rpc.py 프로젝트: movnetwork/swap
def get_web3(network: str = config["network"], provider: str = config["provider"],
             token: Optional[str] = None) -> Web3:
    """
    Get Ethereum Web3 instance.

    :param network: Ethereum network, defaults to ``mainnet``.
    :type network: str
    :param provider: Ethereum network provider, defaults to ``http``.
    :type provider: str
    :param token: Infura API endpoint token, defaults to ``4414fea5f7454211956b1627621450b4``.
    :type token: str

    :returns: Web3 -- Ethereum Web3 instance.

    >>> from swap.providers.ethereum.rpc import get_web3
    >>> get_web3(network="testnet", provider="http", token="infura endpoint token ...")
    <web3.main.Web3 object at 0x000001DDECCD0640>
    """

    # Check parameter instances
    if not is_network(network=network):
        raise NetworkError(f"Invalid Ethereum '{network}' network",
                           "choose only 'mainnet', 'ropsten', 'kovan', 'rinkeby' or 'testnet' networks.")

    endpoint: str = "ganache-cli" if network == "testnet" else "infura"
    token: str = token if token else config[network][endpoint]["token"]

    if provider == "http":
        web3: Web3 = Web3(HTTPProvider(
                URI(
                    f"{config[network]['infura']['http']}/{token}"
                    if token else config[network][endpoint]["http"]
                ),
                request_kwargs={
                    "timeout": config["timeout"]
                }
            )
        )
        return web3
    elif provider == "websocket":
        web3: Web3 = Web3(WebsocketProvider(
                URI(
                    f"{config[network]['infura']['websocket']}/{token}"
                    if token else config[network][endpoint]["websocket"]
                )
            )
        )
        return web3
    else:
        raise ValueError(f"Invalid Ethereum '{provider}' provider",
                         "choose only 'http' or 'websocket' providers.")
예제 #3
0
def load_provider_from_uri(
        uri_string: URI,
        headers: Optional[Dict[str, Tuple[str, str]]] = None) -> BaseProvider:
    uri = urlparse(uri_string)
    if uri.scheme == 'file':
        return IPCProvider(uri.path)
    elif uri.scheme in HTTP_SCHEMES:
        return HTTPProvider(uri_string, headers)
    elif uri.scheme in WS_SCHEMES:
        return WebsocketProvider(uri_string)
    else:
        raise NotImplementedError(
            f'Web3 does not know how to connect to scheme {uri.scheme!r} in {uri_string!r}'
        )
예제 #4
0
def load_provider_from_uri(uri_string, headers=None):
    uri = urlparse(uri_string)
    if uri.scheme == 'file':
        return IPCProvider(uri.path)
    elif uri.scheme in HTTP_SCHEMES:
        return HTTPProvider(uri_string, headers)
    elif uri.scheme in WS_SCHEMES:
        return WebsocketProvider(uri_string)
    else:
        raise NotImplementedError(
            'Web3 does not know how to connect to scheme %r in %r' % (
                uri.scheme,
                uri_string,
            ))
예제 #5
0
def load_provider_from_environment():
    uri_string = os.environ.get('WEB3_PROVIDER_URI', '')
    if not uri_string:
        return None

    uri = urlparse(uri_string)
    if uri.scheme == 'file':
        return IPCProvider(uri.path)
    elif uri.scheme in HTTP_SCHEMES:
        return HTTPProvider(uri_string)
    elif uri.scheme == 'ws':
        return WebsocketProvider(uri_string)
    else:
        raise NotImplementedError(
            'Web3 does not know how to connect to scheme %r in %r' % (
                uri.scheme,
                uri_string,
            ))
예제 #6
0
PROJECT_ID = os.environ.get('PROJECT_ID') or '' # Infura Project ID
if not PROJECT_ID:
    print('Error: env variable PROJECT_ID not found', file=sys.stderr)
    sys.exit(1)

ROPSTEN_ENDPOINT = f'wss://ropsten.infura.io/ws/v3/{PROJECT_ID}'

WEBSOCKET_TIMEOUT = 30 # raising timeout makes no difference
ABI_FILEPATH = 'ABI_Ropsten.json'

with open(ABI_FILEPATH, 'r', encoding='utf-8') as abi_file:
    abi_json = json.loads(abi_file.read())
    Contract_Address = web3.Web3.toChecksumAddress(abi_json["contractAddress"].lower())
    contract_abi = abi_json['abi']

w3 = web3.Web3(WebsocketProvider(ROPSTEN_ENDPOINT, websocket_timeout=WEBSOCKET_TIMEOUT))
contract = w3.eth.contract(address=Contract_Address, abi=contract_abi)

tests = OrderedDict() # {from_block: message}
#tests[6807500] = 'Both BrickTransfer and EthUpdate succeed'
tests[6807400] = 'BrickTransfer succeeds, but EthUpdate will timeout'
#tests[6807300] = 'Both will timeout'

for from_block, msg in tests.items():
    print(f'fromBlock={from_block}, {msg}', flush=True)

#    event_filter = contract.events.BrickTransfer.createFilter(fromBlock=from_block)
#    all_entries = event_filter.get_all_entries()
#    for event in all_entries[:3]:
#        print(f'BrickTransfer event transactionHash {event.transactionHash.hex()}', flush=True)
#    print()