code
stringlengths
1
5.19M
package
stringlengths
1
81
path
stringlengths
9
304
filename
stringlengths
4
145
# coding: utf-8 import pprint import re # noqa: F401 import six class RelayerApiOrdersChannelSubscribePayloadSchema(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { "maker_asset_proxy_id": "str", "taker_asset_proxy_id": "str", "maker_asset_address": "str", "taker_asset_address": "str", "maker_asset_data": "str", "taker_asset_data": "str", "trader_asset_data": "str", } attribute_map = { "maker_asset_proxy_id": "makerAssetProxyId", "taker_asset_proxy_id": "takerAssetProxyId", "maker_asset_address": "makerAssetAddress", "taker_asset_address": "takerAssetAddress", "maker_asset_data": "makerAssetData", "taker_asset_data": "takerAssetData", "trader_asset_data": "traderAssetData", } def __init__( self, maker_asset_proxy_id=None, taker_asset_proxy_id=None, maker_asset_address=None, taker_asset_address=None, maker_asset_data=None, taker_asset_data=None, trader_asset_data=None, ): # noqa: E501 """RelayerApiOrdersChannelSubscribePayloadSchema - a model defined in OpenAPI""" # noqa: E501 self._maker_asset_proxy_id = None self._taker_asset_proxy_id = None self._maker_asset_address = None self._taker_asset_address = None self._maker_asset_data = None self._taker_asset_data = None self._trader_asset_data = None self.discriminator = None if maker_asset_proxy_id is not None: self.maker_asset_proxy_id = maker_asset_proxy_id if taker_asset_proxy_id is not None: self.taker_asset_proxy_id = taker_asset_proxy_id if maker_asset_address is not None: self.maker_asset_address = maker_asset_address if taker_asset_address is not None: self.taker_asset_address = taker_asset_address if maker_asset_data is not None: self.maker_asset_data = maker_asset_data if taker_asset_data is not None: self.taker_asset_data = taker_asset_data if trader_asset_data is not None: self.trader_asset_data = trader_asset_data @property def maker_asset_proxy_id(self): """Gets the maker_asset_proxy_id of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 :return: The maker_asset_proxy_id of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 :rtype: str """ return self._maker_asset_proxy_id @maker_asset_proxy_id.setter def maker_asset_proxy_id(self, maker_asset_proxy_id): """Sets the maker_asset_proxy_id of this RelayerApiOrdersChannelSubscribePayloadSchema. :param maker_asset_proxy_id: The maker_asset_proxy_id of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 :type: str """ if maker_asset_proxy_id is not None and not re.search( r"^0x(([0-9a-f][0-9a-f])+)?$", maker_asset_proxy_id ): # noqa: E501 raise ValueError( r"Invalid value for `maker_asset_proxy_id`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`" ) # noqa: E501 self._maker_asset_proxy_id = maker_asset_proxy_id @property def taker_asset_proxy_id(self): """Gets the taker_asset_proxy_id of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 :return: The taker_asset_proxy_id of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 :rtype: str """ return self._taker_asset_proxy_id @taker_asset_proxy_id.setter def taker_asset_proxy_id(self, taker_asset_proxy_id): """Sets the taker_asset_proxy_id of this RelayerApiOrdersChannelSubscribePayloadSchema. :param taker_asset_proxy_id: The taker_asset_proxy_id of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 :type: str """ if taker_asset_proxy_id is not None and not re.search( r"^0x(([0-9a-f][0-9a-f])+)?$", taker_asset_proxy_id ): # noqa: E501 raise ValueError( r"Invalid value for `taker_asset_proxy_id`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`" ) # noqa: E501 self._taker_asset_proxy_id = taker_asset_proxy_id @property def maker_asset_address(self): """Gets the maker_asset_address of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 :return: The maker_asset_address of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 :rtype: str """ return self._maker_asset_address @maker_asset_address.setter def maker_asset_address(self, maker_asset_address): """Sets the maker_asset_address of this RelayerApiOrdersChannelSubscribePayloadSchema. :param maker_asset_address: The maker_asset_address of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 :type: str """ if maker_asset_address is not None and not re.search( r"^0x[0-9a-f]{40}$", maker_asset_address ): # noqa: E501 raise ValueError( r"Invalid value for `maker_asset_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`" ) # noqa: E501 self._maker_asset_address = maker_asset_address @property def taker_asset_address(self): """Gets the taker_asset_address of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 :return: The taker_asset_address of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 :rtype: str """ return self._taker_asset_address @taker_asset_address.setter def taker_asset_address(self, taker_asset_address): """Sets the taker_asset_address of this RelayerApiOrdersChannelSubscribePayloadSchema. :param taker_asset_address: The taker_asset_address of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 :type: str """ if taker_asset_address is not None and not re.search( r"^0x[0-9a-f]{40}$", taker_asset_address ): # noqa: E501 raise ValueError( r"Invalid value for `taker_asset_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`" ) # noqa: E501 self._taker_asset_address = taker_asset_address @property def maker_asset_data(self): """Gets the maker_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 :return: The maker_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 :rtype: str """ return self._maker_asset_data @maker_asset_data.setter def maker_asset_data(self, maker_asset_data): """Sets the maker_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. :param maker_asset_data: The maker_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 :type: str """ if maker_asset_data is not None and not re.search( r"^0x(([0-9a-f][0-9a-f])+)?$", maker_asset_data ): # noqa: E501 raise ValueError( r"Invalid value for `maker_asset_data`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`" ) # noqa: E501 self._maker_asset_data = maker_asset_data @property def taker_asset_data(self): """Gets the taker_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 :return: The taker_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 :rtype: str """ return self._taker_asset_data @taker_asset_data.setter def taker_asset_data(self, taker_asset_data): """Sets the taker_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. :param taker_asset_data: The taker_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 :type: str """ if taker_asset_data is not None and not re.search( r"^0x(([0-9a-f][0-9a-f])+)?$", taker_asset_data ): # noqa: E501 raise ValueError( r"Invalid value for `taker_asset_data`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`" ) # noqa: E501 self._taker_asset_data = taker_asset_data @property def trader_asset_data(self): """Gets the trader_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 :return: The trader_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 :rtype: str """ return self._trader_asset_data @trader_asset_data.setter def trader_asset_data(self, trader_asset_data): """Sets the trader_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. :param trader_asset_data: The trader_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 :type: str """ if trader_asset_data is not None and not re.search( r"^0x(([0-9a-f][0-9a-f])+)?$", trader_asset_data ): # noqa: E501 raise ValueError( r"Invalid value for `trader_asset_data`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`" ) # noqa: E501 self._trader_asset_data = trader_asset_data def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list( map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value, ) ) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict( map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items(), ) ) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance( other, RelayerApiOrdersChannelSubscribePayloadSchema ): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
0x-sra-client
/0x-sra-client-4.0.0.tar.gz/0x-sra-client-4.0.0/src/zero_ex/sra_client/models/relayer_api_orders_channel_subscribe_payload_schema.py
relayer_api_orders_channel_subscribe_payload_schema.py
# coding: utf-8 import pprint import re # noqa: F401 import six class PaginatedCollectionSchema(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = {"total": "float", "per_page": "float", "page": "float"} attribute_map = {"total": "total", "per_page": "perPage", "page": "page"} def __init__(self, total=None, per_page=None, page=None): # noqa: E501 """PaginatedCollectionSchema - a model defined in OpenAPI""" # noqa: E501 self._total = None self._per_page = None self._page = None self.discriminator = None self.total = total self.per_page = per_page self.page = page @property def total(self): """Gets the total of this PaginatedCollectionSchema. # noqa: E501 :return: The total of this PaginatedCollectionSchema. # noqa: E501 :rtype: float """ return self._total @total.setter def total(self, total): """Sets the total of this PaginatedCollectionSchema. :param total: The total of this PaginatedCollectionSchema. # noqa: E501 :type: float """ if total is None: raise ValueError( "Invalid value for `total`, must not be `None`" ) # noqa: E501 self._total = total @property def per_page(self): """Gets the per_page of this PaginatedCollectionSchema. # noqa: E501 :return: The per_page of this PaginatedCollectionSchema. # noqa: E501 :rtype: float """ return self._per_page @per_page.setter def per_page(self, per_page): """Sets the per_page of this PaginatedCollectionSchema. :param per_page: The per_page of this PaginatedCollectionSchema. # noqa: E501 :type: float """ if per_page is None: raise ValueError( "Invalid value for `per_page`, must not be `None`" ) # noqa: E501 self._per_page = per_page @property def page(self): """Gets the page of this PaginatedCollectionSchema. # noqa: E501 :return: The page of this PaginatedCollectionSchema. # noqa: E501 :rtype: float """ return self._page @page.setter def page(self, page): """Sets the page of this PaginatedCollectionSchema. :param page: The page of this PaginatedCollectionSchema. # noqa: E501 :type: float """ if page is None: raise ValueError( "Invalid value for `page`, must not be `None`" ) # noqa: E501 self._page = page def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list( map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value, ) ) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict( map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items(), ) ) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, PaginatedCollectionSchema): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
0x-sra-client
/0x-sra-client-4.0.0.tar.gz/0x-sra-client-4.0.0/src/zero_ex/sra_client/models/paginated_collection_schema.py
paginated_collection_schema.py
# coding: utf-8 import pprint import re # noqa: F401 import six class RelayerApiOrdersResponseSchema(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = {"records": "list[RelayerApiOrderSchema]"} attribute_map = {"records": "records"} def __init__(self, records=None): # noqa: E501 """RelayerApiOrdersResponseSchema - a model defined in OpenAPI""" # noqa: E501 self._records = None self.discriminator = None self.records = records @property def records(self): """Gets the records of this RelayerApiOrdersResponseSchema. # noqa: E501 :return: The records of this RelayerApiOrdersResponseSchema. # noqa: E501 :rtype: list[RelayerApiOrderSchema] """ return self._records @records.setter def records(self, records): """Sets the records of this RelayerApiOrdersResponseSchema. :param records: The records of this RelayerApiOrdersResponseSchema. # noqa: E501 :type: list[RelayerApiOrderSchema] """ if records is None: raise ValueError( "Invalid value for `records`, must not be `None`" ) # noqa: E501 self._records = records def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list( map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value, ) ) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict( map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items(), ) ) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, RelayerApiOrdersResponseSchema): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
0x-sra-client
/0x-sra-client-4.0.0.tar.gz/0x-sra-client-4.0.0/src/zero_ex/sra_client/models/relayer_api_orders_response_schema.py
relayer_api_orders_response_schema.py
# coding: utf-8 import pprint import re # noqa: F401 import six class SignedOrderSchema(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = {"signature": "str"} attribute_map = {"signature": "signature"} def __init__(self, signature=None): # noqa: E501 """SignedOrderSchema - a model defined in OpenAPI""" # noqa: E501 self._signature = None self.discriminator = None self.signature = signature @property def signature(self): """Gets the signature of this SignedOrderSchema. # noqa: E501 :return: The signature of this SignedOrderSchema. # noqa: E501 :rtype: str """ return self._signature @signature.setter def signature(self, signature): """Sets the signature of this SignedOrderSchema. :param signature: The signature of this SignedOrderSchema. # noqa: E501 :type: str """ if signature is None: raise ValueError( "Invalid value for `signature`, must not be `None`" ) # noqa: E501 if signature is not None and not re.search( r"^0x(([0-9a-f][0-9a-f])+)?$", signature ): # noqa: E501 raise ValueError( r"Invalid value for `signature`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`" ) # noqa: E501 self._signature = signature def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list( map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value, ) ) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict( map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items(), ) ) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, SignedOrderSchema): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
0x-sra-client
/0x-sra-client-4.0.0.tar.gz/0x-sra-client-4.0.0/src/zero_ex/sra_client/models/signed_order_schema.py
signed_order_schema.py
# coding: utf-8 import pprint import re # noqa: F401 import six class RelayerApiAssetDataPairsResponseSchema(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = {"records": "list[object]"} attribute_map = {"records": "records"} def __init__(self, records=None): # noqa: E501 """RelayerApiAssetDataPairsResponseSchema - a model defined in OpenAPI""" # noqa: E501 self._records = None self.discriminator = None self.records = records @property def records(self): """Gets the records of this RelayerApiAssetDataPairsResponseSchema. # noqa: E501 :return: The records of this RelayerApiAssetDataPairsResponseSchema. # noqa: E501 :rtype: list[object] """ return self._records @records.setter def records(self, records): """Sets the records of this RelayerApiAssetDataPairsResponseSchema. :param records: The records of this RelayerApiAssetDataPairsResponseSchema. # noqa: E501 :type: list[object] """ if records is None: raise ValueError( "Invalid value for `records`, must not be `None`" ) # noqa: E501 self._records = records def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list( map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value, ) ) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict( map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items(), ) ) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, RelayerApiAssetDataPairsResponseSchema): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
0x-sra-client
/0x-sra-client-4.0.0.tar.gz/0x-sra-client-4.0.0/src/zero_ex/sra_client/models/relayer_api_asset_data_pairs_response_schema.py
relayer_api_asset_data_pairs_response_schema.py
# coding: utf-8 # flake8: noqa from __future__ import absolute_import # import models into model package from zero_ex.sra_client.models.order_schema import OrderSchema from zero_ex.sra_client.models.paginated_collection_schema import ( PaginatedCollectionSchema, ) from zero_ex.sra_client.models.relayer_api_asset_data_pairs_response_schema import ( RelayerApiAssetDataPairsResponseSchema, ) from zero_ex.sra_client.models.relayer_api_asset_data_trade_info_schema import ( RelayerApiAssetDataTradeInfoSchema, ) from zero_ex.sra_client.models.relayer_api_error_response_schema import ( RelayerApiErrorResponseSchema, ) from zero_ex.sra_client.models.relayer_api_error_response_schema_validation_errors import ( RelayerApiErrorResponseSchemaValidationErrors, ) from zero_ex.sra_client.models.relayer_api_fee_recipients_response_schema import ( RelayerApiFeeRecipientsResponseSchema, ) from zero_ex.sra_client.models.relayer_api_order_config_payload_schema import ( RelayerApiOrderConfigPayloadSchema, ) from zero_ex.sra_client.models.relayer_api_order_config_response_schema import ( RelayerApiOrderConfigResponseSchema, ) from zero_ex.sra_client.models.relayer_api_order_schema import RelayerApiOrderSchema from zero_ex.sra_client.models.relayer_api_orderbook_response_schema import ( RelayerApiOrderbookResponseSchema, ) from zero_ex.sra_client.models.relayer_api_orders_channel_subscribe_payload_schema import ( RelayerApiOrdersChannelSubscribePayloadSchema, ) from zero_ex.sra_client.models.relayer_api_orders_channel_subscribe_schema import ( RelayerApiOrdersChannelSubscribeSchema, ) from zero_ex.sra_client.models.relayer_api_orders_channel_update_schema import ( RelayerApiOrdersChannelUpdateSchema, ) from zero_ex.sra_client.models.relayer_api_orders_response_schema import ( RelayerApiOrdersResponseSchema, ) from zero_ex.sra_client.models.signed_order_schema import SignedOrderSchema
0x-sra-client
/0x-sra-client-4.0.0.tar.gz/0x-sra-client-4.0.0/src/zero_ex/sra_client/models/__init__.py
__init__.py
# coding: utf-8 import pprint import re # noqa: F401 import six class RelayerApiOrdersChannelSubscribeSchema(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { "type": "str", "channel": "str", "request_id": "str", "payload": "RelayerApiOrdersChannelSubscribePayloadSchema", } attribute_map = { "type": "type", "channel": "channel", "request_id": "requestId", "payload": "payload", } def __init__( self, type=None, channel=None, request_id=None, payload=None ): # noqa: E501 """RelayerApiOrdersChannelSubscribeSchema - a model defined in OpenAPI""" # noqa: E501 self._type = None self._channel = None self._request_id = None self._payload = None self.discriminator = None self.type = type self.channel = channel self.request_id = request_id if payload is not None: self.payload = payload @property def type(self): """Gets the type of this RelayerApiOrdersChannelSubscribeSchema. # noqa: E501 :return: The type of this RelayerApiOrdersChannelSubscribeSchema. # noqa: E501 :rtype: str """ return self._type @type.setter def type(self, type): """Sets the type of this RelayerApiOrdersChannelSubscribeSchema. :param type: The type of this RelayerApiOrdersChannelSubscribeSchema. # noqa: E501 :type: str """ if type is None: raise ValueError( "Invalid value for `type`, must not be `None`" ) # noqa: E501 allowed_values = ["subscribe"] # noqa: E501 if type not in allowed_values: raise ValueError( "Invalid value for `type` ({0}), must be one of {1}".format( # noqa: E501 type, allowed_values ) ) self._type = type @property def channel(self): """Gets the channel of this RelayerApiOrdersChannelSubscribeSchema. # noqa: E501 :return: The channel of this RelayerApiOrdersChannelSubscribeSchema. # noqa: E501 :rtype: str """ return self._channel @channel.setter def channel(self, channel): """Sets the channel of this RelayerApiOrdersChannelSubscribeSchema. :param channel: The channel of this RelayerApiOrdersChannelSubscribeSchema. # noqa: E501 :type: str """ if channel is None: raise ValueError( "Invalid value for `channel`, must not be `None`" ) # noqa: E501 allowed_values = ["orders"] # noqa: E501 if channel not in allowed_values: raise ValueError( "Invalid value for `channel` ({0}), must be one of {1}".format( # noqa: E501 channel, allowed_values ) ) self._channel = channel @property def request_id(self): """Gets the request_id of this RelayerApiOrdersChannelSubscribeSchema. # noqa: E501 :return: The request_id of this RelayerApiOrdersChannelSubscribeSchema. # noqa: E501 :rtype: str """ return self._request_id @request_id.setter def request_id(self, request_id): """Sets the request_id of this RelayerApiOrdersChannelSubscribeSchema. :param request_id: The request_id of this RelayerApiOrdersChannelSubscribeSchema. # noqa: E501 :type: str """ if request_id is None: raise ValueError( "Invalid value for `request_id`, must not be `None`" ) # noqa: E501 self._request_id = request_id @property def payload(self): """Gets the payload of this RelayerApiOrdersChannelSubscribeSchema. # noqa: E501 :return: The payload of this RelayerApiOrdersChannelSubscribeSchema. # noqa: E501 :rtype: RelayerApiOrdersChannelSubscribePayloadSchema """ return self._payload @payload.setter def payload(self, payload): """Sets the payload of this RelayerApiOrdersChannelSubscribeSchema. :param payload: The payload of this RelayerApiOrdersChannelSubscribeSchema. # noqa: E501 :type: RelayerApiOrdersChannelSubscribePayloadSchema """ self._payload = payload def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list( map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value, ) ) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict( map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items(), ) ) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, RelayerApiOrdersChannelSubscribeSchema): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
0x-sra-client
/0x-sra-client-4.0.0.tar.gz/0x-sra-client-4.0.0/src/zero_ex/sra_client/models/relayer_api_orders_channel_subscribe_schema.py
relayer_api_orders_channel_subscribe_schema.py
# Web3.py [![Join the chat at https://gitter.im/ethereum/web3.py](https://badges.gitter.im/ethereum/web3.py.svg)](https://gitter.im/ethereum/web3.py?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Build Status](https://circleci.com/gh/ethereum/web3.py.svg?style=shield)](https://circleci.com/gh/ethereum/web3.py) A Python implementation of [web3.js](https://github.com/ethereum/web3.js) * Python 3.6+ support Read more in the [documentation on ReadTheDocs](http://web3py.readthedocs.io/). [View the change log on Github](docs/releases.rst). ## Developer Setup ```sh git clone git@github.com:ethereum/web3.py.git cd web3.py ``` Please see OS-specific instructions for: - [Linux](docs/README-linux.md#Developer-Setup) - [Mac](docs/README-osx.md#Developer-Setup) - [Windows](docs/README-windows.md#Developer-Setup) - [FreeBSD](docs/README-freebsd.md#Developer-Setup) Then run these install commands: ```sh virtualenv venv . venv/bin/activate pip install -e .[dev] ``` For different environments, you can set up multiple `virtualenv`. For example, if you want to create a `venvdocs`, then you do the following: ```sh virtualenv venvdocs . venvdocs/bin/activate pip install -e .[docs] pip install -e . ``` ## Using Docker If you would like to develop and test inside a Docker environment, use the *sandbox* container provided in the **docker-compose.yml** file. To start up the test environment, run: ``` docker-compose up -d ``` This will build a Docker container set up with an environment to run the Python test code. **Note: This container does not have `go-ethereum` installed, so you cannot run the go-ethereum test suite.** To run the Python tests from your local machine: ``` docker-compose exec sandbox bash -c 'pytest -n 4 -f -k "not goethereum"' ``` You can run arbitrary commands inside the Docker container by using the `bash -c` prefix. ``` docker-compose exec sandbox bash -c '' ``` Or, if you would like to just open a session to the container, run: ``` docker-compose exec sandbox bash ``` ### Testing Setup During development, you might like to have tests run on every file save. Show flake8 errors on file change: ```sh # Test flake8 when-changed -v -s -r -1 web3/ tests/ ens/ -c "clear; flake8 web3 tests ens && echo 'flake8 success' || echo 'error'" ``` You can use `pytest-watch`, running one for every Python environment: ```sh pip install pytest-watch cd venv ptw --onfail "notify-send -t 5000 'Test failure ⚠⚠⚠⚠⚠' 'python 3 test on web3.py failed'" ../tests ../web3 ``` Or, you can run multi-process tests in one command, but without color: ```sh # in the project root: pytest --numprocesses=4 --looponfail --maxfail=1 # the same thing, succinctly: pytest -n 4 -f --maxfail=1 ``` #### How to Execute the Tests? 1. [Setup your development environment](https://github.com/ethereum/web3.py/#developer-setup). 2. Execute `tox` for the tests There are multiple [components](https://github.com/ethereum/web3.py/blob/master/.travis.yml#L53) of the tests. You can run test to against specific component. For example: ```sh # Run Tests for the Core component (for Python 3.5): tox -e py35-core # Run Tests for the Core component (for Python 3.6): tox -e py36-core ``` If for some reason it is not working, add `--recreate` params. `tox` is good for testing against the full set of build targets. But if you want to run the tests individually, `py.test` is better for development workflow. For example, to run only the tests in one file: ```sh py.test tests/core/gas-strategies/test_time_based_gas_price_strategy.py ``` ### Release setup For Debian-like systems: ``` apt install pandoc ``` To release a new version: ```sh make release bump=$$VERSION_PART_TO_BUMP$$ ``` #### How to bumpversion The version format for this repo is `{major}.{minor}.{patch}` for stable, and `{major}.{minor}.{patch}-{stage}.{devnum}` for unstable (`stage` can be alpha or beta). To issue the next version in line, specify which part to bump, like `make release bump=minor` or `make release bump=devnum`. If you are in a beta version, `make release bump=stage` will switch to a stable. To issue an unstable version when the current version is stable, specify the new version explicitly, like `make release bump="--new-version 4.0.0-alpha.1 devnum"`
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/README.md
README.md
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import ( find_packages, setup, ) extras_require = { 'tester': [ "eth-tester[py-evm]==0.1.0-beta.37", "py-geth>=2.0.1,<3.0.0", "pytest-ethereum>=0.1.3a6,<1.0.0", ], 'testrpc': ["eth-testrpc>=1.3.3,<2.0.0"], 'linter': [ "flake8==3.4.1", "isort>=4.2.15,<5", ], 'docs': [ "mock", "sphinx-better-theme>=0.1.4", "click>=5.1", "configparser==3.5.0", "contextlib2>=0.5.4", "ethtoken", "py-geth>=1.4.0", "py-solc>=0.4.0", "pytest>=3.5.0,<4.0.0", "sphinx", "sphinx_rtd_theme>=0.1.9", "toposort>=1.4", "urllib3", "web3>=2.1.0", "wheel" ], 'dev': [ "bumpversion", "flaky>=3.3.0", "hypothesis>=3.31.2", "pytest>=3.6.0,<4.0.0", "pytest-mock==1.*", "pytest-pythonpath>=0.3", "pytest-watch==4.*", "pytest-xdist==1.*", "setuptools>=36.2.0", "tox>=1.8.0", "tqdm", "twine", "when-changed" ] } extras_require['dev'] = ( extras_require['tester'] + extras_require['linter'] + extras_require['docs'] + extras_require['dev'] ) setup( name='0x-web3', # *IMPORTANT*: Don't manually change the version here. Use the 'bumpversion' utility. version='5.0.0-alpha.5', description="""Web3.py""", long_description_markdown_filename='README.md', author='Piper Merriam', author_email='pipermerriam@gmail.com', url='https://github.com/ethereum/web3.py', include_package_data=True, install_requires=[ "eth-abi>=2.0.0b5,<3.0.0", "eth-account>=0.2.1,<0.4.0", "eth-hash[pycryptodome]>=0.2.0,<1.0.0", "eth-utils>=1.3.0,<2.0.0", "ethpm>=0.1.4a12,<1.0.0", "hexbytes>=0.1.0,<1.0.0", "lru-dict>=1.1.6,<2.0.0", "requests>=2.16.0,<3.0.0", "websockets>=7.0.0,<8.0.0", "pypiwin32>=223;platform_system=='Windows'", ], setup_requires=['setuptools-markdown'], python_requires='>=3.6,<4', extras_require=extras_require, py_modules=['web3', 'ens'], license="MIT", zip_safe=False, keywords='ethereum', packages=find_packages(exclude=["tests", "tests.*"]), classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ], )
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/setup.py
setup.py
# flake8: noqa import json registrar_abi = json.loads('[{"constant":false,"inputs":[{"name":"_hash","type":"bytes32"}],"name":"releaseDeed","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_hash","type":"bytes32"}],"name":"getAllowedTime","outputs":[{"name":"timestamp","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"unhashedName","type":"string"}],"name":"invalidateName","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"hash","type":"bytes32"},{"name":"owner","type":"address"},{"name":"value","type":"uint256"},{"name":"salt","type":"bytes32"}],"name":"shaBid","outputs":[{"name":"sealedBid","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bidder","type":"address"},{"name":"seal","type":"bytes32"}],"name":"cancelBid","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_hash","type":"bytes32"}],"name":"entries","outputs":[{"name":"","type":"uint8"},{"name":"","type":"address"},{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"ens","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_hash","type":"bytes32"},{"name":"_value","type":"uint256"},{"name":"_salt","type":"bytes32"}],"name":"unsealBid","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_hash","type":"bytes32"}],"name":"transferRegistrars","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"bytes32"}],"name":"sealedBids","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_hash","type":"bytes32"}],"name":"state","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_hash","type":"bytes32"},{"name":"newOwner","type":"address"}],"name":"transfer","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_hash","type":"bytes32"},{"name":"_timestamp","type":"uint256"}],"name":"isAllowed","outputs":[{"name":"allowed","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_hash","type":"bytes32"}],"name":"finalizeAuction","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"registryStarted","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"launchLength","outputs":[{"name":"","type":"uint32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"sealedBid","type":"bytes32"}],"name":"newBid","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"name":"labels","type":"bytes32[]"}],"name":"eraseNode","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_hashes","type":"bytes32[]"}],"name":"startAuctions","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"hash","type":"bytes32"},{"name":"deed","type":"address"},{"name":"registrationDate","type":"uint256"}],"name":"acceptRegistrarTransfer","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_hash","type":"bytes32"}],"name":"startAuction","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"rootNode","outputs":[{"name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"hashes","type":"bytes32[]"},{"name":"sealedBid","type":"bytes32"}],"name":"startAuctionsAndBid","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"_ens","type":"address"},{"name":"_rootNode","type":"bytes32"},{"name":"_startDate","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"hash","type":"bytes32"},{"indexed":false,"name":"registrationDate","type":"uint256"}],"name":"AuctionStarted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"hash","type":"bytes32"},{"indexed":true,"name":"bidder","type":"address"},{"indexed":false,"name":"deposit","type":"uint256"}],"name":"NewBid","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"hash","type":"bytes32"},{"indexed":true,"name":"owner","type":"address"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"status","type":"uint8"}],"name":"BidRevealed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"hash","type":"bytes32"},{"indexed":true,"name":"owner","type":"address"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"registrationDate","type":"uint256"}],"name":"HashRegistered","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"hash","type":"bytes32"},{"indexed":false,"name":"value","type":"uint256"}],"name":"HashReleased","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"hash","type":"bytes32"},{"indexed":true,"name":"name","type":"string"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"registrationDate","type":"uint256"}],"name":"HashInvalidated","type":"event"}]') registrar_bytecode = "6060604052341561000f57600080fd5b60405160608061275783398101604052808051919060200180519190602001805160008054600160a060020a031916600160a060020a0387161781556001859055909250821190506100615742610063565b805b6004555050506126df806100786000396000f300606060405236156101175763ffffffff60e060020a6000350416630230a07c811461011c57806313c89a8f1461013457806315f733311461015c57806322ec1244146101ad5780632525f5c1146101d5578063267b6922146101f75780633f15457f1461025f57806347872b421461028e5780635ddae283146102aa5780635e431709146102c057806361d585da146102e257806379ce9fac1461031c578063935033371461033e578063983b94fb1461036b5780639c67f06f14610381578063ae1a0b0c14610394578063ce92dced146103c0578063de10f04b146103cb578063e27fe50f1461041a578063ea9e107a14610469578063ede8acdb1461048e578063faff50a8146104a4578063febefd61146104b7575b600080fd5b341561012757600080fd5b6101326004356104fd565b005b341561013f57600080fd5b61014a60043561072a565b60405190815260200160405180910390f35b341561016757600080fd5b61013260046024813581810190830135806020601f8201819004810201604051908101604052818152929190602084018383808284375094965061074e95505050505050565b34156101b857600080fd5b61014a600435600160a060020a0360243516604435606435610a7a565b34156101e057600080fd5b610132600160a060020a0360043516602435610ac5565b341561020257600080fd5b61020d600435610c8c565b6040518086600581111561021d57fe5b60ff16815260200185600160a060020a0316600160a060020a031681526020018481526020018381526020018281526020019550505050505060405180910390f35b341561026a57600080fd5b610272610cd8565b604051600160a060020a03909116815260200160405180910390f35b341561029957600080fd5b610132600435602435604435610ce7565b34156102b557600080fd5b610132600435611254565b34156102cb57600080fd5b610272600160a060020a03600435166024356114b4565b34156102ed57600080fd5b6102f86004356114da565b6040518082600581111561030857fe5b60ff16815260200191505060405180910390f35b341561032757600080fd5b610132600435600160a060020a0360243516611550565b341561034957600080fd5b61035760043560243561169b565b604051901515815260200160405180910390f35b341561037657600080fd5b6101326004356116b1565b341561038c57600080fd5b61014a611919565b341561039f57600080fd5b6103a761191f565b60405163ffffffff909116815260200160405180910390f35b610132600435611926565b34156103d657600080fd5b6101326004602481358181019083013580602081810201604051908101604052809392919081815260200183836020028082843750949650611a1a95505050505050565b341561042557600080fd5b6101326004602481358181019083013580602081810201604051908101604052809392919081815260200183836020028082843750949650611a7595505050505050565b341561047457600080fd5b610132600435600160a060020a0360243516604435611aab565b341561049957600080fd5b610132600435611ab0565b34156104af57600080fd5b61014a611bfc565b61013260046024813581810190830135806020818102016040519081016040528093929190818152602001838360200280828437509496505093359350611c0292505050565b60008082600261050c826114da565b600581111561051757fe5b1415806105a3575060008181526002602052604080822054600160a060020a031691638da5cb5b9151602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b151561057257600080fd5b6102c65a03f1151561058357600080fd5b50505060405180519050600160a060020a031633600160a060020a031614155b156105ad57600080fd5b600084815260026020526040902080546001820154919450600160a060020a031692506301e13380014210801561065f575060008054600154600160a060020a03308116939216916302571be391906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b151561063957600080fd5b6102c65a03f1151561064a57600080fd5b50505060405180519050600160a060020a0316145b1561066957600080fd5b60006002840181905560038401558254600160a060020a031916835561068e84611c14565b81600160a060020a031663bbe427716103e860405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b15156106d657600080fd5b6102c65a03f115156106e757600080fd5b505050600283015484907f292b79b9246fa2c8e77d3fe195b251f9cb839d7d038e667c069ee7708c631e169060405190815260200160405180910390a250505050565b6004547001000000000000000000000000000000006249d400818404020401919050565b600080826040518082805190602001908083835b602083106107815780518252601f199092019160209182019101610762565b6001836020036101000a03801982511681845116179092525050509190910192506040915050519081900390206002806107ba836114da565b60058111156107c557fe5b146107cf57600080fd5b60066107da86611e12565b11156107e557600080fd5b846040518082805190602001908083835b602083106108155780518252601f1990920191602091820191016107f6565b6001836020036101000a03801982511681845116179092525050509190910192506040915050519081900390206000818152600260205260409020909450925061085e84611c14565b8254600160a060020a0316156109b5576108838360020154662386f26fc10000611ec3565b60028085018290558454600160a060020a03169163b0c80972919004600060405160e060020a63ffffffff8516028152600481019290925215156024820152604401600060405180830381600087803b15156108de57600080fd5b6102c65a03f115156108ef57600080fd5b50508354600160a060020a031690506313af40353360405160e060020a63ffffffff8416028152600160a060020a039091166004820152602401600060405180830381600087803b151561094257600080fd5b6102c65a03f1151561095357600080fd5b50508354600160a060020a0316905063bbe427716103e860405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b15156109a057600080fd5b6102c65a03f115156109b157600080fd5b5050505b846040518082805190602001908083835b602083106109e55780518252601f1990920191602091820191016109c6565b6001836020036101000a0380198251168184511617909252505050919091019250604091505051809103902084600019167f1f9c649fe47e58bb60f4e52f0d90e4c47a526c9f90c5113df842c025970b66ad8560020154866001015460405191825260208201526040908101905180910390a3505060006002820181905560038201558054600160a060020a03191690555050565b600084848484604051938452600160a060020a03929092166c010000000000000000000000000260208401526034830152605482015260740160405180910390209050949350505050565b600160a060020a03808316600090815260036020908152604080832085845290915290205416801580610b61575062069780600160a060020a0382166305b344106000604051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b1515610b3d57600080fd5b6102c65a03f11515610b4e57600080fd5b5050506040518051905001621275000142105b15610b6b57600080fd5b80600160a060020a03166313af40353360405160e060020a63ffffffff8416028152600160a060020a039091166004820152602401600060405180830381600087803b1515610bb957600080fd5b6102c65a03f11515610bca57600080fd5b50505080600160a060020a031663bbe42771600560405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b1515610c1457600080fd5b6102c65a03f11515610c2557600080fd5b505050600160a060020a03831660008181526003602090815260408083208684529091528082208054600160a060020a03191690558491600080516020612694833981519152916005905191825260ff1660208201526040908101905180910390a3505050565b60008181526002602052604081208190819081908190610cab876114da565b815460018301546002840154600390940154929a600160a060020a03909216995097509195509350915050565b600054600160a060020a031681565b600080600080600080610cfc89338a8a610a7a565b600160a060020a033381166000908152600360209081526040808320858452909152902054919750169450841515610d3357600080fd5b600160a060020a0333811660009081526003602090815260408083208a845282528083208054600160a060020a03191690558c835260029091528082209650610dd6928b9290891691633fa4f245919051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b1515610db657600080fd5b6102c65a03f11515610dc757600080fd5b50505060405180519050611edb565b925084600160a060020a031663b0c8097284600160405160e060020a63ffffffff8516028152600481019290925215156024820152604401600060405180830381600087803b1515610e2757600080fd5b6102c65a03f11515610e3857600080fd5b505050610e44896114da565b91506002826005811115610e5457fe5b1415610ef25784600160a060020a031663bbe42771600560405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b1515610ea157600080fd5b6102c65a03f11515610eb257600080fd5b5050600160a060020a03331690508960008051602061269483398151915285600160405191825260ff1660208201526040908101905180910390a3611249565b6004826005811115610f0057fe5b14610f0a57600080fd5b662386f26fc10000831080610f88575060018401546202a2ff1901600160a060020a0386166305b344106000604051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b1515610f6b57600080fd5b6102c65a03f11515610f7c57600080fd5b50505060405180519050115b156110265784600160a060020a031663bbe427716103e360405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b1515610fd557600080fd5b6102c65a03f11515610fe657600080fd5b5050600160a060020a03331690508960008051602061269483398151915285600060405191825260ff1660208201526040908101905180910390a3611249565b8360030154831115611108578354600160a060020a0316156110a257508254600160a060020a03168063bbe427716103e360405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b151561108d57600080fd5b6102c65a03f1151561109e57600080fd5b5050505b600384018054600280870191909155908490558454600160a060020a031916600160a060020a038781169190911786553316908a9060008051602061269483398151915290869060405191825260ff1660208201526040908101905180910390a3611249565b83600201548311156111b45760028401839055600160a060020a03851663bbe427716103e360405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b151561116357600080fd5b6102c65a03f1151561117457600080fd5b5050600160a060020a03331690508960008051602061269483398151915285600360405191825260ff1660208201526040908101905180910390a3611249565b84600160a060020a031663bbe427716103e360405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b15156111fc57600080fd5b6102c65a03f1151561120d57600080fd5b5050600160a060020a03331690508960008051602061269483398151915285600460405191825260ff1660208201526040908101905180910390a35b505050505050505050565b600080826002611263826114da565b600581111561126e57fe5b1415806112fa575060008181526002602052604080822054600160a060020a031691638da5cb5b9151602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b15156112c957600080fd5b6102c65a03f115156112da57600080fd5b50505060405180519050600160a060020a031633600160a060020a031614155b1561130457600080fd5b60008054600154600160a060020a03909116916302571be391906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b151561135b57600080fd5b6102c65a03f1151561136c57600080fd5b50505060405180519050925030600160a060020a031683600160a060020a0316141561139757600080fd5b600084815260026020526040908190208054909350600160a060020a03169063faab9d399085905160e060020a63ffffffff8416028152600160a060020a039091166004820152602401600060405180830381600087803b15156113fa57600080fd5b6102c65a03f1151561140b57600080fd5b505082546001840154600160a060020a03808716935063ea9e107a92889291169060405160e060020a63ffffffff86160281526004810193909352600160a060020a0390911660248301526044820152606401600060405180830381600087803b151561147757600080fd5b6102c65a03f1151561148857600080fd5b50508254600160a060020a03191683555050600060018201819055600282018190556003909101555050565b6003602090815260009283526040808420909152908252902054600160a060020a031681565b60008181526002602052604081206114f2834261169b565b1515611501576005915061154a565b80600101544210156115315760018101546202a2ff1901421015611528576001915061154a565b6004915061154a565b60038101541515611545576000915061154a565b600291505b50919050565b600082600261155e826114da565b600581111561156957fe5b1415806115f5575060008181526002602052604080822054600160a060020a031691638da5cb5b9151602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b15156115c457600080fd5b6102c65a03f115156115d557600080fd5b50505060405180519050600160a060020a031633600160a060020a031614155b156115ff57600080fd5b600160a060020a038316151561161457600080fd5b600084815260026020526040908190208054909350600160a060020a0316906313af40359085905160e060020a63ffffffff8416028152600160a060020a039091166004820152602401600060405180830381600087803b151561167757600080fd5b6102c65a03f1151561168857600080fd5b5050506116958484611eec565b50505050565b60006116a68361072a565b821190505b92915050565b60008160026116bf826114da565b60058111156116ca57fe5b141580611756575060008181526002602052604080822054600160a060020a031691638da5cb5b9151602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b151561172557600080fd5b6102c65a03f1151561173657600080fd5b50505060405180519050600160a060020a031633600160a060020a031614155b1561176057600080fd5b60008381526002602081905260409091209081015490925061178990662386f26fc10000611ec3565b600283018190558254600160a060020a03169063b0c8097290600160405160e060020a63ffffffff8516028152600481019290925215156024820152604401600060405180830381600087803b15156117e157600080fd5b6102c65a03f115156117f257600080fd5b5050825461186291508490600160a060020a0316638da5cb5b6000604051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b151561184257600080fd5b6102c65a03f1151561185357600080fd5b50505060405180519050611eec565b8154600160a060020a0316638da5cb5b6000604051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b15156118a957600080fd5b6102c65a03f115156118ba57600080fd5b50505060405180519050600160a060020a031683600019167f0f0c27adfd84b60b6f456b0e87cdccb1e5fb9603991588d87fa99f5b6b61e6708460020154856001015460405191825260208201526040908101905180910390a3505050565b60045481565b6249d40081565b600160a060020a0333811660009081526003602090815260408083208584529091528120549091168190111561195b57600080fd5b662386f26fc1000034101561196f57600080fd5b3433611979612187565b600160a060020a0390911681526020016040518091039082f080151561199e57600080fd5b33600160a060020a039081166000818152600360209081526040808320898452909152908190208054600160a060020a0319169385169390931790925591935090915083907fb556ff269c1b6714f432c36431e2041d28436a73b6c3f19c021827bbdc6bfc299034905190815260200160405180910390a35050565b80511515611a2757600080fd5b6002611a4b82600184510381518110611a3c57fe5b906020019060200201516114da565b6005811115611a5657fe5b1415611a6157600080fd5b611a72600182510382600154611fd6565b50565b60005b8151811015611aa757611a9f828281518110611a9057fe5b90602001906020020151611ab0565b600101611a78565b5050565b505050565b600080600454421080611aca5750600454630784ce000142115b80611b51575060008054600154600160a060020a03308116939216916302571be391906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b1515611b2a57600080fd5b6102c65a03f11515611b3b57600080fd5b50505060405180519050600160a060020a031614155b15611b5b57600080fd5b611b64836114da565b91506001826005811115611b7457fe5b1415611b7f57611aab565b6000826005811115611b8d57fe5b14611b9757600080fd5b50600082815260026020819052604080832042620697800160018201819055928101849055600381019390935584917f87e97e825a1d1fa0c54e1d36c7506c1dea8b1efd451fe68b000cf96f7cf40003915190815260200160405180910390a2505050565b60015481565b611c0b82611a75565b611aa781611926565b60008054600154600160a060020a033081169216906302571be390846040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b1515611c6d57600080fd5b6102c65a03f11515611c7e57600080fd5b50505060405180519050600160a060020a03161415611aa757600054600154600160a060020a03909116906306ab592390843060405160e060020a63ffffffff861602815260048101939093526024830191909152600160a060020a03166044820152606401600060405180830381600087803b1515611cfd57600080fd5b6102c65a03f11515611d0e57600080fd5b5050506001548260405191825260208201526040908101905190819003902060008054919250600160a060020a0390911690631896f70a90839060405160e060020a63ffffffff85160281526004810192909252600160a060020a03166024820152604401600060405180830381600087803b1515611d8c57600080fd5b6102c65a03f11515611d9d57600080fd5b505060008054600160a060020a03169150635b0fc9c390839060405160e060020a63ffffffff85160281526004810192909252600160a060020a03166024820152604401600060405180830381600087803b1515611dfa57600080fd5b6102c65a03f11515611e0b57600080fd5b5050505050565b600060018201818080838651019250600091505b82841015611eba5760ff845116905060808160ff161015611e4c57600184019350611eaf565b60e08160ff161015611e6357600284019350611eaf565b60f08160ff161015611e7a57600384019350611eaf565b60f88160ff161015611e9157600484019350611eaf565b60fc8160ff161015611ea857600584019350611eaf565b6006840193505b600190910190611e26565b50949350505050565b600081831115611ed45750816116ab565b50806116ab565b600081831015611ed45750816116ab565b60008054600154600160a060020a03308116939216916302571be391906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b1515611f4657600080fd5b6102c65a03f11515611f5757600080fd5b50505060405180519050600160a060020a03161415611aa757600054600154600160a060020a03909116906306ab592390848460405160e060020a63ffffffff861602815260048101939093526024830191909152600160a060020a03166044820152606401600060405180830381600087803b1515611dfa57600080fd5b600054600160a060020a03166306ab592382848681518110611ff457fe5b906020019060200201513060405160e060020a63ffffffff861602815260048101939093526024830191909152600160a060020a03166044820152606401600060405180830381600087803b151561204b57600080fd5b6102c65a03f1151561205c57600080fd5b5050508082848151811061206c57fe5b906020019060200201516040519182526020820152604090810190518091039020905060008311156120a6576120a6600184038383611fd6565b60008054600160a060020a031690631896f70a90839060405160e060020a63ffffffff85160281526004810192909252600160a060020a03166024820152604401600060405180830381600087803b151561210057600080fd5b6102c65a03f1151561211157600080fd5b505060008054600160a060020a03169150635b0fc9c390839060405160e060020a63ffffffff85160281526004810192909252600160a060020a03166024820152604401600060405180830381600087803b151561216e57600080fd5b6102c65a03f1151561217f57600080fd5b505050505050565b6040516104fc8061219883390190560060606040526040516020806104fc8339810160405280805160028054600160a060020a03928316600160a060020a03199182161790915560008054339093169290911691909117905550504260019081556005805460ff191690911790553460045561048c806100706000396000f300606060405236156100a15763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166305b3441081146100a65780630b5ab3d5146100cb57806313af4035146100e05780632b20e397146100ff5780633fa4f2451461012e578063674f220f146101415780638da5cb5b14610154578063b0c8097214610167578063bbe4277114610182578063faab9d3914610198575b600080fd5b34156100b157600080fd5b6100b96101b7565b60405190815260200160405180910390f35b34156100d657600080fd5b6100de6101bd565b005b34156100eb57600080fd5b6100de600160a060020a0360043516610207565b341561010a57600080fd5b6101126102b0565b604051600160a060020a03909116815260200160405180910390f35b341561013957600080fd5b6100b96102bf565b341561014c57600080fd5b6101126102c5565b341561015f57600080fd5b6101126102d4565b341561017257600080fd5b6100de60043560243515156102e3565b341561018d57600080fd5b6100de60043561036c565b34156101a357600080fd5b6100de600160a060020a0360043516610416565b60015481565b60055460ff16156101cd57600080fd5b600254600160a060020a039081169030163180156108fc0290604051600060405180830381858888f19350505050156102055761deadff5b565b60005433600160a060020a0390811691161461022257600080fd5b600160a060020a038116151561023757600080fd5b6002805460038054600160a060020a0380841673ffffffffffffffffffffffffffffffffffffffff19928316179092559091169083161790557fa2ea9883a321a3e97b8266c2b078bfeec6d50c711ed71f874a90d500ae2eaf3681604051600160a060020a03909116815260200160405180910390a150565b600054600160a060020a031681565b60045481565b600354600160a060020a031681565b600254600160a060020a031681565b60005433600160a060020a039081169116146102fe57600080fd5b60055460ff16151561030f57600080fd5b81600454101561031e57600080fd5b6004829055600254600160a060020a039081169030163183900380156108fc0290604051600060405180830381858888f1935050505015801561035e5750805b1561036857600080fd5b5050565b60005433600160a060020a0390811691161461038757600080fd5b60055460ff16151561039857600080fd5b6005805460ff1916905561dead6103e8600160a060020a03301631838203020480156108fc0290604051600060405180830381858888f1935050505015156103df57600080fd5b7fbb2ce2f51803bba16bc85282b47deeea9a5c6223eabea1077be696b3f265cf1360405160405180910390a16104136101bd565b50565b60005433600160a060020a0390811691161461043157600080fd5b6000805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a03929092169190911790555600a165627a7a7230582023849fab751378a237489f526a289ede7796b7f6b7dac5a973b8c3ca25f368a800297b6c4b278d165a6b33958f8ea5dfb00c8c9d4d0acf1985bef5d10786898bc3e7a165627a7a72305820e6807b87ab11a69864cefed52eef7f9c4635fd0e26312e944bbbcbff5cd26d920029" registrar_bytecode_runtime = "606060405236156101175763ffffffff60e060020a6000350416630230a07c811461011c57806313c89a8f1461013457806315f733311461015c57806322ec1244146101ad5780632525f5c1146101d5578063267b6922146101f75780633f15457f1461025f57806347872b421461028e5780635ddae283146102aa5780635e431709146102c057806361d585da146102e257806379ce9fac1461031c578063935033371461033e578063983b94fb1461036b5780639c67f06f14610381578063ae1a0b0c14610394578063ce92dced146103c0578063de10f04b146103cb578063e27fe50f1461041a578063ea9e107a14610469578063ede8acdb1461048e578063faff50a8146104a4578063febefd61146104b7575b600080fd5b341561012757600080fd5b6101326004356104fd565b005b341561013f57600080fd5b61014a60043561072a565b60405190815260200160405180910390f35b341561016757600080fd5b61013260046024813581810190830135806020601f8201819004810201604051908101604052818152929190602084018383808284375094965061074e95505050505050565b34156101b857600080fd5b61014a600435600160a060020a0360243516604435606435610a7a565b34156101e057600080fd5b610132600160a060020a0360043516602435610ac5565b341561020257600080fd5b61020d600435610c8c565b6040518086600581111561021d57fe5b60ff16815260200185600160a060020a0316600160a060020a031681526020018481526020018381526020018281526020019550505050505060405180910390f35b341561026a57600080fd5b610272610cd8565b604051600160a060020a03909116815260200160405180910390f35b341561029957600080fd5b610132600435602435604435610ce7565b34156102b557600080fd5b610132600435611254565b34156102cb57600080fd5b610272600160a060020a03600435166024356114b4565b34156102ed57600080fd5b6102f86004356114da565b6040518082600581111561030857fe5b60ff16815260200191505060405180910390f35b341561032757600080fd5b610132600435600160a060020a0360243516611550565b341561034957600080fd5b61035760043560243561169b565b604051901515815260200160405180910390f35b341561037657600080fd5b6101326004356116b1565b341561038c57600080fd5b61014a611919565b341561039f57600080fd5b6103a761191f565b60405163ffffffff909116815260200160405180910390f35b610132600435611926565b34156103d657600080fd5b6101326004602481358181019083013580602081810201604051908101604052809392919081815260200183836020028082843750949650611a1a95505050505050565b341561042557600080fd5b6101326004602481358181019083013580602081810201604051908101604052809392919081815260200183836020028082843750949650611a7595505050505050565b341561047457600080fd5b610132600435600160a060020a0360243516604435611aab565b341561049957600080fd5b610132600435611ab0565b34156104af57600080fd5b61014a611bfc565b61013260046024813581810190830135806020818102016040519081016040528093929190818152602001838360200280828437509496505093359350611c0292505050565b60008082600261050c826114da565b600581111561051757fe5b1415806105a3575060008181526002602052604080822054600160a060020a031691638da5cb5b9151602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b151561057257600080fd5b6102c65a03f1151561058357600080fd5b50505060405180519050600160a060020a031633600160a060020a031614155b156105ad57600080fd5b600084815260026020526040902080546001820154919450600160a060020a031692506301e13380014210801561065f575060008054600154600160a060020a03308116939216916302571be391906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b151561063957600080fd5b6102c65a03f1151561064a57600080fd5b50505060405180519050600160a060020a0316145b1561066957600080fd5b60006002840181905560038401558254600160a060020a031916835561068e84611c14565b81600160a060020a031663bbe427716103e860405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b15156106d657600080fd5b6102c65a03f115156106e757600080fd5b505050600283015484907f292b79b9246fa2c8e77d3fe195b251f9cb839d7d038e667c069ee7708c631e169060405190815260200160405180910390a250505050565b6004547001000000000000000000000000000000006249d400818404020401919050565b600080826040518082805190602001908083835b602083106107815780518252601f199092019160209182019101610762565b6001836020036101000a03801982511681845116179092525050509190910192506040915050519081900390206002806107ba836114da565b60058111156107c557fe5b146107cf57600080fd5b60066107da86611e12565b11156107e557600080fd5b846040518082805190602001908083835b602083106108155780518252601f1990920191602091820191016107f6565b6001836020036101000a03801982511681845116179092525050509190910192506040915050519081900390206000818152600260205260409020909450925061085e84611c14565b8254600160a060020a0316156109b5576108838360020154662386f26fc10000611ec3565b60028085018290558454600160a060020a03169163b0c80972919004600060405160e060020a63ffffffff8516028152600481019290925215156024820152604401600060405180830381600087803b15156108de57600080fd5b6102c65a03f115156108ef57600080fd5b50508354600160a060020a031690506313af40353360405160e060020a63ffffffff8416028152600160a060020a039091166004820152602401600060405180830381600087803b151561094257600080fd5b6102c65a03f1151561095357600080fd5b50508354600160a060020a0316905063bbe427716103e860405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b15156109a057600080fd5b6102c65a03f115156109b157600080fd5b5050505b846040518082805190602001908083835b602083106109e55780518252601f1990920191602091820191016109c6565b6001836020036101000a0380198251168184511617909252505050919091019250604091505051809103902084600019167f1f9c649fe47e58bb60f4e52f0d90e4c47a526c9f90c5113df842c025970b66ad8560020154866001015460405191825260208201526040908101905180910390a3505060006002820181905560038201558054600160a060020a03191690555050565b600084848484604051938452600160a060020a03929092166c010000000000000000000000000260208401526034830152605482015260740160405180910390209050949350505050565b600160a060020a03808316600090815260036020908152604080832085845290915290205416801580610b61575062069780600160a060020a0382166305b344106000604051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b1515610b3d57600080fd5b6102c65a03f11515610b4e57600080fd5b5050506040518051905001621275000142105b15610b6b57600080fd5b80600160a060020a03166313af40353360405160e060020a63ffffffff8416028152600160a060020a039091166004820152602401600060405180830381600087803b1515610bb957600080fd5b6102c65a03f11515610bca57600080fd5b50505080600160a060020a031663bbe42771600560405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b1515610c1457600080fd5b6102c65a03f11515610c2557600080fd5b505050600160a060020a03831660008181526003602090815260408083208684529091528082208054600160a060020a03191690558491600080516020612694833981519152916005905191825260ff1660208201526040908101905180910390a3505050565b60008181526002602052604081208190819081908190610cab876114da565b815460018301546002840154600390940154929a600160a060020a03909216995097509195509350915050565b600054600160a060020a031681565b600080600080600080610cfc89338a8a610a7a565b600160a060020a033381166000908152600360209081526040808320858452909152902054919750169450841515610d3357600080fd5b600160a060020a0333811660009081526003602090815260408083208a845282528083208054600160a060020a03191690558c835260029091528082209650610dd6928b9290891691633fa4f245919051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b1515610db657600080fd5b6102c65a03f11515610dc757600080fd5b50505060405180519050611edb565b925084600160a060020a031663b0c8097284600160405160e060020a63ffffffff8516028152600481019290925215156024820152604401600060405180830381600087803b1515610e2757600080fd5b6102c65a03f11515610e3857600080fd5b505050610e44896114da565b91506002826005811115610e5457fe5b1415610ef25784600160a060020a031663bbe42771600560405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b1515610ea157600080fd5b6102c65a03f11515610eb257600080fd5b5050600160a060020a03331690508960008051602061269483398151915285600160405191825260ff1660208201526040908101905180910390a3611249565b6004826005811115610f0057fe5b14610f0a57600080fd5b662386f26fc10000831080610f88575060018401546202a2ff1901600160a060020a0386166305b344106000604051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b1515610f6b57600080fd5b6102c65a03f11515610f7c57600080fd5b50505060405180519050115b156110265784600160a060020a031663bbe427716103e360405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b1515610fd557600080fd5b6102c65a03f11515610fe657600080fd5b5050600160a060020a03331690508960008051602061269483398151915285600060405191825260ff1660208201526040908101905180910390a3611249565b8360030154831115611108578354600160a060020a0316156110a257508254600160a060020a03168063bbe427716103e360405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b151561108d57600080fd5b6102c65a03f1151561109e57600080fd5b5050505b600384018054600280870191909155908490558454600160a060020a031916600160a060020a038781169190911786553316908a9060008051602061269483398151915290869060405191825260ff1660208201526040908101905180910390a3611249565b83600201548311156111b45760028401839055600160a060020a03851663bbe427716103e360405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b151561116357600080fd5b6102c65a03f1151561117457600080fd5b5050600160a060020a03331690508960008051602061269483398151915285600360405191825260ff1660208201526040908101905180910390a3611249565b84600160a060020a031663bbe427716103e360405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b15156111fc57600080fd5b6102c65a03f1151561120d57600080fd5b5050600160a060020a03331690508960008051602061269483398151915285600460405191825260ff1660208201526040908101905180910390a35b505050505050505050565b600080826002611263826114da565b600581111561126e57fe5b1415806112fa575060008181526002602052604080822054600160a060020a031691638da5cb5b9151602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b15156112c957600080fd5b6102c65a03f115156112da57600080fd5b50505060405180519050600160a060020a031633600160a060020a031614155b1561130457600080fd5b60008054600154600160a060020a03909116916302571be391906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b151561135b57600080fd5b6102c65a03f1151561136c57600080fd5b50505060405180519050925030600160a060020a031683600160a060020a0316141561139757600080fd5b600084815260026020526040908190208054909350600160a060020a03169063faab9d399085905160e060020a63ffffffff8416028152600160a060020a039091166004820152602401600060405180830381600087803b15156113fa57600080fd5b6102c65a03f1151561140b57600080fd5b505082546001840154600160a060020a03808716935063ea9e107a92889291169060405160e060020a63ffffffff86160281526004810193909352600160a060020a0390911660248301526044820152606401600060405180830381600087803b151561147757600080fd5b6102c65a03f1151561148857600080fd5b50508254600160a060020a03191683555050600060018201819055600282018190556003909101555050565b6003602090815260009283526040808420909152908252902054600160a060020a031681565b60008181526002602052604081206114f2834261169b565b1515611501576005915061154a565b80600101544210156115315760018101546202a2ff1901421015611528576001915061154a565b6004915061154a565b60038101541515611545576000915061154a565b600291505b50919050565b600082600261155e826114da565b600581111561156957fe5b1415806115f5575060008181526002602052604080822054600160a060020a031691638da5cb5b9151602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b15156115c457600080fd5b6102c65a03f115156115d557600080fd5b50505060405180519050600160a060020a031633600160a060020a031614155b156115ff57600080fd5b600160a060020a038316151561161457600080fd5b600084815260026020526040908190208054909350600160a060020a0316906313af40359085905160e060020a63ffffffff8416028152600160a060020a039091166004820152602401600060405180830381600087803b151561167757600080fd5b6102c65a03f1151561168857600080fd5b5050506116958484611eec565b50505050565b60006116a68361072a565b821190505b92915050565b60008160026116bf826114da565b60058111156116ca57fe5b141580611756575060008181526002602052604080822054600160a060020a031691638da5cb5b9151602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b151561172557600080fd5b6102c65a03f1151561173657600080fd5b50505060405180519050600160a060020a031633600160a060020a031614155b1561176057600080fd5b60008381526002602081905260409091209081015490925061178990662386f26fc10000611ec3565b600283018190558254600160a060020a03169063b0c8097290600160405160e060020a63ffffffff8516028152600481019290925215156024820152604401600060405180830381600087803b15156117e157600080fd5b6102c65a03f115156117f257600080fd5b5050825461186291508490600160a060020a0316638da5cb5b6000604051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b151561184257600080fd5b6102c65a03f1151561185357600080fd5b50505060405180519050611eec565b8154600160a060020a0316638da5cb5b6000604051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b15156118a957600080fd5b6102c65a03f115156118ba57600080fd5b50505060405180519050600160a060020a031683600019167f0f0c27adfd84b60b6f456b0e87cdccb1e5fb9603991588d87fa99f5b6b61e6708460020154856001015460405191825260208201526040908101905180910390a3505050565b60045481565b6249d40081565b600160a060020a0333811660009081526003602090815260408083208584529091528120549091168190111561195b57600080fd5b662386f26fc1000034101561196f57600080fd5b3433611979612187565b600160a060020a0390911681526020016040518091039082f080151561199e57600080fd5b33600160a060020a039081166000818152600360209081526040808320898452909152908190208054600160a060020a0319169385169390931790925591935090915083907fb556ff269c1b6714f432c36431e2041d28436a73b6c3f19c021827bbdc6bfc299034905190815260200160405180910390a35050565b80511515611a2757600080fd5b6002611a4b82600184510381518110611a3c57fe5b906020019060200201516114da565b6005811115611a5657fe5b1415611a6157600080fd5b611a72600182510382600154611fd6565b50565b60005b8151811015611aa757611a9f828281518110611a9057fe5b90602001906020020151611ab0565b600101611a78565b5050565b505050565b600080600454421080611aca5750600454630784ce000142115b80611b51575060008054600154600160a060020a03308116939216916302571be391906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b1515611b2a57600080fd5b6102c65a03f11515611b3b57600080fd5b50505060405180519050600160a060020a031614155b15611b5b57600080fd5b611b64836114da565b91506001826005811115611b7457fe5b1415611b7f57611aab565b6000826005811115611b8d57fe5b14611b9757600080fd5b50600082815260026020819052604080832042620697800160018201819055928101849055600381019390935584917f87e97e825a1d1fa0c54e1d36c7506c1dea8b1efd451fe68b000cf96f7cf40003915190815260200160405180910390a2505050565b60015481565b611c0b82611a75565b611aa781611926565b60008054600154600160a060020a033081169216906302571be390846040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b1515611c6d57600080fd5b6102c65a03f11515611c7e57600080fd5b50505060405180519050600160a060020a03161415611aa757600054600154600160a060020a03909116906306ab592390843060405160e060020a63ffffffff861602815260048101939093526024830191909152600160a060020a03166044820152606401600060405180830381600087803b1515611cfd57600080fd5b6102c65a03f11515611d0e57600080fd5b5050506001548260405191825260208201526040908101905190819003902060008054919250600160a060020a0390911690631896f70a90839060405160e060020a63ffffffff85160281526004810192909252600160a060020a03166024820152604401600060405180830381600087803b1515611d8c57600080fd5b6102c65a03f11515611d9d57600080fd5b505060008054600160a060020a03169150635b0fc9c390839060405160e060020a63ffffffff85160281526004810192909252600160a060020a03166024820152604401600060405180830381600087803b1515611dfa57600080fd5b6102c65a03f11515611e0b57600080fd5b5050505050565b600060018201818080838651019250600091505b82841015611eba5760ff845116905060808160ff161015611e4c57600184019350611eaf565b60e08160ff161015611e6357600284019350611eaf565b60f08160ff161015611e7a57600384019350611eaf565b60f88160ff161015611e9157600484019350611eaf565b60fc8160ff161015611ea857600584019350611eaf565b6006840193505b600190910190611e26565b50949350505050565b600081831115611ed45750816116ab565b50806116ab565b600081831015611ed45750816116ab565b60008054600154600160a060020a03308116939216916302571be391906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b1515611f4657600080fd5b6102c65a03f11515611f5757600080fd5b50505060405180519050600160a060020a03161415611aa757600054600154600160a060020a03909116906306ab592390848460405160e060020a63ffffffff861602815260048101939093526024830191909152600160a060020a03166044820152606401600060405180830381600087803b1515611dfa57600080fd5b600054600160a060020a03166306ab592382848681518110611ff457fe5b906020019060200201513060405160e060020a63ffffffff861602815260048101939093526024830191909152600160a060020a03166044820152606401600060405180830381600087803b151561204b57600080fd5b6102c65a03f1151561205c57600080fd5b5050508082848151811061206c57fe5b906020019060200201516040519182526020820152604090810190518091039020905060008311156120a6576120a6600184038383611fd6565b60008054600160a060020a031690631896f70a90839060405160e060020a63ffffffff85160281526004810192909252600160a060020a03166024820152604401600060405180830381600087803b151561210057600080fd5b6102c65a03f1151561211157600080fd5b505060008054600160a060020a03169150635b0fc9c390839060405160e060020a63ffffffff85160281526004810192909252600160a060020a03166024820152604401600060405180830381600087803b151561216e57600080fd5b6102c65a03f1151561217f57600080fd5b505050505050565b6040516104fc8061219883390190560060606040526040516020806104fc8339810160405280805160028054600160a060020a03928316600160a060020a03199182161790915560008054339093169290911691909117905550504260019081556005805460ff191690911790553460045561048c806100706000396000f300606060405236156100a15763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166305b3441081146100a65780630b5ab3d5146100cb57806313af4035146100e05780632b20e397146100ff5780633fa4f2451461012e578063674f220f146101415780638da5cb5b14610154578063b0c8097214610167578063bbe4277114610182578063faab9d3914610198575b600080fd5b34156100b157600080fd5b6100b96101b7565b60405190815260200160405180910390f35b34156100d657600080fd5b6100de6101bd565b005b34156100eb57600080fd5b6100de600160a060020a0360043516610207565b341561010a57600080fd5b6101126102b0565b604051600160a060020a03909116815260200160405180910390f35b341561013957600080fd5b6100b96102bf565b341561014c57600080fd5b6101126102c5565b341561015f57600080fd5b6101126102d4565b341561017257600080fd5b6100de60043560243515156102e3565b341561018d57600080fd5b6100de60043561036c565b34156101a357600080fd5b6100de600160a060020a0360043516610416565b60015481565b60055460ff16156101cd57600080fd5b600254600160a060020a039081169030163180156108fc0290604051600060405180830381858888f19350505050156102055761deadff5b565b60005433600160a060020a0390811691161461022257600080fd5b600160a060020a038116151561023757600080fd5b6002805460038054600160a060020a0380841673ffffffffffffffffffffffffffffffffffffffff19928316179092559091169083161790557fa2ea9883a321a3e97b8266c2b078bfeec6d50c711ed71f874a90d500ae2eaf3681604051600160a060020a03909116815260200160405180910390a150565b600054600160a060020a031681565b60045481565b600354600160a060020a031681565b600254600160a060020a031681565b60005433600160a060020a039081169116146102fe57600080fd5b60055460ff16151561030f57600080fd5b81600454101561031e57600080fd5b6004829055600254600160a060020a039081169030163183900380156108fc0290604051600060405180830381858888f1935050505015801561035e5750805b1561036857600080fd5b5050565b60005433600160a060020a0390811691161461038757600080fd5b60055460ff16151561039857600080fd5b6005805460ff1916905561dead6103e8600160a060020a03301631838203020480156108fc0290604051600060405180830381858888f1935050505015156103df57600080fd5b7fbb2ce2f51803bba16bc85282b47deeea9a5c6223eabea1077be696b3f265cf1360405160405180910390a16104136101bd565b50565b60005433600160a060020a0390811691161461043157600080fd5b6000805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a03929092169190911790555600a165627a7a7230582023849fab751378a237489f526a289ede7796b7f6b7dac5a973b8c3ca25f368a800297b6c4b278d165a6b33958f8ea5dfb00c8c9d4d0acf1985bef5d10786898bc3e7a165627a7a72305820e6807b87ab11a69864cefed52eef7f9c4635fd0e26312e944bbbcbff5cd26d920029" resolver_abi = json.loads('[{"constant":true,"inputs":[{"name":"interfaceID","type":"bytes4"}],"name":"supportsInterface","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"node","type":"bytes32"},{"name":"key","type":"string"},{"name":"value","type":"string"}],"name":"setText","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"node","type":"bytes32"},{"name":"contentTypes","type":"uint256"}],"name":"ABI","outputs":[{"name":"contentType","type":"uint256"},{"name":"data","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"node","type":"bytes32"},{"name":"x","type":"bytes32"},{"name":"y","type":"bytes32"}],"name":"setPubkey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"node","type":"bytes32"}],"name":"content","outputs":[{"name":"ret","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"node","type":"bytes32"}],"name":"addr","outputs":[{"name":"ret","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"node","type":"bytes32"},{"name":"key","type":"string"}],"name":"text","outputs":[{"name":"ret","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"node","type":"bytes32"},{"name":"contentType","type":"uint256"},{"name":"data","type":"bytes"}],"name":"setABI","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"node","type":"bytes32"}],"name":"name","outputs":[{"name":"ret","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"node","type":"bytes32"},{"name":"name","type":"string"}],"name":"setName","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"node","type":"bytes32"},{"name":"hash","type":"bytes32"}],"name":"setContent","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"node","type":"bytes32"}],"name":"pubkey","outputs":[{"name":"x","type":"bytes32"},{"name":"y","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"node","type":"bytes32"},{"name":"addr","type":"address"}],"name":"setAddr","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"ensAddr","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"node","type":"bytes32"},{"indexed":false,"name":"a","type":"address"}],"name":"AddrChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"node","type":"bytes32"},{"indexed":false,"name":"hash","type":"bytes32"}],"name":"ContentChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"node","type":"bytes32"},{"indexed":false,"name":"name","type":"string"}],"name":"NameChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"node","type":"bytes32"},{"indexed":true,"name":"contentType","type":"uint256"}],"name":"ABIChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"node","type":"bytes32"},{"indexed":false,"name":"x","type":"bytes32"},{"indexed":false,"name":"y","type":"bytes32"}],"name":"PubkeyChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"node","type":"bytes32"},{"indexed":true,"name":"indexedKey","type":"string"},{"indexed":false,"name":"key","type":"string"}],"name":"TextChanged","type":"event"}]') resolver_bytecode = "6060604052341561000f57600080fd5b6040516020806111b08339810160405280805160008054600160a060020a03909216600160a060020a0319909216919091179055505061115c806100546000396000f300606060405236156100a95763ffffffff60e060020a60003504166301ffc9a781146100ae57806310f13a8c146100e25780632203ab561461017c57806329cd62ea146102135780632dff69411461022f5780633b3b57de1461025757806359d1d43c14610289578063623195b014610356578063691f3431146103b257806377372213146103c8578063c3d014d61461041e578063c869023314610437578063d5fa2b0014610465575b600080fd5b34156100b957600080fd5b6100ce600160e060020a031960043516610487565b604051901515815260200160405180910390f35b34156100ed57600080fd5b61017a600480359060446024803590810190830135806020601f8201819004810201604051908101604052818152929190602084018383808284378201915050505050509190803590602001908201803590602001908080601f0160208091040260200160405190810160405281815292919060208401838380828437509496506105f495505050505050565b005b341561018757600080fd5b610195600435602435610805565b60405182815260406020820181815290820183818151815260200191508051906020019080838360005b838110156101d75780820151838201526020016101bf565b50505050905090810190601f1680156102045780820380516001836020036101000a031916815260200191505b50935050505060405180910390f35b341561021e57600080fd5b61017a60043560243560443561092f565b341561023a57600080fd5b610245600435610a2e565b60405190815260200160405180910390f35b341561026257600080fd5b61026d600435610a44565b604051600160a060020a03909116815260200160405180910390f35b341561029457600080fd5b6102df600480359060446024803590810190830135806020601f82018190048102016040519081016040528181529291906020840183838082843750949650610a5f95505050505050565b60405160208082528190810183818151815260200191508051906020019080838360005b8381101561031b578082015183820152602001610303565b50505050905090810190601f1680156103485780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561036157600080fd5b61017a600480359060248035919060649060443590810190830135806020601f82018190048102016040519081016040528181529291906020840183838082843750949650610b7e95505050505050565b34156103bd57600080fd5b6102df600435610c7a565b34156103d357600080fd5b61017a600480359060446024803590810190830135806020601f82018190048102016040519081016040528181529291906020840183838082843750949650610d4095505050505050565b341561042957600080fd5b61017a600435602435610e8a565b341561044257600080fd5b61044d600435610f63565b60405191825260208201526040908101905180910390f35b341561047057600080fd5b61017a600435600160a060020a0360243516610f80565b6000600160e060020a031982167f3b3b57de0000000000000000000000000000000000000000000000000000000014806104ea5750600160e060020a031982167fd8389dc500000000000000000000000000000000000000000000000000000000145b8061051e5750600160e060020a031982167f691f343100000000000000000000000000000000000000000000000000000000145b806105525750600160e060020a031982167f2203ab5600000000000000000000000000000000000000000000000000000000145b806105865750600160e060020a031982167fc869023300000000000000000000000000000000000000000000000000000000145b806105ba5750600160e060020a031982167f59d1d43c00000000000000000000000000000000000000000000000000000000145b806105ee5750600160e060020a031982167f01ffc9a700000000000000000000000000000000000000000000000000000000145b92915050565b600080548491600160a060020a033381169216906302571be39084906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b151561064d57600080fd5b6102c65a03f1151561065e57600080fd5b50505060405180519050600160a060020a031614151561067d57600080fd5b6000848152600160205260409081902083916005909101908590518082805190602001908083835b602083106106c45780518252601f1990920191602091820191016106a5565b6001836020036101000a0380198251168184511680821785525050505050509050019150509081526020016040518091039020908051610708929160200190611083565b50826040518082805190602001908083835b602083106107395780518252601f19909201916020918201910161071a565b6001836020036101000a0380198251168184511617909252505050919091019250604091505051908190039020847fd8c9334b1a9c2f9da342a0a2b32629c1a229b6445dad78947f674b44444a75508560405160208082528190810183818151815260200191508051906020019080838360005b838110156107c55780820151838201526020016107ad565b50505050905090810190601f1680156107f25780820380516001836020036101000a031916815260200191505b509250505060405180910390a350505050565b600061080f611101565b60008481526001602081905260409091209092505b838311610922578284161580159061085d5750600083815260068201602052604081205460026000196101006001841615020190911604115b15610917578060060160008481526020019081526020016000208054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561090b5780601f106108e05761010080835404028352916020019161090b565b820191906000526020600020905b8154815290600101906020018083116108ee57829003601f168201915b50505050509150610927565b600290920291610824565b600092505b509250929050565b600080548491600160a060020a033381169216906302571be39084906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b151561098857600080fd5b6102c65a03f1151561099957600080fd5b50505060405180519050600160a060020a03161415156109b857600080fd5b6040805190810160409081528482526020808301859052600087815260019091522060030181518155602082015160019091015550837f1d6f5e03d3f63eb58751986629a5439baee5079ff04f345becb66e23eb154e46848460405191825260208201526040908101905180910390a250505050565b6000908152600160208190526040909120015490565b600090815260016020526040902054600160a060020a031690565b610a67611101565b60008381526001602052604090819020600501908390518082805190602001908083835b60208310610aaa5780518252601f199092019160209182019101610a8b565b6001836020036101000a03801982511681845116808217855250505050505090500191505090815260200160405180910390208054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610b715780601f10610b4657610100808354040283529160200191610b71565b820191906000526020600020905b815481529060010190602001808311610b5457829003601f168201915b5050505050905092915050565b600080548491600160a060020a033381169216906302571be39084906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b1515610bd757600080fd5b6102c65a03f11515610be857600080fd5b50505060405180519050600160a060020a0316141515610c0757600080fd5b6000198301831615610c1857600080fd5b60008481526001602090815260408083208684526006019091529020828051610c45929160200190611083565b5082847faa121bbeef5f32f5961a2a28966e769023910fc9479059ee3495d4c1a696efe360405160405180910390a350505050565b610c82611101565b6001600083600019166000191681526020019081526020016000206002018054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610d345780601f10610d0957610100808354040283529160200191610d34565b820191906000526020600020905b815481529060010190602001808311610d1757829003601f168201915b50505050509050919050565b600080548391600160a060020a033381169216906302571be39084906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b1515610d9957600080fd5b6102c65a03f11515610daa57600080fd5b50505060405180519050600160a060020a0316141515610dc957600080fd5b6000838152600160205260409020600201828051610deb929160200190611083565b50827fb7d29e911041e8d9b843369e890bcb72c9388692ba48b65ac54e7214c4c348f78360405160208082528190810183818151815260200191508051906020019080838360005b83811015610e4b578082015183820152602001610e33565b50505050905090810190601f168015610e785780820380516001836020036101000a031916815260200191505b509250505060405180910390a2505050565b600080548391600160a060020a033381169216906302571be39084906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b1515610ee357600080fd5b6102c65a03f11515610ef457600080fd5b50505060405180519050600160a060020a0316141515610f1357600080fd5b6000838152600160208190526040918290200183905583907f0424b6fe0d9c3bdbece0e7879dc241bb0c22e900be8b6c168b4ee08bd9bf83bc9084905190815260200160405180910390a2505050565b600090815260016020526040902060038101546004909101549091565b600080548391600160a060020a033381169216906302571be39084906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b1515610fd957600080fd5b6102c65a03f11515610fea57600080fd5b50505060405180519050600160a060020a031614151561100957600080fd5b60008381526001602052604090819020805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a03851617905583907f52d7d861f09ab3d26239d492e8968629f95e9e318cf0b73bfddc441522a15fd290849051600160a060020a03909116815260200160405180910390a2505050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106110c457805160ff19168380011785556110f1565b828001600101855582156110f1579182015b828111156110f15782518255916020019190600101906110d6565b506110fd929150611113565b5090565b60206040519081016040526000815290565b61112d91905b808211156110fd5760008155600101611119565b905600a165627a7a723058206016a807d9d5f6060e9c0d1c808e52d4ca30a4cab0140adcc6587bfc13bedf100029" resolver_bytecode_runtime = "606060405236156100a95763ffffffff60e060020a60003504166301ffc9a781146100ae57806310f13a8c146100e25780632203ab561461017c57806329cd62ea146102135780632dff69411461022f5780633b3b57de1461025757806359d1d43c14610289578063623195b014610356578063691f3431146103b257806377372213146103c8578063c3d014d61461041e578063c869023314610437578063d5fa2b0014610465575b600080fd5b34156100b957600080fd5b6100ce600160e060020a031960043516610487565b604051901515815260200160405180910390f35b34156100ed57600080fd5b61017a600480359060446024803590810190830135806020601f8201819004810201604051908101604052818152929190602084018383808284378201915050505050509190803590602001908201803590602001908080601f0160208091040260200160405190810160405281815292919060208401838380828437509496506105f495505050505050565b005b341561018757600080fd5b610195600435602435610805565b60405182815260406020820181815290820183818151815260200191508051906020019080838360005b838110156101d75780820151838201526020016101bf565b50505050905090810190601f1680156102045780820380516001836020036101000a031916815260200191505b50935050505060405180910390f35b341561021e57600080fd5b61017a60043560243560443561092f565b341561023a57600080fd5b610245600435610a2e565b60405190815260200160405180910390f35b341561026257600080fd5b61026d600435610a44565b604051600160a060020a03909116815260200160405180910390f35b341561029457600080fd5b6102df600480359060446024803590810190830135806020601f82018190048102016040519081016040528181529291906020840183838082843750949650610a5f95505050505050565b60405160208082528190810183818151815260200191508051906020019080838360005b8381101561031b578082015183820152602001610303565b50505050905090810190601f1680156103485780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561036157600080fd5b61017a600480359060248035919060649060443590810190830135806020601f82018190048102016040519081016040528181529291906020840183838082843750949650610b7e95505050505050565b34156103bd57600080fd5b6102df600435610c7a565b34156103d357600080fd5b61017a600480359060446024803590810190830135806020601f82018190048102016040519081016040528181529291906020840183838082843750949650610d4095505050505050565b341561042957600080fd5b61017a600435602435610e8a565b341561044257600080fd5b61044d600435610f63565b60405191825260208201526040908101905180910390f35b341561047057600080fd5b61017a600435600160a060020a0360243516610f80565b6000600160e060020a031982167f3b3b57de0000000000000000000000000000000000000000000000000000000014806104ea5750600160e060020a031982167fd8389dc500000000000000000000000000000000000000000000000000000000145b8061051e5750600160e060020a031982167f691f343100000000000000000000000000000000000000000000000000000000145b806105525750600160e060020a031982167f2203ab5600000000000000000000000000000000000000000000000000000000145b806105865750600160e060020a031982167fc869023300000000000000000000000000000000000000000000000000000000145b806105ba5750600160e060020a031982167f59d1d43c00000000000000000000000000000000000000000000000000000000145b806105ee5750600160e060020a031982167f01ffc9a700000000000000000000000000000000000000000000000000000000145b92915050565b600080548491600160a060020a033381169216906302571be39084906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b151561064d57600080fd5b6102c65a03f1151561065e57600080fd5b50505060405180519050600160a060020a031614151561067d57600080fd5b6000848152600160205260409081902083916005909101908590518082805190602001908083835b602083106106c45780518252601f1990920191602091820191016106a5565b6001836020036101000a0380198251168184511680821785525050505050509050019150509081526020016040518091039020908051610708929160200190611083565b50826040518082805190602001908083835b602083106107395780518252601f19909201916020918201910161071a565b6001836020036101000a0380198251168184511617909252505050919091019250604091505051908190039020847fd8c9334b1a9c2f9da342a0a2b32629c1a229b6445dad78947f674b44444a75508560405160208082528190810183818151815260200191508051906020019080838360005b838110156107c55780820151838201526020016107ad565b50505050905090810190601f1680156107f25780820380516001836020036101000a031916815260200191505b509250505060405180910390a350505050565b600061080f611101565b60008481526001602081905260409091209092505b838311610922578284161580159061085d5750600083815260068201602052604081205460026000196101006001841615020190911604115b15610917578060060160008481526020019081526020016000208054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561090b5780601f106108e05761010080835404028352916020019161090b565b820191906000526020600020905b8154815290600101906020018083116108ee57829003601f168201915b50505050509150610927565b600290920291610824565b600092505b509250929050565b600080548491600160a060020a033381169216906302571be39084906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b151561098857600080fd5b6102c65a03f1151561099957600080fd5b50505060405180519050600160a060020a03161415156109b857600080fd5b6040805190810160409081528482526020808301859052600087815260019091522060030181518155602082015160019091015550837f1d6f5e03d3f63eb58751986629a5439baee5079ff04f345becb66e23eb154e46848460405191825260208201526040908101905180910390a250505050565b6000908152600160208190526040909120015490565b600090815260016020526040902054600160a060020a031690565b610a67611101565b60008381526001602052604090819020600501908390518082805190602001908083835b60208310610aaa5780518252601f199092019160209182019101610a8b565b6001836020036101000a03801982511681845116808217855250505050505090500191505090815260200160405180910390208054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610b715780601f10610b4657610100808354040283529160200191610b71565b820191906000526020600020905b815481529060010190602001808311610b5457829003601f168201915b5050505050905092915050565b600080548491600160a060020a033381169216906302571be39084906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b1515610bd757600080fd5b6102c65a03f11515610be857600080fd5b50505060405180519050600160a060020a0316141515610c0757600080fd5b6000198301831615610c1857600080fd5b60008481526001602090815260408083208684526006019091529020828051610c45929160200190611083565b5082847faa121bbeef5f32f5961a2a28966e769023910fc9479059ee3495d4c1a696efe360405160405180910390a350505050565b610c82611101565b6001600083600019166000191681526020019081526020016000206002018054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610d345780601f10610d0957610100808354040283529160200191610d34565b820191906000526020600020905b815481529060010190602001808311610d1757829003601f168201915b50505050509050919050565b600080548391600160a060020a033381169216906302571be39084906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b1515610d9957600080fd5b6102c65a03f11515610daa57600080fd5b50505060405180519050600160a060020a0316141515610dc957600080fd5b6000838152600160205260409020600201828051610deb929160200190611083565b50827fb7d29e911041e8d9b843369e890bcb72c9388692ba48b65ac54e7214c4c348f78360405160208082528190810183818151815260200191508051906020019080838360005b83811015610e4b578082015183820152602001610e33565b50505050905090810190601f168015610e785780820380516001836020036101000a031916815260200191505b509250505060405180910390a2505050565b600080548391600160a060020a033381169216906302571be39084906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b1515610ee357600080fd5b6102c65a03f11515610ef457600080fd5b50505060405180519050600160a060020a0316141515610f1357600080fd5b6000838152600160208190526040918290200183905583907f0424b6fe0d9c3bdbece0e7879dc241bb0c22e900be8b6c168b4ee08bd9bf83bc9084905190815260200160405180910390a2505050565b600090815260016020526040902060038101546004909101549091565b600080548391600160a060020a033381169216906302571be39084906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b1515610fd957600080fd5b6102c65a03f11515610fea57600080fd5b50505060405180519050600160a060020a031614151561100957600080fd5b60008381526001602052604090819020805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a03851617905583907f52d7d861f09ab3d26239d492e8968629f95e9e318cf0b73bfddc441522a15fd290849051600160a060020a03909116815260200160405180910390a2505050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106110c457805160ff19168380011785556110f1565b828001600101855582156110f1579182015b828111156110f15782518255916020019190600101906110d6565b506110fd929150611113565b5090565b60206040519081016040526000815290565b61112d91905b808211156110fd5760008155600101611119565b905600a165627a7a723058206016a807d9d5f6060e9c0d1c808e52d4ca30a4cab0140adcc6587bfc13bedf100029" reverse_registrar_abi = json.loads('[{"constant":false,"inputs":[{"name":"owner","type":"address"},{"name":"resolver","type":"address"}],"name":"claimWithResolver","outputs":[{"name":"node","type":"bytes32"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"owner","type":"address"}],"name":"claim","outputs":[{"name":"node","type":"bytes32"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"ens","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"defaultResolver","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"addr","type":"address"}],"name":"node","outputs":[{"name":"ret","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"name","type":"string"}],"name":"setName","outputs":[{"name":"node","type":"bytes32"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"ensAddr","type":"address"},{"name":"resolverAddr","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"}]') reverse_registrar_bytecode = "6060604052341561000f57600080fd5b604051604080610d96833981016040528080519060200190919080519060200190919050506000826000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555081600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166302571be37f91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e26001026000604051602001526040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808260001916600019168152602001915050602060405180830381600087803b151561017a57600080fd5b6102c65a03f1151561018b57600080fd5b50505060405180519050905060008173ffffffffffffffffffffffffffffffffffffffff16141515610277578073ffffffffffffffffffffffffffffffffffffffff16631e83409a336000604051602001526040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001915050602060405180830381600087803b151561025a57600080fd5b6102c65a03f1151561026b57600080fd5b50505060405180519050505b505050610b0d806102896000396000f300606060405260043610610078576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680630f5a54661461007d5780631e83409a146100f15780633f15457f14610146578063828eab0e1461019b578063bffbe61c146101f0578063c47f002714610245575b600080fd5b341561008857600080fd5b6100d3600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506102be565b60405180826000191660001916815260200191505060405180910390f35b34156100fc57600080fd5b610128600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190505061086e565b60405180826000191660001916815260200191505060405180910390f35b341561015157600080fd5b610159610882565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34156101a657600080fd5b6101ae6108a7565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34156101fb57600080fd5b610227600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506108cd565b60405180826000191660001916815260200191505060405180910390f35b341561025057600080fd5b6102a0600480803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509190505061092f565b60405180826000191660001916815260200191505060405180910390f35b60008060006102cc33610a80565b91507f91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e260010282604051808360001916600019168152602001826000191660001916815260200192505050604051809103902092506000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166302571be3846000604051602001526040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808260001916600019168152602001915050602060405180830381600087803b15156103c157600080fd5b6102c65a03f115156103d257600080fd5b50505060405180519050905060008473ffffffffffffffffffffffffffffffffffffffff16141580156104eb57506000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16630178b8bf846000604051602001526040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808260001916600019168152602001915050602060405180830381600087803b15156104a057600080fd5b6102c65a03f115156104b157600080fd5b5050506040518051905073ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff1614155b1561071b573073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614151561063b576000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166306ab59237f91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e260010284306040518463ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180846000191660001916815260200183600019166000191681526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019350505050600060405180830381600087803b151561062357600080fd5b6102c65a03f1151561063457600080fd5b5050503090505b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16631896f70a84866040518363ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018083600019166000191681526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200192505050600060405180830381600087803b151561070657600080fd5b6102c65a03f1151561071757600080fd5b5050505b8473ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16141515610863576000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166306ab59237f91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e260010284886040518463ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180846000191660001916815260200183600019166000191681526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019350505050600060405180830381600087803b151561084e57600080fd5b6102c65a03f1151561085f57600080fd5b5050505b829250505092915050565b600061087b8260006102be565b9050919050565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60007f91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e26001026108fc83610a80565b60405180836000191660001916815260200182600019166000191681526020019250505060405180910390209050919050565b600061095d30600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff166102be565b9050600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16637737221382846040518363ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180836000191660001916815260200180602001828103825283818151815260200191508051906020019080838360005b83811015610a185780820151818401526020810190506109fd565b50505050905090810190601f168015610a455780820380516001836020036101000a031916815260200191505b509350505050600060405180830381600087803b1515610a6457600080fd5b6102c65a03f11515610a7557600080fd5b505050809050919050565b60007f303132333435363738396162636465660000000000000000000000000000000060285b60018103905081600f85161a815360108404935060018103905081600f85161a815360108404935080610aa6576028600020925050509190505600a165627a7a72305820a8513240f040cd9ded89ca4d0c5bda58536850e642e1d933ad64158ef4c820660029" reverse_registrar_bytecode_runtime = "606060405260043610610078576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680630f5a54661461007d5780631e83409a146100f15780633f15457f14610146578063828eab0e1461019b578063bffbe61c146101f0578063c47f002714610245575b600080fd5b341561008857600080fd5b6100d3600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506102be565b60405180826000191660001916815260200191505060405180910390f35b34156100fc57600080fd5b610128600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190505061086e565b60405180826000191660001916815260200191505060405180910390f35b341561015157600080fd5b610159610882565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34156101a657600080fd5b6101ae6108a7565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34156101fb57600080fd5b610227600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506108cd565b60405180826000191660001916815260200191505060405180910390f35b341561025057600080fd5b6102a0600480803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509190505061092f565b60405180826000191660001916815260200191505060405180910390f35b60008060006102cc33610a80565b91507f91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e260010282604051808360001916600019168152602001826000191660001916815260200192505050604051809103902092506000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166302571be3846000604051602001526040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808260001916600019168152602001915050602060405180830381600087803b15156103c157600080fd5b6102c65a03f115156103d257600080fd5b50505060405180519050905060008473ffffffffffffffffffffffffffffffffffffffff16141580156104eb57506000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16630178b8bf846000604051602001526040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808260001916600019168152602001915050602060405180830381600087803b15156104a057600080fd5b6102c65a03f115156104b157600080fd5b5050506040518051905073ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff1614155b1561071b573073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614151561063b576000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166306ab59237f91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e260010284306040518463ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180846000191660001916815260200183600019166000191681526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019350505050600060405180830381600087803b151561062357600080fd5b6102c65a03f1151561063457600080fd5b5050503090505b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16631896f70a84866040518363ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018083600019166000191681526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200192505050600060405180830381600087803b151561070657600080fd5b6102c65a03f1151561071757600080fd5b5050505b8473ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16141515610863576000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166306ab59237f91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e260010284886040518463ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180846000191660001916815260200183600019166000191681526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019350505050600060405180830381600087803b151561084e57600080fd5b6102c65a03f1151561085f57600080fd5b5050505b829250505092915050565b600061087b8260006102be565b9050919050565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60007f91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e26001026108fc83610a80565b60405180836000191660001916815260200182600019166000191681526020019250505060405180910390209050919050565b600061095d30600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff166102be565b9050600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16637737221382846040518363ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180836000191660001916815260200180602001828103825283818151815260200191508051906020019080838360005b83811015610a185780820151818401526020810190506109fd565b50505050905090810190601f168015610a455780820380516001836020036101000a031916815260200191505b509350505050600060405180830381600087803b1515610a6457600080fd5b6102c65a03f11515610a7557600080fd5b505050809050919050565b60007f303132333435363738396162636465660000000000000000000000000000000060285b60018103905081600f85161a815360108404935060018103905081600f85161a815360108404935080610aa6576028600020925050509190505600a165627a7a72305820a8513240f040cd9ded89ca4d0c5bda58536850e642e1d933ad64158ef4c820660029" reverse_resolver_abi = json.loads('[{"constant":true,"inputs":[],"name":"ens","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"bytes32"}],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"node","type":"bytes32"},{"name":"_name","type":"string"}],"name":"setName","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"ensAddr","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"}]') reverse_resolver_bytecode = "6060604052341561000f57600080fd5b6040516020806106c9833981016040528080519060200190919050506000816000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166302571be37f91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e26001026000604051602001526040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808260001916600019168152602001915050602060405180830381600087803b151561013057600080fd5b6102c65a03f1151561014157600080fd5b50505060405180519050905060008173ffffffffffffffffffffffffffffffffffffffff1614151561022d578073ffffffffffffffffffffffffffffffffffffffff16631e83409a336000604051602001526040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001915050602060405180830381600087803b151561021057600080fd5b6102c65a03f1151561022157600080fd5b50505060405180519050505b505061048b8061023e6000396000f300606060405260043610610057576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680633f15457f1461005c578063691f3431146100b15780637737221314610151575b600080fd5b341561006757600080fd5b61006f6101bb565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34156100bc57600080fd5b6100d66004808035600019169060200190919050506101e0565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101165780820151818401526020810190506100fb565b50505050905090810190601f1680156101435780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561015c57600080fd5b6101b960048080356000191690602001909190803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091905050610290565b005b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60016020528060005260406000206000915090508054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156102885780601f1061025d57610100808354040283529160200191610288565b820191906000526020600020905b81548152906001019060200180831161026b57829003601f168201915b505050505081565b816000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166302571be3826000604051602001526040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808260001916600019168152602001915050602060405180830381600087803b151561033157600080fd5b6102c65a03f1151561034257600080fd5b5050506040518051905073ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561038557600080fd5b8160016000856000191660001916815260200190815260200160002090805190602001906103b49291906103ba565b50505050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106103fb57805160ff1916838001178555610429565b82800160010185558215610429579182015b8281111561042857825182559160200191906001019061040d565b5b509050610436919061043a565b5090565b61045c91905b80821115610458576000816000905550600101610440565b5090565b905600a165627a7a72305820f4c4cb4d191f31a62c4de12f7aecf9b258ba17f3a6ee294191171f7d30c04ab00029" reverse_resolver_bytecode_runtime = "606060405260043610610057576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680633f15457f1461005c578063691f3431146100b15780637737221314610151575b600080fd5b341561006757600080fd5b61006f6101bb565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34156100bc57600080fd5b6100d66004808035600019169060200190919050506101e0565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101165780820151818401526020810190506100fb565b50505050905090810190601f1680156101435780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561015c57600080fd5b6101b960048080356000191690602001909190803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091905050610290565b005b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60016020528060005260406000206000915090508054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156102885780601f1061025d57610100808354040283529160200191610288565b820191906000526020600020905b81548152906001019060200180831161026b57829003601f168201915b505050505081565b816000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166302571be3826000604051602001526040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808260001916600019168152602001915050602060405180830381600087803b151561033157600080fd5b6102c65a03f1151561034257600080fd5b5050506040518051905073ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561038557600080fd5b8160016000856000191660001916815260200190815260200160002090805190602001906103b49291906103ba565b50505050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106103fb57805160ff1916838001178555610429565b82800160010185558215610429579182015b8281111561042857825182559160200191906001019061040d565b5b509050610436919061043a565b5090565b61045c91905b80821115610458576000816000905550600101610440565b5090565b905600a165627a7a72305820f4c4cb4d191f31a62c4de12f7aecf9b258ba17f3a6ee294191171f7d30c04ab00029"
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/ens/contract_data.py
contract_data.py
ACCEPTABLE_STALE_HOURS = 48 AUCTION_START_GAS_CONSTANT = 25000 AUCTION_START_GAS_MARGINAL = 39000 EMPTY_SHA3_BYTES = b'\0' * 32 EMPTY_ADDR_HEX = '0x' + '00' * 20 MIN_ETH_LABEL_LENGTH = 7 REVERSE_REGISTRAR_DOMAIN = 'addr.reverse'
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/ens/constants.py
constants.py
from eth_utils import ( is_binary_address, is_checksum_address, to_checksum_address, ) from ens import abis from ens.constants import ( EMPTY_ADDR_HEX, REVERSE_REGISTRAR_DOMAIN, ) from ens.exceptions import ( AddressMismatch, UnauthorizedError, UnownedName, ) from ens.utils import ( address_in, address_to_reverse_domain, default, dict_copy, init_web3, is_none_or_zero_address, is_valid_name, label_to_hash, normal_name_to_hash, normalize_name, raw_name_to_hash, ) ENS_MAINNET_ADDR = '0x314159265dD8dbb310642f98f50C066173C1259b' class ENS: """ Quick access to common Ethereum Name Service functions, like getting the address for a name. Unless otherwise specified, all addresses are assumed to be a `str` in `checksum format <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md>`_, like: ``"0x314159265dD8dbb310642f98f50C066173C1259b"`` """ labelhash = staticmethod(label_to_hash) namehash = staticmethod(raw_name_to_hash) nameprep = staticmethod(normalize_name) is_valid_name = staticmethod(is_valid_name) reverse_domain = staticmethod(address_to_reverse_domain) def __init__(self, provider=default, addr=None): """ :param provider: a single provider used to connect to Ethereum :type provider: instance of `web3.providers.base.BaseProvider` :param hex-string addr: the address of the ENS registry on-chain. If not provided, ENS.py will default to the mainnet ENS registry address. """ self.web3 = init_web3(provider) ens_addr = addr if addr else ENS_MAINNET_ADDR self.ens = self.web3.eth.contract(abi=abis.ENS, address=ens_addr) self._resolverContract = self.web3.eth.contract(abi=abis.RESOLVER) @classmethod def fromWeb3(cls, web3, addr=None): """ Generate an ENS instance with web3 :param `web3.Web3` web3: to infer connection information :param hex-string addr: the address of the ENS registry on-chain. If not provided, ENS.py will default to the mainnet ENS registry address. """ return cls(web3.manager.provider, addr=addr) def address(self, name): """ Look up the Ethereum address that `name` currently points to. :param str name: an ENS name to look up :raises InvalidName: if `name` has invalid syntax """ return self.resolve(name, 'addr') def name(self, address): """ Look up the name that the address points to, using a reverse lookup. Reverse lookup is opt-in for name owners. :param address: :type address: hex-string """ reversed_domain = address_to_reverse_domain(address) return self.resolve(reversed_domain, get='name') @dict_copy def setup_address(self, name, address=default, transact={}): """ Set up the name to point to the supplied address. The sender of the transaction must own the name, or its parent name. Example: If the caller owns ``parentname.eth`` with no subdomains and calls this method with ``sub.parentname.eth``, then ``sub`` will be created as part of this call. :param str name: ENS name to set up :param str address: name will point to this address, in checksum format. If ``None``, erase the record. If not specified, name will point to the owner's address. :param dict transact: the transaction configuration, like in :meth:`~web3.eth.Eth.sendTransaction` :raises InvalidName: if ``name`` has invalid syntax :raises UnauthorizedError: if ``'from'`` in `transact` does not own `name` """ owner = self.setup_owner(name, transact=transact) self._assert_control(owner, name) if is_none_or_zero_address(address): address = None elif address is default: address = owner elif is_binary_address(address): address = to_checksum_address(address) elif not is_checksum_address(address): raise ValueError("You must supply the address in checksum format") if self.address(name) == address: return None if address is None: address = EMPTY_ADDR_HEX transact['from'] = owner resolver = self._set_resolver(name, transact=transact) return resolver.functions.setAddr(raw_name_to_hash(name), address).transact(transact) @dict_copy def setup_name(self, name, address=None, transact={}): """ Set up the address for reverse lookup, aka "caller ID". After successful setup, the method :meth:`~ens.main.ENS.name` will return `name` when supplied with `address`. :param str name: ENS name that address will point to :param str address: to set up, in checksum format :param dict transact: the transaction configuration, like in :meth:`~web3.eth.sendTransaction` :raises AddressMismatch: if the name does not already point to the address :raises InvalidName: if `name` has invalid syntax :raises UnauthorizedError: if ``'from'`` in `transact` does not own `name` :raises UnownedName: if no one owns `name` """ if not name: self._assert_control(address, 'the reverse record') return self._setup_reverse(None, address, transact=transact) else: resolved = self.address(name) if is_none_or_zero_address(address): address = resolved elif resolved and address != resolved and resolved != EMPTY_ADDR_HEX: raise AddressMismatch( "Could not set address %r to point to name, because the name resolves to %r. " "To change the name for an existing address, call setup_address() first." % ( address, resolved ) ) if is_none_or_zero_address(address): address = self.owner(name) if is_none_or_zero_address(address): raise UnownedName("claim subdomain using setup_address() first") if is_binary_address(address): address = to_checksum_address(address) if not is_checksum_address(address): raise ValueError("You must supply the address in checksum format") self._assert_control(address, name) if not resolved: self.setup_address(name, address, transact=transact) return self._setup_reverse(name, address, transact=transact) def resolve(self, name, get='addr'): normal_name = normalize_name(name) resolver = self.resolver(normal_name) if resolver: lookup_function = getattr(resolver.functions, get) namehash = normal_name_to_hash(normal_name) address = lookup_function(namehash).call() if is_none_or_zero_address(address): return None return lookup_function(namehash).call() else: return None def resolver(self, normal_name): resolver_addr = self.ens.caller.resolver(normal_name_to_hash(normal_name)) if is_none_or_zero_address(resolver_addr): return None return self._resolverContract(address=resolver_addr) def reverser(self, target_address): reversed_domain = address_to_reverse_domain(target_address) return self.resolver(reversed_domain) def owner(self, name): """ Get the owner of a name. Note that this may be different from the deed holder in the '.eth' registrar. Learn more about the difference between deed and name ownership in the ENS `Managing Ownership docs <http://docs.ens.domains/en/latest/userguide.html#managing-ownership>`_ :param str name: ENS name to look up :return: owner address :rtype: str """ node = raw_name_to_hash(name) return self.ens.caller.owner(node) @dict_copy def setup_owner(self, name, new_owner=default, transact={}): """ Set the owner of the supplied name to `new_owner`. For typical scenarios, you'll never need to call this method directly, simply call :meth:`setup_name` or :meth:`setup_address`. This method does *not* set up the name to point to an address. If `new_owner` is not supplied, then this will assume you want the same owner as the parent domain. If the caller owns ``parentname.eth`` with no subdomains and calls this method with ``sub.parentname.eth``, then ``sub`` will be created as part of this call. :param str name: ENS name to set up :param new_owner: account that will own `name`. If ``None``, set owner to empty addr. If not specified, name will point to the parent domain owner's address. :param dict transact: the transaction configuration, like in :meth:`~web3.eth.Eth.sendTransaction` :raises InvalidName: if `name` has invalid syntax :raises UnauthorizedError: if ``'from'`` in `transact` does not own `name` :returns: the new owner's address """ (super_owner, unowned, owned) = self._first_owner(name) if new_owner is default: new_owner = super_owner elif not new_owner: new_owner = EMPTY_ADDR_HEX else: new_owner = to_checksum_address(new_owner) current_owner = self.owner(name) if new_owner == EMPTY_ADDR_HEX and not current_owner: return None elif current_owner == new_owner: return current_owner else: self._assert_control(super_owner, name, owned) self._claim_ownership(new_owner, unowned, owned, super_owner, transact=transact) return new_owner def _assert_control(self, account, name, parent_owned=None): if not address_in(account, self.web3.eth.accounts): raise UnauthorizedError( "in order to modify %r, you must control account %r, which owns %r" % ( name, account, parent_owned or name ) ) def _first_owner(self, name): """ Takes a name, and returns the owner of the deepest subdomain that has an owner :returns: (owner or None, list(unowned_subdomain_labels), first_owned_domain) """ owner = None unowned = [] pieces = normalize_name(name).split('.') while pieces and is_none_or_zero_address(owner): name = '.'.join(pieces) owner = self.owner(name) if is_none_or_zero_address(owner): unowned.append(pieces.pop(0)) return (owner, unowned, name) @dict_copy def _claim_ownership(self, owner, unowned, owned, old_owner=None, transact={}): transact['from'] = old_owner or owner for label in reversed(unowned): self.ens.functions.setSubnodeOwner( raw_name_to_hash(owned), label_to_hash(label), owner ).transact(transact) owned = "%s.%s" % (label, owned) @dict_copy def _set_resolver(self, name, resolver_addr=None, transact={}): if is_none_or_zero_address(resolver_addr): resolver_addr = self.address('resolver.eth') namehash = raw_name_to_hash(name) if self.ens.caller.resolver(namehash) != resolver_addr: self.ens.functions.setResolver( namehash, resolver_addr ).transact(transact) return self._resolverContract(address=resolver_addr) @dict_copy def _setup_reverse(self, name, address, transact={}): if name: name = normalize_name(name) else: name = '' transact['from'] = address return self._reverse_registrar().functions.setName(name).transact(transact) def _reverse_registrar(self): addr = self.ens.caller.owner(normal_name_to_hash(REVERSE_REGISTRAR_DOMAIN)) return self.web3.eth.contract(address=addr, abi=abis.REVERSE_REGISTRAR)
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/ens/main.py
main.py
from ens import ENS ns = ENS()
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/ens/auto.py
auto.py
import copy import datetime import functools from eth_utils import ( is_same_address, remove_0x_prefix, to_normalized_address, ) import idna from ens.constants import ( ACCEPTABLE_STALE_HOURS, AUCTION_START_GAS_CONSTANT, AUCTION_START_GAS_MARGINAL, EMPTY_SHA3_BYTES, MIN_ETH_LABEL_LENGTH, REVERSE_REGISTRAR_DOMAIN, ) from ens.exceptions import ( InvalidLabel, InvalidName, ) default = object() def Web3(): from web3 import Web3 return Web3 def dict_copy(func): "copy dict keyword args, to avoid modifying caller's copy" @functools.wraps(func) def wrapper(*args, **kwargs): copied_kwargs = copy.deepcopy(kwargs) return func(*args, **copied_kwargs) return wrapper def ensure_hex(data): if not isinstance(data, str): return Web3().toHex(data) return data def init_web3(providers=default): from web3 import Web3 if providers is default: w3 = Web3(ens=None) else: w3 = Web3(providers, ens=None) return customize_web3(w3) def customize_web3(w3): from web3.middleware import make_stalecheck_middleware w3.middleware_onion.remove('name_to_address') w3.middleware_onion.add( make_stalecheck_middleware(ACCEPTABLE_STALE_HOURS * 3600), name='stalecheck', ) return w3 def normalize_name(name): """ Clean the fully qualified name, as defined in ENS `EIP-137 <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-137.md#name-syntax>`_ This does *not* enforce whether ``name`` is a label or fully qualified domain. :param str name: the dot-separated ENS name :raises InvalidName: if ``name`` has invalid syntax """ if not name: return name elif isinstance(name, (bytes, bytearray)): name = name.decode('utf-8') try: return idna.decode(name, uts46=True, std3_rules=True) except idna.IDNAError as exc: raise InvalidName("%s is an invalid name, because %s" % (name, exc)) from exc def is_valid_name(name): """ Validate whether the fully qualified name is valid, as defined in ENS `EIP-137 <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-137.md#name-syntax>`_ :param str name: the dot-separated ENS name :returns: True if ``name`` is set, and :meth:`~ens.main.ENS.nameprep` will not raise InvalidName """ if not name: return False try: normalize_name(name) return True except InvalidName: return False def name_to_label(name, registrar): name = normalize_name(name) if '.' not in name: label = name else: name_pieces = name.split('.') registrar_pieces = registrar.split('.') if len(name_pieces) != len(registrar_pieces) + 1: raise ValueError( "You must specify a label, like 'tickets' " "or a fully-qualified name, like 'tickets.%s'" % registrar ) label, *label_registrar = name_pieces if label_registrar != registrar_pieces: raise ValueError("This interface only manages names under .%s " % registrar) return label def dot_eth_label(name): """ Convert from a name, like 'ethfinex.eth', to a label, like 'ethfinex' If name is already a label, this should be a noop, except for converting to a string and validating the name syntax. """ label = name_to_label(name, registrar='eth') if len(label) < MIN_ETH_LABEL_LENGTH: raise InvalidLabel('name %r is too short' % label) else: return label def to_utc_datetime(timestamp): if timestamp: return datetime.datetime.fromtimestamp(timestamp, datetime.timezone.utc) else: return None def sha3_text(val): if isinstance(val, str): val = val.encode('utf-8') return Web3().keccak(val) def label_to_hash(label): label = normalize_name(label) if '.' in label: raise ValueError("Cannot generate hash for label %r with a '.'" % label) return Web3().keccak(text=label) def normal_name_to_hash(name): node = EMPTY_SHA3_BYTES if name: labels = name.split(".") for label in reversed(labels): labelhash = label_to_hash(label) assert isinstance(labelhash, bytes) assert isinstance(node, bytes) node = Web3().keccak(node + labelhash) return node def raw_name_to_hash(name): """ Generate the namehash. This is also known as the ``node`` in ENS contracts. In normal operation, generating the namehash is handled behind the scenes. For advanced usage, it is a helpful utility. This normalizes the name with `nameprep <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-137.md#name-syntax>`_ before hashing. :param str name: ENS name to hash :return: the namehash :rtype: bytes :raises InvalidName: if ``name`` has invalid syntax """ normalized_name = normalize_name(name) return normal_name_to_hash(normalized_name) def address_in(address, addresses): return any(is_same_address(address, item) for item in addresses) def address_to_reverse_domain(address): lower_unprefixed_address = remove_0x_prefix(to_normalized_address(address)) return lower_unprefixed_address + '.' + REVERSE_REGISTRAR_DOMAIN def estimate_auction_start_gas(labels): return AUCTION_START_GAS_CONSTANT + AUCTION_START_GAS_MARGINAL * len(labels) def assert_signer_in_modifier_kwargs(modifier_kwargs): ERR_MSG = "You must specify the sending account" assert len(modifier_kwargs) == 1, ERR_MSG _modifier_type, modifier_dict = dict(modifier_kwargs).popitem() if 'from' not in modifier_dict: raise TypeError(ERR_MSG) return modifier_dict['from'] def is_none_or_zero_address(addr): return not addr or addr == '0x' + '00' * 20
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/ens/utils.py
utils.py
# flake8: noqa from .main import ( ENS, ) from .exceptions import ( AddressMismatch, BidTooLow, InvalidLabel, InvalidName, UnauthorizedError, UnderfundedBid, UnownedName, )
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/ens/__init__.py
__init__.py
# flake8: noqa ENS = [ { "constant": True, "inputs": [ { "name": "node", "type": "bytes32" } ], "name": "resolver", "outputs": [ { "name": "", "type": "address" } ], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "node", "type": "bytes32" } ], "name": "owner", "outputs": [ { "name": "", "type": "address" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "label", "type": "bytes32" }, { "name": "owner", "type": "address" } ], "name": "setSubnodeOwner", "outputs": [], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "ttl", "type": "uint64" } ], "name": "setTTL", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "node", "type": "bytes32" } ], "name": "ttl", "outputs": [ { "name": "", "type": "uint64" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "resolver", "type": "address" } ], "name": "setResolver", "outputs": [], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "owner", "type": "address" } ], "name": "setOwner", "outputs": [], "payable": False, "type": "function" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "node", "type": "bytes32" }, { "indexed": False, "name": "owner", "type": "address" } ], "name": "Transfer", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "node", "type": "bytes32" }, { "indexed": True, "name": "label", "type": "bytes32" }, { "indexed": False, "name": "owner", "type": "address" } ], "name": "NewOwner", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "node", "type": "bytes32" }, { "indexed": False, "name": "resolver", "type": "address" } ], "name": "NewResolver", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "node", "type": "bytes32" }, { "indexed": False, "name": "ttl", "type": "uint64" } ], "name": "NewTTL", "type": "event" } ] AUCTION_REGISTRAR = [ { "constant": False, "inputs": [ { "name": "_hash", "type": "bytes32" } ], "name": "releaseDeed", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "_hash", "type": "bytes32" } ], "name": "getAllowedTime", "outputs": [ { "name": "timestamp", "type": "uint256" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "unhashedName", "type": "string" } ], "name": "invalidateName", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "hash", "type": "bytes32" }, { "name": "owner", "type": "address" }, { "name": "value", "type": "uint256" }, { "name": "salt", "type": "bytes32" } ], "name": "shaBid", "outputs": [ { "name": "sealedBid", "type": "bytes32" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "bidder", "type": "address" }, { "name": "seal", "type": "bytes32" } ], "name": "cancelBid", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "_hash", "type": "bytes32" } ], "name": "entries", "outputs": [ { "name": "", "type": "uint8" }, { "name": "", "type": "address" }, { "name": "", "type": "uint256" }, { "name": "", "type": "uint256" }, { "name": "", "type": "uint256" } ], "payable": False, "type": "function" }, { "constant": True, "inputs": [], "name": "ens", "outputs": [ { "name": "", "type": "address" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "_hash", "type": "bytes32" }, { "name": "_value", "type": "uint256" }, { "name": "_salt", "type": "bytes32" } ], "name": "unsealBid", "outputs": [], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "_hash", "type": "bytes32" } ], "name": "transferRegistrars", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "", "type": "address" }, { "name": "", "type": "bytes32" } ], "name": "sealedBids", "outputs": [ { "name": "", "type": "address" } ], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "_hash", "type": "bytes32" } ], "name": "state", "outputs": [ { "name": "", "type": "uint8" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "_hash", "type": "bytes32" }, { "name": "newOwner", "type": "address" } ], "name": "transfer", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "_hash", "type": "bytes32" }, { "name": "_timestamp", "type": "uint256" } ], "name": "isAllowed", "outputs": [ { "name": "allowed", "type": "bool" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "_hash", "type": "bytes32" } ], "name": "finalizeAuction", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [], "name": "registryStarted", "outputs": [ { "name": "", "type": "uint256" } ], "payable": False, "type": "function" }, { "constant": True, "inputs": [], "name": "launchLength", "outputs": [ { "name": "", "type": "uint32" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "sealedBid", "type": "bytes32" } ], "name": "newBid", "outputs": [], "payable": True, "type": "function" }, { "constant": False, "inputs": [ { "name": "labels", "type": "bytes32[]" } ], "name": "eraseNode", "outputs": [], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "_hashes", "type": "bytes32[]" } ], "name": "startAuctions", "outputs": [], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "hash", "type": "bytes32" }, { "name": "deed", "type": "address" }, { "name": "registrationDate", "type": "uint256" } ], "name": "acceptRegistrarTransfer", "outputs": [], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "_hash", "type": "bytes32" } ], "name": "startAuction", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [], "name": "rootNode", "outputs": [ { "name": "", "type": "bytes32" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "hashes", "type": "bytes32[]" }, { "name": "sealedBid", "type": "bytes32" } ], "name": "startAuctionsAndBid", "outputs": [], "payable": True, "type": "function" }, { "inputs": [ { "name": "_ens", "type": "address" }, { "name": "_rootNode", "type": "bytes32" }, { "name": "_startDate", "type": "uint256" } ], "payable": False, "type": "constructor" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "hash", "type": "bytes32" }, { "indexed": False, "name": "registrationDate", "type": "uint256" } ], "name": "AuctionStarted", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "hash", "type": "bytes32" }, { "indexed": True, "name": "bidder", "type": "address" }, { "indexed": False, "name": "deposit", "type": "uint256" } ], "name": "NewBid", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "hash", "type": "bytes32" }, { "indexed": True, "name": "owner", "type": "address" }, { "indexed": False, "name": "value", "type": "uint256" }, { "indexed": False, "name": "status", "type": "uint8" } ], "name": "BidRevealed", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "hash", "type": "bytes32" }, { "indexed": True, "name": "owner", "type": "address" }, { "indexed": False, "name": "value", "type": "uint256" }, { "indexed": False, "name": "registrationDate", "type": "uint256" } ], "name": "HashRegistered", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "hash", "type": "bytes32" }, { "indexed": False, "name": "value", "type": "uint256" } ], "name": "HashReleased", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "hash", "type": "bytes32" }, { "indexed": True, "name": "name", "type": "string" }, { "indexed": False, "name": "value", "type": "uint256" }, { "indexed": False, "name": "registrationDate", "type": "uint256" } ], "name": "HashInvalidated", "type": "event" } ] DEED = [ { "constant": True, "inputs": [], "name": "creationDate", "outputs": [ { "name": "", "type": "uint256" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [], "name": "destroyDeed", "outputs": [], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "newOwner", "type": "address" } ], "name": "setOwner", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [], "name": "registrar", "outputs": [ { "name": "", "type": "address" } ], "payable": False, "type": "function" }, { "constant": True, "inputs": [], "name": "owner", "outputs": [ { "name": "", "type": "address" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "refundRatio", "type": "uint256" } ], "name": "closeDeed", "outputs": [], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "newRegistrar", "type": "address" } ], "name": "setRegistrar", "outputs": [], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "newValue", "type": "uint256" } ], "name": "setBalance", "outputs": [], "payable": True, "type": "function" }, { "inputs": [], "type": "constructor" }, { "payable": True, "type": "fallback" }, { "anonymous": False, "inputs": [ { "indexed": False, "name": "newOwner", "type": "address" } ], "name": "OwnerChanged", "type": "event" }, { "anonymous": False, "inputs": [], "name": "DeedClosed", "type": "event" } ] FIFS_REGISTRAR = [ { "constant": True, "inputs": [], "name": "ens", "outputs": [ { "name": "", "type": "address" } ], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "", "type": "bytes32" } ], "name": "expiryTimes", "outputs": [ { "name": "", "type": "uint256" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "subnode", "type": "bytes32" }, { "name": "owner", "type": "address" } ], "name": "register", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [], "name": "rootNode", "outputs": [ { "name": "", "type": "bytes32" } ], "payable": False, "type": "function" }, { "inputs": [ { "name": "ensAddr", "type": "address" }, { "name": "node", "type": "bytes32" } ], "type": "constructor" } ] RESOLVER = [ { "constant": True, "inputs": [ { "name": "interfaceID", "type": "bytes4" } ], "name": "supportsInterface", "outputs": [ { "name": "", "type": "bool" } ], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "contentTypes", "type": "uint256" } ], "name": "ABI", "outputs": [ { "name": "contentType", "type": "uint256" }, { "name": "data", "type": "bytes" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "x", "type": "bytes32" }, { "name": "y", "type": "bytes32" } ], "name": "setPubkey", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "node", "type": "bytes32" } ], "name": "content", "outputs": [ { "name": "ret", "type": "bytes32" } ], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "node", "type": "bytes32" } ], "name": "addr", "outputs": [ { "name": "ret", "type": "address" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "contentType", "type": "uint256" }, { "name": "data", "type": "bytes" } ], "name": "setABI", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "node", "type": "bytes32" } ], "name": "name", "outputs": [ { "name": "ret", "type": "string" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "name", "type": "string" } ], "name": "setName", "outputs": [], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "hash", "type": "bytes32" } ], "name": "setContent", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "node", "type": "bytes32" } ], "name": "pubkey", "outputs": [ { "name": "x", "type": "bytes32" }, { "name": "y", "type": "bytes32" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "addr", "type": "address" } ], "name": "setAddr", "outputs": [], "payable": False, "type": "function" }, { "inputs": [ { "name": "ensAddr", "type": "address" } ], "payable": False, "type": "constructor" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "node", "type": "bytes32" }, { "indexed": False, "name": "a", "type": "address" } ], "name": "AddrChanged", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "node", "type": "bytes32" }, { "indexed": False, "name": "hash", "type": "bytes32" } ], "name": "ContentChanged", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "node", "type": "bytes32" }, { "indexed": False, "name": "name", "type": "string" } ], "name": "NameChanged", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "node", "type": "bytes32" }, { "indexed": True, "name": "contentType", "type": "uint256" } ], "name": "ABIChanged", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "node", "type": "bytes32" }, { "indexed": False, "name": "x", "type": "bytes32" }, { "indexed": False, "name": "y", "type": "bytes32" } ], "name": "PubkeyChanged", "type": "event" } ] REVERSE_REGISTRAR = [ { "constant": False, "inputs": [ { "name": "owner", "type": "address" }, { "name": "resolver", "type": "address" } ], "name": "claimWithResolver", "outputs": [ { "name": "node", "type": "bytes32" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "owner", "type": "address" } ], "name": "claim", "outputs": [ { "name": "node", "type": "bytes32" } ], "payable": False, "type": "function" }, { "constant": True, "inputs": [], "name": "ens", "outputs": [ { "name": "", "type": "address" } ], "payable": False, "type": "function" }, { "constant": True, "inputs": [], "name": "defaultResolver", "outputs": [ { "name": "", "type": "address" } ], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "addr", "type": "address" } ], "name": "node", "outputs": [ { "name": "ret", "type": "bytes32" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "name", "type": "string" } ], "name": "setName", "outputs": [ { "name": "node", "type": "bytes32" } ], "payable": False, "type": "function" }, { "inputs": [ { "name": "ensAddr", "type": "address" }, { "name": "resolverAddr", "type": "address" } ], "payable": False, "type": "constructor" } ]
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/ens/abis.py
abis.py
import idna class AddressMismatch(ValueError): """ In order to set up reverse resolution correctly, the ENS name should first point to the address. This exception is raised if the name does not currently point to the address. """ pass class InvalidName(idna.IDNAError): """ This exception is raised if the provided name does not meet the syntax standards specified in `EIP 137 name syntax <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-137.md#name-syntax>`_. For example: names may not start with a dot, or include a space. """ pass class UnauthorizedError(Exception): """ Raised if the sending account is not the owner of the name you are trying to modify. Make sure to set ``from`` in the ``transact`` keyword argument to the owner of the name. """ pass class UnownedName(Exception): """ Raised if you are trying to modify a name that no one owns. If working on a subdomain, make sure the subdomain gets created first with :meth:`~ens.main.ENS.setup_address`. """ pass class BidTooLow(ValueError): """ Raised if you bid less than the minimum amount """ pass class InvalidBidHash(ValueError): """ Raised if you supply incorrect data to generate the bid hash. """ pass class InvalidLabel(ValueError): """ Raised if you supply an invalid label """ pass class OversizeTransaction(ValueError): """ Raised if a transaction you are trying to create would cost so much gas that it could not fit in a block. For example: when you try to start too many auctions at once. """ pass class UnderfundedBid(ValueError): """ Raised if you send less wei with your bid than you declared as your intent to bid. """ pass
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/ens/exceptions.py
exceptions.py
from web3.module import ( Module, ) class Net(Module): @property def listening(self): return self.web3.manager.request_blocking("net_listening", []) @property def peerCount(self): return self.web3.manager.request_blocking("net_peerCount", []) @property def chainId(self): return None @property def version(self): return self.web3.manager.request_blocking("net_version", [])
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/net.py
net.py
from web3.module import ( Module, ) class Miner(Module): def makeDAG(self, number): return self.web3.manager.request_blocking("miner_makeDag", [number]) def setExtra(self, extra): return self.web3.manager.request_blocking("miner_setExtra", [extra]) def setEtherBase(self, etherbase): return self.web3.manager.request_blocking("miner_setEtherbase", [etherbase]) def setGasPrice(self, gas_price): return self.web3.manager.request_blocking( "miner_setGasPrice", [gas_price], ) def start(self, num_threads): return self.web3.manager.request_blocking( "miner_start", [num_threads], ) def stop(self): return self.web3.manager.request_blocking("miner_stop", []) def startAutoDAG(self): return self.web3.manager.request_blocking("miner_startAutoDag", []) def stopAutoDAG(self): return self.web3.manager.request_blocking("miner_stopAutoDag", [])
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/miner.py
miner.py
from eth_account import ( Account, ) from eth_utils import ( apply_to_return_value, is_checksum_address, is_string, ) from hexbytes import ( HexBytes, ) from web3._utils.blocks import ( select_method_for_block_identifier, ) from web3._utils.decorators import ( deprecated_for, ) from web3._utils.empty import ( empty, ) from web3._utils.encoding import ( to_hex, ) from web3._utils.filters import ( BlockFilter, LogFilter, TransactionFilter, ) from web3._utils.threads import ( Timeout, ) from web3._utils.toolz import ( assoc, merge, ) from web3._utils.transactions import ( assert_valid_transaction_params, extract_valid_transaction_params, get_buffered_gas_estimate, get_required_transaction, replace_transaction, wait_for_transaction_receipt, ) from web3.contract import ( Contract, ) from web3.exceptions import ( TimeExhausted, ) from web3.iban import ( Iban, ) from web3.module import ( Module, ) class Eth(Module): account = Account() defaultAccount = empty defaultBlock = "latest" defaultContractFactory = Contract iban = Iban gasPriceStrategy = None @deprecated_for("doing nothing at all") def enable_unaudited_features(self): pass def namereg(self): raise NotImplementedError() def icapNamereg(self): raise NotImplementedError() @property def protocolVersion(self): return self.web3.manager.request_blocking("eth_protocolVersion", []) @property def syncing(self): return self.web3.manager.request_blocking("eth_syncing", []) @property def coinbase(self): return self.web3.manager.request_blocking("eth_coinbase", []) @property def mining(self): return self.web3.manager.request_blocking("eth_mining", []) @property def hashrate(self): return self.web3.manager.request_blocking("eth_hashrate", []) @property def gasPrice(self): return self.web3.manager.request_blocking("eth_gasPrice", []) @property def accounts(self): return self.web3.manager.request_blocking("eth_accounts", []) @property def blockNumber(self): return self.web3.manager.request_blocking("eth_blockNumber", []) def getBalance(self, account, block_identifier=None): if block_identifier is None: block_identifier = self.defaultBlock return self.web3.manager.request_blocking( "eth_getBalance", [account, block_identifier], ) def getStorageAt(self, account, position, block_identifier=None): if block_identifier is None: block_identifier = self.defaultBlock return self.web3.manager.request_blocking( "eth_getStorageAt", [account, position, block_identifier] ) def getCode(self, account, block_identifier=None): if block_identifier is None: block_identifier = self.defaultBlock return self.web3.manager.request_blocking( "eth_getCode", [account, block_identifier], ) def getBlock(self, block_identifier, full_transactions=False): """ `eth_getBlockByHash` `eth_getBlockByNumber` """ method = select_method_for_block_identifier( block_identifier, if_predefined='eth_getBlockByNumber', if_hash='eth_getBlockByHash', if_number='eth_getBlockByNumber', ) return self.web3.manager.request_blocking( method, [block_identifier, full_transactions], ) def getBlockTransactionCount(self, block_identifier): """ `eth_getBlockTransactionCountByHash` `eth_getBlockTransactionCountByNumber` """ method = select_method_for_block_identifier( block_identifier, if_predefined='eth_getBlockTransactionCountByNumber', if_hash='eth_getBlockTransactionCountByHash', if_number='eth_getBlockTransactionCountByNumber', ) return self.web3.manager.request_blocking( method, [block_identifier], ) def getUncleCount(self, block_identifier): """ `eth_getUncleCountByBlockHash` `eth_getUncleCountByBlockNumber` """ method = select_method_for_block_identifier( block_identifier, if_predefined='eth_getUncleCountByBlockNumber', if_hash='eth_getUncleCountByBlockHash', if_number='eth_getUncleCountByBlockNumber', ) return self.web3.manager.request_blocking( method, [block_identifier], ) def getUncleByBlock(self, block_identifier, uncle_index): """ `eth_getUncleByBlockHashAndIndex` `eth_getUncleByBlockNumberAndIndex` """ method = select_method_for_block_identifier( block_identifier, if_predefined='eth_getUncleByBlockNumberAndIndex', if_hash='eth_getUncleByBlockHashAndIndex', if_number='eth_getUncleByBlockNumberAndIndex', ) return self.web3.manager.request_blocking( method, [block_identifier, uncle_index], ) def getTransaction(self, transaction_hash): return self.web3.manager.request_blocking( "eth_getTransactionByHash", [transaction_hash], ) @deprecated_for("w3.eth.getTransactionByBlock") def getTransactionFromBlock(self, block_identifier, transaction_index): """ Alias for the method getTransactionByBlock Depreceated to maintain naming consistency with the json-rpc API """ return self.getTransactionByBlock(block_identifier, transaction_index) def getTransactionByBlock(self, block_identifier, transaction_index): """ `eth_getTransactionByBlockHashAndIndex` `eth_getTransactionByBlockNumberAndIndex` """ method = select_method_for_block_identifier( block_identifier, if_predefined='eth_getTransactionByBlockNumberAndIndex', if_hash='eth_getTransactionByBlockHashAndIndex', if_number='eth_getTransactionByBlockNumberAndIndex', ) return self.web3.manager.request_blocking( method, [block_identifier, transaction_index], ) def waitForTransactionReceipt(self, transaction_hash, timeout=120): try: return wait_for_transaction_receipt(self.web3, transaction_hash, timeout) except Timeout: raise TimeExhausted( "Transaction {} is not in the chain, after {} seconds".format( transaction_hash, timeout, ) ) def getTransactionReceipt(self, transaction_hash): return self.web3.manager.request_blocking( "eth_getTransactionReceipt", [transaction_hash], ) def getTransactionCount(self, account, block_identifier=None): if block_identifier is None: block_identifier = self.defaultBlock return self.web3.manager.request_blocking( "eth_getTransactionCount", [ account, block_identifier, ], ) def replaceTransaction(self, transaction_hash, new_transaction): current_transaction = get_required_transaction(self.web3, transaction_hash) return replace_transaction(self.web3, current_transaction, new_transaction) def modifyTransaction(self, transaction_hash, **transaction_params): assert_valid_transaction_params(transaction_params) current_transaction = get_required_transaction(self.web3, transaction_hash) current_transaction_params = extract_valid_transaction_params(current_transaction) new_transaction = merge(current_transaction_params, transaction_params) return replace_transaction(self.web3, current_transaction, new_transaction) def sendTransaction(self, transaction): # TODO: move to middleware if 'from' not in transaction and is_checksum_address(self.defaultAccount): transaction = assoc(transaction, 'from', self.defaultAccount) # TODO: move gas estimation in middleware if 'gas' not in transaction: transaction = assoc( transaction, 'gas', get_buffered_gas_estimate(self.web3, transaction), ) return self.web3.manager.request_blocking( "eth_sendTransaction", [transaction], ) def sendRawTransaction(self, raw_transaction): return self.web3.manager.request_blocking( "eth_sendRawTransaction", [raw_transaction], ) def sign(self, account, data=None, hexstr=None, text=None): message_hex = to_hex(data, hexstr=hexstr, text=text) return self.web3.manager.request_blocking( "eth_sign", [account, message_hex], ) @apply_to_return_value(HexBytes) def call(self, transaction, block_identifier=None): # TODO: move to middleware if 'from' not in transaction and is_checksum_address(self.defaultAccount): transaction = assoc(transaction, 'from', self.defaultAccount) # TODO: move to middleware if block_identifier is None: block_identifier = self.defaultBlock return self.web3.manager.request_blocking( "eth_call", [transaction, block_identifier], ) def estimateGas(self, transaction, block_identifier=None): # TODO: move to middleware if 'from' not in transaction and is_checksum_address(self.defaultAccount): transaction = assoc(transaction, 'from', self.defaultAccount) if block_identifier is None: params = [transaction] else: params = [transaction, block_identifier] return self.web3.manager.request_blocking( "eth_estimateGas", params, ) def filter(self, filter_params=None, filter_id=None): if filter_id and filter_params: raise TypeError( "Ambiguous invocation: provide either a `filter_params` or a `filter_id` argument. " "Both were supplied." ) if is_string(filter_params): if filter_params == "latest": filter_id = self.web3.manager.request_blocking( "eth_newBlockFilter", [], ) return BlockFilter(self.web3, filter_id) elif filter_params == "pending": filter_id = self.web3.manager.request_blocking( "eth_newPendingTransactionFilter", [], ) return TransactionFilter(self.web3, filter_id) else: raise ValueError( "The filter API only accepts the values of `pending` or " "`latest` for string based filters" ) elif isinstance(filter_params, dict): _filter_id = self.web3.manager.request_blocking( "eth_newFilter", [filter_params], ) return LogFilter(self.web3, _filter_id) elif filter_id and not filter_params: return LogFilter(self.web3, filter_id) else: raise TypeError("Must provide either filter_params as a string or " "a valid filter object, or a filter_id as a string " "or hex.") def getFilterChanges(self, filter_id): return self.web3.manager.request_blocking( "eth_getFilterChanges", [filter_id], ) def getFilterLogs(self, filter_id): return self.web3.manager.request_blocking( "eth_getFilterLogs", [filter_id], ) def getLogs(self, filter_params): return self.web3.manager.request_blocking( "eth_getLogs", [filter_params], ) def uninstallFilter(self, filter_id): return self.web3.manager.request_blocking( "eth_uninstallFilter", [filter_id], ) def contract(self, address=None, **kwargs): ContractFactoryClass = kwargs.pop('ContractFactoryClass', self.defaultContractFactory) ContractFactory = ContractFactoryClass.factory(self.web3, **kwargs) if address: return ContractFactory(address) else: return ContractFactory def setContractFactory(self, contractFactory): self.defaultContractFactory = contractFactory def getCompilers(self): return self.web3.manager.request_blocking("eth_getCompilers", []) def getWork(self): return self.web3.manager.request_blocking("eth_getWork", []) def generateGasPrice(self, transaction_params=None): if self.gasPriceStrategy: return self.gasPriceStrategy(self.web3, transaction_params) def setGasPriceStrategy(self, gas_price_strategy): self.gasPriceStrategy = gas_price_strategy
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/eth.py
eth.py
from eth_utils import ( is_checksum_address, ) from web3._utils.toolz import ( assoc, ) from web3.module import ( Module, ) class Parity(Module): """ https://paritytech.github.io/wiki/JSONRPC-parity-module """ defaultBlock = "latest" def enode(self): return self.web3.manager.request_blocking( "parity_enode", [], ) def listStorageKeys(self, address, quantity, hash_, block_identifier=None): if block_identifier is None: block_identifier = self.defaultBlock return self.web3.manager.request_blocking( "parity_listStorageKeys", [address, quantity, hash_, block_identifier], ) def netPeers(self): return self.web3.manager.request_blocking( "parity_netPeers", [], ) def traceReplayTransaction(self, transaction_hash, mode=['trace']): return self.web3.manager.request_blocking( "trace_replayTransaction", [transaction_hash, mode], ) def traceReplayBlockTransactions(self, block_identifier, mode=['trace']): return self.web3.manager.request_blocking( "trace_replayBlockTransactions", [block_identifier, mode] ) def traceBlock(self, block_identifier): return self.web3.manager.request_blocking( "trace_block", [block_identifier] ) def traceFilter(self, params): return self.web3.manager.request_blocking( "trace_filter", [params] ) def traceTransaction(self, transaction_hash): return self.web3.manager.request_blocking( "trace_transaction", [transaction_hash] ) def traceCall(self, transaction, mode=['trace'], block_identifier=None): # TODO: move to middleware if 'from' not in transaction and is_checksum_address(self.defaultAccount): transaction = assoc(transaction, 'from', self.defaultAccount) # TODO: move to middleware if block_identifier is None: block_identifier = self.defaultBlock return self.web3.manager.request_blocking( "trace_call", [transaction, mode, block_identifier], ) def traceRawTransaction(self, raw_transaction, mode=['trace']): return self.web3.manager.request_blocking( "trace_rawTransaction", [raw_transaction, mode], )
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/parity.py
parity.py
from web3.module import ( Module, ) class Admin(Module): def addPeer(self, node_url): return self.web3.manager.request_blocking( "admin_addPeer", [node_url], ) @property def datadir(self): return self.web3.manager.request_blocking("admin_datadir", []) @property def nodeInfo(self): return self.web3.manager.request_blocking("admin_nodeInfo", []) @property def peers(self): return self.web3.manager.request_blocking("admin_peers", []) def setSolc(self, solc_path): return self.web3.manager.request_blocking( "admin_setSolc", [solc_path], ) def startRPC(self, host='localhost', port='8545', cors="", apis="eth,net,web3"): return self.web3.manager.request_blocking( "admin_startRPC", [host, port, cors, apis], ) def startWS(self, host='localhost', port='8546', cors="", apis="eth,net,web3"): return self.web3.manager.request_blocking( "admin_startWS", [host, port, cors, apis], ) def stopRPC(self): return self.web3.manager.request_blocking("admin_stopRPC", []) def stopWS(self): return self.web3.manager.request_blocking("admin_stopWS", [])
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/admin.py
admin.py
"""Interaction with smart contracts over Web3 connector. """ import copy import itertools from eth_abi import ( decode_abi, ) from eth_abi.exceptions import ( DecodingError, ) from eth_utils import ( add_0x_prefix, encode_hex, function_abi_to_4byte_selector, is_list_like, is_text, to_tuple, ) from hexbytes import ( HexBytes, ) from web3._utils.abi import ( abi_to_signature, check_if_arguments_can_be_encoded, fallback_func_abi_exists, filter_by_type, get_abi_output_types, get_constructor_abi, is_array_type, map_abi_data, merge_args_and_kwargs, ) from web3._utils.blocks import ( is_hex_encoded_block_hash, ) from web3._utils.contracts import ( encode_abi, find_matching_event_abi, find_matching_fn_abi, get_function_info, prepare_transaction, ) from web3._utils.datatypes import ( PropertyCheckingFactory, ) from web3._utils.decorators import ( combomethod, deprecated_for, ) from web3._utils.empty import ( empty, ) from web3._utils.encoding import ( to_4byte_hex, to_hex, ) from web3._utils.events import ( EventFilterBuilder, get_event_data, is_dynamic_sized_type, ) from web3._utils.filters import ( construct_event_filter_params, ) from web3._utils.function_identifiers import ( FallbackFn, ) from web3._utils.normalizers import ( BASE_RETURN_NORMALIZERS, normalize_abi, normalize_address, normalize_bytecode, ) from web3._utils.toolz import ( compose, partial, ) from web3._utils.transactions import ( fill_transaction_defaults, ) from web3.exceptions import ( BadFunctionCallOutput, BlockNumberOutofRange, FallbackNotFound, MismatchedABI, NoABIEventsFound, NoABIFound, NoABIFunctionsFound, ) DEPRECATED_SIGNATURE_MESSAGE = ( "The constructor signature for the `Contract` object has changed. " "Please update your code to reflect the updated function signature: " "'Contract(address)'. To construct contract classes use the " "'Contract.factory(...)' class method." ) ACCEPTABLE_EMPTY_STRINGS = ["0x", b"0x", "", b""] class ContractFunctions: """Class containing contract function objects """ def __init__(self, abi, web3, address=None): if abi: self.abi = abi self._functions = filter_by_type('function', self.abi) for func in self._functions: setattr( self, func['name'], ContractFunction.factory( func['name'], web3=web3, contract_abi=self.abi, address=address, function_identifier=func['name'])) def __iter__(self): if not hasattr(self, '_functions') or not self._functions: return for func in self._functions: yield func['name'] def __getattr__(self, function_name): if '_functions' not in self.__dict__: raise NoABIFunctionsFound( "The abi for this contract contains no function definitions. ", "Are you sure you provided the correct contract abi?" ) elif function_name not in self.__dict__['_functions']: raise MismatchedABI( "The function '{}' was not found in this contract's abi. ".format(function_name), "Are you sure you provided the correct contract abi?" ) else: return super().__getattribute__(function_name) def __getitem__(self, function_name): return getattr(self, function_name) class ContractEvents: """Class containing contract event objects This is available via: .. code-block:: python >>> mycontract.events <web3.contract.ContractEvents object at 0x108afde10> To get list of all supported events in the contract ABI. This allows you to iterate over :class:`ContractEvent` proxy classes. .. code-block:: python >>> for e in mycontract.events: print(e) <class 'web3._utils.datatypes.LogAnonymous'> ... """ def __init__(self, abi, web3, address=None): if abi: self.abi = abi self._events = filter_by_type('event', self.abi) for event in self._events: setattr( self, event['name'], ContractEvent.factory( event['name'], web3=web3, contract_abi=self.abi, address=address, event_name=event['name'])) def __getattr__(self, event_name): if '_events' not in self.__dict__: raise NoABIEventsFound( "The abi for this contract contains no event definitions. ", "Are you sure you provided the correct contract abi?" ) elif event_name not in self.__dict__['_events']: raise MismatchedABI( "The event '{}' was not found in this contract's abi. ".format(event_name), "Are you sure you provided the correct contract abi?" ) else: return super().__getattribute__(event_name) def __getitem__(self, event_name): return getattr(self, event_name) def __iter__(self): """Iterate over supported :return: Iterable of :class:`ContractEvent` """ for event in self._events: yield self[event['name']] class Contract: """Base class for Contract proxy classes. First you need to create your Contract classes using :meth:`web3.eth.Eth.contract` that takes compiled Solidity contract ABI definitions as input. The created class object will be a subclass of this base class. After you have your Contract proxy class created you can interact with smart contracts * Create a Contract proxy object for an existing deployed smart contract by its address using :meth:`__init__` * Deploy a new smart contract using :py:meth:`Contract.deploy` """ # set during class construction web3 = None # instance level properties address = None # class properties (overridable at instance level) abi = None asm = None ast = None bytecode = None bytecode_runtime = None clone_bin = None functions = None caller = None #: Instance of :class:`ContractEvents` presenting available Event ABIs events = None dev_doc = None interface = None metadata = None opcodes = None src_map = None src_map_runtime = None user_doc = None def __init__(self, address=None): """Create a new smart contract proxy object. :param address: Contract address as 0x hex string """ if self.web3 is None: raise AttributeError( 'The `Contract` class has not been initialized. Please use the ' '`web3.contract` interface to create your contract class.' ) if address: self.address = normalize_address(self.web3.ens, address) if not self.address: raise TypeError("The address argument is required to instantiate a contract.") self.functions = ContractFunctions(self.abi, self.web3, self.address) self.caller = ContractCaller(self.abi, self.web3, self.address) self.events = ContractEvents(self.abi, self.web3, self.address) self.fallback = Contract.get_fallback_function(self.abi, self.web3, self.address) @classmethod def factory(cls, web3, class_name=None, **kwargs): kwargs['web3'] = web3 normalizers = { 'abi': normalize_abi, 'address': partial(normalize_address, kwargs['web3'].ens), 'bytecode': normalize_bytecode, 'bytecode_runtime': normalize_bytecode, } contract = PropertyCheckingFactory( class_name or cls.__name__, (cls,), kwargs, normalizers=normalizers, ) contract.functions = ContractFunctions(contract.abi, contract.web3) contract.caller = ContractCaller(contract.abi, contract.web3, contract.address) contract.events = ContractEvents(contract.abi, contract.web3) contract.fallback = Contract.get_fallback_function(contract.abi, contract.web3) return contract # # Contract Methods # @classmethod def constructor(cls, *args, **kwargs): """ :param args: The contract constructor arguments as positional arguments :param kwargs: The contract constructor arguments as keyword arguments :return: a contract constructor object """ if cls.bytecode is None: raise ValueError( "Cannot call constructor on a contract that does not have 'bytecode' associated " "with it" ) return ContractConstructor(cls.web3, cls.abi, cls.bytecode, *args, **kwargs) # Public API # @combomethod def encodeABI(cls, fn_name, args=None, kwargs=None, data=None): """ Encodes the arguments using the Ethereum ABI for the contract function that matches the given name and arguments.. :param data: defaults to function selector """ fn_abi, fn_selector, fn_arguments = get_function_info( fn_name, contract_abi=cls.abi, args=args, kwargs=kwargs, ) if data is None: data = fn_selector return encode_abi(cls.web3, fn_abi, fn_arguments, data) @combomethod def all_functions(self): return find_functions_by_identifier( self.abi, self.web3, self.address, lambda _: True ) @combomethod def get_function_by_signature(self, signature): if ' ' in signature: raise ValueError( 'Function signature should not contain any spaces. ' 'Found spaces in input: %s' % signature ) def callable_check(fn_abi): return abi_to_signature(fn_abi) == signature fns = find_functions_by_identifier(self.abi, self.web3, self.address, callable_check) return get_function_by_identifier(fns, 'signature') @combomethod def find_functions_by_name(self, fn_name): def callable_check(fn_abi): return fn_abi['name'] == fn_name return find_functions_by_identifier( self.abi, self.web3, self.address, callable_check ) @combomethod def get_function_by_name(self, fn_name): fns = self.find_functions_by_name(fn_name) return get_function_by_identifier(fns, 'name') @combomethod def get_function_by_selector(self, selector): def callable_check(fn_abi): return encode_hex(function_abi_to_4byte_selector(fn_abi)) == to_4byte_hex(selector) fns = find_functions_by_identifier(self.abi, self.web3, self.address, callable_check) return get_function_by_identifier(fns, 'selector') @combomethod def decode_function_input(self, data): data = HexBytes(data) selector, params = data[:4], data[4:] func = self.get_function_by_selector(selector) names = [x['name'] for x in func.abi['inputs']] types = [x['type'] for x in func.abi['inputs']] decoded = decode_abi(types, params) normalized = map_abi_data(BASE_RETURN_NORMALIZERS, types, decoded) return func, dict(zip(names, normalized)) @combomethod def find_functions_by_args(self, *args): def callable_check(fn_abi): return check_if_arguments_can_be_encoded(fn_abi, args=args, kwargs={}) return find_functions_by_identifier( self.abi, self.web3, self.address, callable_check ) @combomethod def get_function_by_args(self, *args): fns = self.find_functions_by_args(*args) return get_function_by_identifier(fns, 'args') # # Private Helpers # _return_data_normalizers = tuple() @classmethod def _prepare_transaction(cls, fn_name, fn_args=None, fn_kwargs=None, transaction=None): return prepare_transaction( cls.address, cls.web3, fn_identifier=fn_name, contract_abi=cls.abi, transaction=transaction, fn_args=fn_args, fn_kwargs=fn_kwargs, ) @classmethod def _find_matching_fn_abi(cls, fn_identifier=None, args=None, kwargs=None): return find_matching_fn_abi(cls.abi, fn_identifier=fn_identifier, args=args, kwargs=kwargs) @classmethod def _find_matching_event_abi(cls, event_name=None, argument_names=None): return find_matching_event_abi( abi=cls.abi, event_name=event_name, argument_names=argument_names) @staticmethod def get_fallback_function(abi, web3, address=None): if abi and fallback_func_abi_exists(abi): return ContractFunction.factory( 'fallback', web3=web3, contract_abi=abi, address=address, function_identifier=FallbackFn)() return NonExistentFallbackFunction() @combomethod def _encode_constructor_data(cls, args=None, kwargs=None): constructor_abi = get_constructor_abi(cls.abi) if constructor_abi: if args is None: args = tuple() if kwargs is None: kwargs = {} arguments = merge_args_and_kwargs(constructor_abi, args, kwargs) deploy_data = add_0x_prefix( encode_abi(cls.web3, constructor_abi, arguments, data=cls.bytecode) ) else: deploy_data = to_hex(cls.bytecode) return deploy_data def mk_collision_prop(fn_name): def collision_fn(): msg = "Namespace collision for function name {0} with ConciseContract API.".format(fn_name) raise AttributeError(msg) collision_fn.__name__ = fn_name return collision_fn class ContractConstructor: """ Class for contract constructor API. """ def __init__(self, web3, abi, bytecode, *args, **kwargs): self.web3 = web3 self.abi = abi self.bytecode = bytecode self.data_in_transaction = self._encode_data_in_transaction(*args, **kwargs) @combomethod def _encode_data_in_transaction(self, *args, **kwargs): constructor_abi = get_constructor_abi(self.abi) if constructor_abi: if not args: args = tuple() if not kwargs: kwargs = {} arguments = merge_args_and_kwargs(constructor_abi, args, kwargs) data = add_0x_prefix( encode_abi(self.web3, constructor_abi, arguments, data=self.bytecode) ) else: data = to_hex(self.bytecode) return data @combomethod def estimateGas(self, transaction=None): if transaction is None: estimate_gas_transaction = {} else: estimate_gas_transaction = dict(**transaction) self.check_forbidden_keys_in_transaction(estimate_gas_transaction, ["data", "to"]) if self.web3.eth.defaultAccount is not empty: estimate_gas_transaction.setdefault('from', self.web3.eth.defaultAccount) estimate_gas_transaction['data'] = self.data_in_transaction return self.web3.eth.estimateGas(estimate_gas_transaction) @combomethod def transact(self, transaction=None): if transaction is None: transact_transaction = {} else: transact_transaction = dict(**transaction) self.check_forbidden_keys_in_transaction(transact_transaction, ["data", "to"]) if self.web3.eth.defaultAccount is not empty: transact_transaction.setdefault('from', self.web3.eth.defaultAccount) transact_transaction['data'] = self.data_in_transaction # TODO: handle asynchronous contract creation return self.web3.eth.sendTransaction(transact_transaction) @combomethod def buildTransaction(self, transaction=None): """ Build the transaction dictionary without sending """ if transaction is None: built_transaction = {} else: built_transaction = dict(**transaction) self.check_forbidden_keys_in_transaction(built_transaction, ["data", "to"]) if self.web3.eth.defaultAccount is not empty: built_transaction.setdefault('from', self.web3.eth.defaultAccount) built_transaction['data'] = self.data_in_transaction built_transaction['to'] = b'' return fill_transaction_defaults(self.web3, built_transaction) @staticmethod def check_forbidden_keys_in_transaction(transaction, forbidden_keys=None): keys_found = set(transaction.keys()) & set(forbidden_keys) if keys_found: raise ValueError("Cannot set {} in transaction".format(', '.join(keys_found))) class ConciseMethod: ALLOWED_MODIFIERS = {'call', 'estimateGas', 'transact', 'buildTransaction'} def __init__(self, function, normalizers=None): self._function = function self._function._return_data_normalizers = normalizers def __call__(self, *args, **kwargs): return self.__prepared_function(*args, **kwargs) def __prepared_function(self, *args, **kwargs): if not kwargs: modifier, modifier_dict = 'call', {} elif len(kwargs) == 1: modifier, modifier_dict = kwargs.popitem() if modifier not in self.ALLOWED_MODIFIERS: raise TypeError( "The only allowed keyword arguments are: %s" % self.ALLOWED_MODIFIERS) else: raise TypeError("Use up to one keyword argument, one of: %s" % self.ALLOWED_MODIFIERS) return getattr(self._function(*args), modifier)(modifier_dict) class ConciseContract: """ An alternative Contract Factory which invokes all methods as `call()`, unless you add a keyword argument. The keyword argument assigns the prep method. This call > contract.withdraw(amount, transact={'from': eth.accounts[1], 'gas': 100000, ...}) is equivalent to this call in the classic contract: > contract.functions.withdraw(amount).transact({'from': eth.accounts[1], 'gas': 100000, ...}) """ @deprecated_for( "contract.caller.<method name> or contract.caller({transaction_dict}).<method name>" ) def __init__(self, classic_contract, method_class=ConciseMethod): classic_contract._return_data_normalizers += CONCISE_NORMALIZERS self._classic_contract = classic_contract self.address = self._classic_contract.address protected_fn_names = [fn for fn in dir(self) if not fn.endswith('__')] for fn_name in self._classic_contract.functions: # Override namespace collisions if fn_name in protected_fn_names: _concise_method = mk_collision_prop(fn_name) else: _classic_method = getattr( self._classic_contract.functions, fn_name) _concise_method = method_class( _classic_method, self._classic_contract._return_data_normalizers ) setattr(self, fn_name, _concise_method) @classmethod def factory(cls, *args, **kwargs): return compose(cls, Contract.factory(*args, **kwargs)) def _none_addr(datatype, data): if datatype == 'address' and int(data, base=16) == 0: return (datatype, None) else: return (datatype, data) CONCISE_NORMALIZERS = ( _none_addr, ) class ImplicitMethod(ConciseMethod): def __call_by_default(self, args): function_abi = find_matching_fn_abi(self._function.contract_abi, fn_identifier=self._function.function_identifier, args=args) return function_abi['constant'] if 'constant' in function_abi.keys() else False @deprecated_for("classic contract syntax. Ex: contract.functions.withdraw(amount).transact({})") def __call__(self, *args, **kwargs): # Modifier is not provided and method is not constant/pure do a transaction instead if not kwargs and not self.__call_by_default(args): return super().__call__(*args, transact={}) else: return super().__call__(*args, **kwargs) class ImplicitContract(ConciseContract): """ ImplicitContract class is similar to the ConciseContract class however it performs a transaction instead of a call if no modifier is given and the method is not marked 'constant' in the ABI. The transaction will use the default account to send the transaction. This call > contract.withdraw(amount) is equivalent to this call in the classic contract: > contract.functions.withdraw(amount).transact({}) """ def __init__(self, classic_contract, method_class=ImplicitMethod): super().__init__(classic_contract, method_class=method_class) class NonExistentFallbackFunction: @staticmethod def _raise_exception(): raise FallbackNotFound("No fallback function was found in the contract ABI.") def __getattr__(self, attr): return NonExistentFallbackFunction._raise_exception class ContractFunction: """Base class for contract functions A function accessed via the api contract.functions.myMethod(*args, **kwargs) is a subclass of this class. """ address = None function_identifier = None web3 = None contract_abi = None abi = None transaction = None arguments = None def __init__(self, abi=None): self.abi = abi self.fn_name = type(self).__name__ def __call__(self, *args, **kwargs): clone = copy.copy(self) if args is None: clone.args = tuple() else: clone.args = args if kwargs is None: clone.kwargs = {} else: clone.kwargs = kwargs clone._set_function_info() return clone def _set_function_info(self): if not self.abi: self.abi = find_matching_fn_abi( self.contract_abi, self.function_identifier, self.args, self.kwargs ) if self.function_identifier is FallbackFn: self.selector = encode_hex(b'') elif is_text(self.function_identifier): self.selector = encode_hex(function_abi_to_4byte_selector(self.abi)) else: raise TypeError("Unsupported function identifier") self.arguments = merge_args_and_kwargs(self.abi, self.args, self.kwargs) def call(self, transaction=None, block_identifier='latest'): """ Execute a contract function call using the `eth_call` interface. This method prepares a ``Caller`` object that exposes the contract functions and public variables as callable Python functions. Reading a public ``owner`` address variable example: .. code-block:: python ContractFactory = w3.eth.contract( abi=wallet_contract_definition["abi"] ) # Not a real contract address contract = ContractFactory("0x2f70d3d26829e412A602E83FE8EeBF80255AEeA5") # Read "owner" public variable addr = contract.functions.owner().call() :param transaction: Dictionary of transaction info for web3 interface :return: ``Caller`` object that has contract public functions and variables exposed as Python methods """ if transaction is None: call_transaction = {} else: call_transaction = dict(**transaction) if 'data' in call_transaction: raise ValueError("Cannot set data in call transaction") if self.address: call_transaction.setdefault('to', self.address) if self.web3.eth.defaultAccount is not empty: call_transaction.setdefault('from', self.web3.eth.defaultAccount) if 'to' not in call_transaction: if isinstance(self, type): raise ValueError( "When using `Contract.[methodtype].[method].call()` from" " a contract factory you " "must provide a `to` address with the transaction" ) else: raise ValueError( "Please ensure that this contract instance has an address." ) block_id = parse_block_identifier(self.web3, block_identifier) return call_contract_function( self.web3, self.address, self._return_data_normalizers, self.function_identifier, call_transaction, block_id, self.contract_abi, self.abi, *self.args, **self.kwargs ) def transact(self, transaction=None): if transaction is None: transact_transaction = {} else: transact_transaction = dict(**transaction) if 'data' in transact_transaction: raise ValueError("Cannot set data in transact transaction") if self.address is not None: transact_transaction.setdefault('to', self.address) if self.web3.eth.defaultAccount is not empty: transact_transaction.setdefault('from', self.web3.eth.defaultAccount) if 'to' not in transact_transaction: if isinstance(self, type): raise ValueError( "When using `Contract.transact` from a contract factory you " "must provide a `to` address with the transaction" ) else: raise ValueError( "Please ensure that this contract instance has an address." ) return transact_with_contract_function( self.address, self.web3, self.function_identifier, transact_transaction, self.contract_abi, self.abi, *self.args, **self.kwargs ) def estimateGas(self, transaction=None): if transaction is None: estimate_gas_transaction = {} else: estimate_gas_transaction = dict(**transaction) if 'data' in estimate_gas_transaction: raise ValueError("Cannot set data in estimateGas transaction") if 'to' in estimate_gas_transaction: raise ValueError("Cannot set to in estimateGas transaction") if self.address: estimate_gas_transaction.setdefault('to', self.address) if self.web3.eth.defaultAccount is not empty: estimate_gas_transaction.setdefault('from', self.web3.eth.defaultAccount) if 'to' not in estimate_gas_transaction: if isinstance(self, type): raise ValueError( "When using `Contract.estimateGas` from a contract factory " "you must provide a `to` address with the transaction" ) else: raise ValueError( "Please ensure that this contract instance has an address." ) return estimate_gas_for_function( self.address, self.web3, self.function_identifier, estimate_gas_transaction, self.contract_abi, self.abi, *self.args, **self.kwargs ) def buildTransaction(self, transaction=None): """ Build the transaction dictionary without sending """ if transaction is None: built_transaction = {} else: built_transaction = dict(**transaction) if 'data' in built_transaction: raise ValueError("Cannot set data in build transaction") if not self.address and 'to' not in built_transaction: raise ValueError( "When using `ContractFunction.buildTransaction` from a contract factory " "you must provide a `to` address with the transaction" ) if self.address and 'to' in built_transaction: raise ValueError("Cannot set to in contract call build transaction") if self.address: built_transaction.setdefault('to', self.address) if 'to' not in built_transaction: raise ValueError( "Please ensure that this contract instance has an address." ) return build_transaction_for_function( self.address, self.web3, self.function_identifier, built_transaction, self.contract_abi, self.abi, *self.args, **self.kwargs ) @combomethod def _encode_transaction_data(cls): return add_0x_prefix(encode_abi(cls.web3, cls.abi, cls.arguments, cls.selector)) _return_data_normalizers = tuple() @classmethod def factory(cls, class_name, **kwargs): return PropertyCheckingFactory(class_name, (cls,), kwargs)(kwargs.get('abi')) def __repr__(self): if self.abi: _repr = '<Function %s' % abi_to_signature(self.abi) if self.arguments is not None: _repr += ' bound to %r' % (self.arguments,) return _repr + '>' return '<Function %s>' % self.fn_name class ContractEvent: """Base class for contract events An event accessed via the api contract.events.myEvents(*args, **kwargs) is a subclass of this class. """ address = None event_name = None web3 = None contract_abi = None abi = None def __init__(self, *argument_names): if argument_names is None: self.argument_names = tuple() else: self.argument_names = argument_names self.abi = self._get_event_abi() @classmethod def _get_event_abi(cls): return find_matching_event_abi( cls.contract_abi, event_name=cls.event_name) @combomethod def processReceipt(self, txn_receipt): return self._parse_logs(txn_receipt) @to_tuple def _parse_logs(self, txn_receipt): for log in txn_receipt['logs']: try: decoded_log = get_event_data(self.abi, log) except MismatchedABI: continue yield decoded_log @combomethod def createFilter( self, *, # PEP 3102 argument_filters=None, fromBlock=None, toBlock="latest", address=None, topics=None): """ Create filter object that tracks logs emitted by this contract event. :param filter_params: other parameters to limit the events """ if fromBlock is None: raise TypeError("Missing mandatory keyword argument to createFilter: fromBlock") if argument_filters is None: argument_filters = dict() _filters = dict(**argument_filters) event_abi = self._get_event_abi() check_for_forbidden_api_filter_arguments(event_abi, _filters) _, event_filter_params = construct_event_filter_params( self._get_event_abi(), contract_address=self.address, argument_filters=_filters, fromBlock=fromBlock, toBlock=toBlock, address=address, topics=topics, ) filter_builder = EventFilterBuilder(event_abi) filter_builder.address = event_filter_params.get('address') filter_builder.fromBlock = event_filter_params.get('fromBlock') filter_builder.toBlock = event_filter_params.get('toBlock') match_any_vals = { arg: value for arg, value in _filters.items() if not is_array_type(filter_builder.args[arg].arg_type) and is_list_like(value) } for arg, value in match_any_vals.items(): filter_builder.args[arg].match_any(*value) match_single_vals = { arg: value for arg, value in _filters.items() if not is_array_type(filter_builder.args[arg].arg_type) and not is_list_like(value) } for arg, value in match_single_vals.items(): filter_builder.args[arg].match_single(value) log_filter = filter_builder.deploy(self.web3) log_filter.log_entry_formatter = get_event_data(self._get_event_abi()) log_filter.builder = filter_builder return log_filter @combomethod def build_filter(self): builder = EventFilterBuilder( self._get_event_abi(), formatter=get_event_data(self._get_event_abi())) builder.address = self.address return builder @combomethod def getLogs(self, argument_filters=None, fromBlock=1, toBlock="latest"): """Get events for this contract instance using eth_getLogs API. This is a stateless method, as opposed to createFilter. It can be safely called against nodes which do not provide eth_newFilter API, like Infura nodes. If no block range is provided and there are many events, like ``Transfer`` events for a popular token, the Ethereum node might be overloaded and timeout on the underlying JSON-RPC call. Example - how to get all ERC-20 token transactions for the latest 10 blocks: .. code-block:: python from = max(mycontract.web3.eth.blockNumber - 10, 1) to = mycontract.web3.eth.blockNumber events = mycontract.events.Transfer.getLogs(fromBlock=from, toBlock=to) for e in events: print(e["args"]["from"], e["args"]["to"], e["args"]["value"]) The returned processed log values will look like: .. code-block:: python ( AttributeDict({ 'args': AttributeDict({}), 'event': 'LogNoArguments', 'logIndex': 0, 'transactionIndex': 0, 'transactionHash': HexBytes('...'), 'address': '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b', 'blockHash': HexBytes('...'), 'blockNumber': 3 }), AttributeDict(...), ... ) See also: :func:`web3.middleware.filter.local_filter_middleware`. :param argument_filters: :param fromBlock: block number, defaults to 1 :param toBlock: block number or "latest". Defaults to "latest" :yield: Tuple of :class:`AttributeDict` instances """ if not self.address: raise TypeError("This method can be only called on " "an instated contract with an address") abi = self._get_event_abi() if argument_filters is None: argument_filters = dict() _filters = dict(**argument_filters) # Construct JSON-RPC raw filter presentation based on human readable Python descriptions # Namely, convert event names to their keccak signatures data_filter_set, event_filter_params = construct_event_filter_params( abi, contract_address=self.address, argument_filters=_filters, fromBlock=fromBlock, toBlock=toBlock, address=self.address, ) # Call JSON-RPC API logs = self.web3.eth.getLogs(event_filter_params) # Convert raw binary data to Python proxy objects as described by ABI return tuple(get_event_data(abi, entry) for entry in logs) @classmethod def factory(cls, class_name, **kwargs): return PropertyCheckingFactory(class_name, (cls,), kwargs) class ContractCaller: """ An alternative Contract API. This call: > contract.caller({'from': eth.accounts[1], 'gas': 100000, ...}).add(2, 3) is equivalent to this call in the classic contract: > contract.functions.add(2, 3).call({'from': eth.accounts[1], 'gas': 100000, ...}) Other options for invoking this class include: > contract.caller.add(2, 3) or > contract.caller().add(2, 3) or > contract.caller(transaction={'from': eth.accounts[1], 'gas': 100000, ...}).add(2, 3) """ def __init__(self, abi, web3, address, transaction=None, block_identifier='latest'): self.web3 = web3 self.address = address self.abi = abi self._functions = None if abi: if transaction is None: transaction = {} self._functions = filter_by_type('function', self.abi) for func in self._functions: fn = ContractFunction.factory( func['name'], web3=self.web3, contract_abi=self.abi, address=self.address, function_identifier=func['name']) block_id = parse_block_identifier(self.web3, block_identifier) caller_method = partial(self.call_function, fn, transaction=transaction, block_identifier=block_id) setattr(self, func['name'], caller_method) def __getattr__(self, function_name): if self.abi is None: raise NoABIFound( "There is no ABI found for this contract.", ) elif not self._functions or len(self._functions) == 0: raise NoABIFunctionsFound( "The ABI for this contract contains no function definitions. ", "Are you sure you provided the correct contract ABI?" ) elif function_name not in self._functions: functions_available = ', '.join([fn['name'] for fn in self._functions]) raise MismatchedABI( "The function '{}' was not found in this contract's ABI. ".format(function_name), "Here is a list of all of the function names found: ", "{}. ".format(functions_available), "Did you mean to call one of those functions?" ) else: return super().__getattribute__(function_name) def __call__(self, transaction=None, block_identifier='latest'): if transaction is None: transaction = {} return type(self)(self.abi, self.web3, self.address, transaction=transaction, block_identifier=block_identifier) @staticmethod def call_function(fn, *args, transaction=None, block_identifier='latest', **kwargs): if transaction is None: transaction = {} return fn(*args, **kwargs).call(transaction, block_identifier) def check_for_forbidden_api_filter_arguments(event_abi, _filters): name_indexed_inputs = {_input['name']: _input for _input in event_abi['inputs']} for filter_name, filter_value in _filters.items(): _input = name_indexed_inputs[filter_name] if is_array_type(_input['type']): raise TypeError( "createFilter no longer supports array type filter arguments. " "see the build_filter method for filtering array type filters.") if is_list_like(filter_value) and is_dynamic_sized_type(_input['type']): raise TypeError( "createFilter no longer supports setting filter argument options for dynamic sized " "types. See the build_filter method for setting filters with the match_any " "method.") def call_contract_function( web3, address, normalizers, function_identifier, transaction, block_id=None, contract_abi=None, fn_abi=None, *args, **kwargs): """ Helper function for interacting with a contract function using the `eth_call` API. """ call_transaction = prepare_transaction( address, web3, fn_identifier=function_identifier, contract_abi=contract_abi, fn_abi=fn_abi, transaction=transaction, fn_args=args, fn_kwargs=kwargs, ) if block_id is None: return_data = web3.eth.call(call_transaction) else: return_data = web3.eth.call(call_transaction, block_identifier=block_id) if fn_abi is None: fn_abi = find_matching_fn_abi(contract_abi, function_identifier, args, kwargs) output_types = get_abi_output_types(fn_abi) try: output_data = decode_abi(output_types, return_data) except DecodingError as e: # Provide a more helpful error message than the one provided by # eth-abi-utils is_missing_code_error = ( return_data in ACCEPTABLE_EMPTY_STRINGS and web3.eth.getCode(address) in ACCEPTABLE_EMPTY_STRINGS ) if is_missing_code_error: msg = ( "Could not transact with/call contract function, is contract " "deployed correctly and chain synced?" ) else: msg = ( "Could not decode contract function call {} return data {} for " "output_types {}".format( function_identifier, return_data, output_types ) ) raise BadFunctionCallOutput(msg) from e _normalizers = itertools.chain( BASE_RETURN_NORMALIZERS, normalizers, ) normalized_data = map_abi_data(_normalizers, output_types, output_data) if len(normalized_data) == 1: return normalized_data[0] else: return normalized_data def parse_block_identifier(web3, block_identifier): if isinstance(block_identifier, int): return parse_block_identifier_int(web3, block_identifier) elif block_identifier in ['latest', 'earliest', 'pending']: return block_identifier elif isinstance(block_identifier, bytes) or is_hex_encoded_block_hash(block_identifier): return web3.eth.getBlock(block_identifier)['number'] else: raise BlockNumberOutofRange def parse_block_identifier_int(web3, block_identifier_int): if block_identifier_int >= 0: block_num = block_identifier_int else: last_block = web3.eth.getBlock('latest')['number'] block_num = last_block + block_identifier_int + 1 if block_num < 0: raise BlockNumberOutofRange return block_num def transact_with_contract_function( address, web3, function_name=None, transaction=None, contract_abi=None, fn_abi=None, *args, **kwargs): """ Helper function for interacting with a contract function by sending a transaction. """ transact_transaction = prepare_transaction( address, web3, fn_identifier=function_name, contract_abi=contract_abi, transaction=transaction, fn_abi=fn_abi, fn_args=args, fn_kwargs=kwargs, ) txn_hash = web3.eth.sendTransaction(transact_transaction) return txn_hash def estimate_gas_for_function( address, web3, fn_identifier=None, transaction=None, contract_abi=None, fn_abi=None, *args, **kwargs): """Estimates gas cost a function call would take. Don't call this directly, instead use :meth:`Contract.estimateGas` on your contract instance. """ estimate_transaction = prepare_transaction( address, web3, fn_identifier=fn_identifier, contract_abi=contract_abi, fn_abi=fn_abi, transaction=transaction, fn_args=args, fn_kwargs=kwargs, ) gas_estimate = web3.eth.estimateGas(estimate_transaction) return gas_estimate def build_transaction_for_function( address, web3, function_name=None, transaction=None, contract_abi=None, fn_abi=None, *args, **kwargs): """Builds a dictionary with the fields required to make the given transaction Don't call this directly, instead use :meth:`Contract.buildTransaction` on your contract instance. """ prepared_transaction = prepare_transaction( address, web3, fn_identifier=function_name, contract_abi=contract_abi, fn_abi=fn_abi, transaction=transaction, fn_args=args, fn_kwargs=kwargs, ) prepared_transaction = fill_transaction_defaults(web3, prepared_transaction) return prepared_transaction def find_functions_by_identifier(contract_abi, web3, address, callable_check): fns_abi = filter_by_type('function', contract_abi) return [ ContractFunction.factory( fn_abi['name'], web3=web3, contract_abi=contract_abi, address=address, function_identifier=fn_abi['name'], abi=fn_abi ) for fn_abi in fns_abi if callable_check(fn_abi) ] def get_function_by_identifier(fns, identifier): if len(fns) > 1: raise ValueError( 'Found multiple functions with matching {0}. ' 'Found: {1!r}'.format(identifier, fns) ) elif len(fns) == 0: raise ValueError( 'Could not find any function with matching {0}'.format(identifier) ) return fns[0]
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/contract.py
contract.py
from eth_utils import ( add_0x_prefix, apply_to_return_value, from_wei, is_address, is_checksum_address, keccak as eth_utils_keccak, remove_0x_prefix, to_checksum_address, to_wei, ) from hexbytes import ( HexBytes, ) from ens import ENS from web3._utils.abi import ( map_abi_data, ) from web3._utils.decorators import ( combomethod, ) from web3._utils.empty import ( empty, ) from web3._utils.encoding import ( hex_encode_abi_type, to_bytes, to_hex, to_int, to_text, to_json, ) from web3._utils.normalizers import ( abi_ens_resolver, ) from web3.admin import ( Admin, ) from web3.eth import ( Eth, ) from web3.iban import ( Iban, ) from web3.manager import ( RequestManager as DefaultRequestManager, ) from web3.miner import ( Miner, ) from web3.net import ( Net, ) from web3.parity import ( Parity, ) from web3.personal import ( Personal, ) from web3.providers.eth_tester import ( EthereumTesterProvider, ) from web3.providers.ipc import ( IPCProvider, ) from web3.providers.rpc import ( HTTPProvider, ) from web3.providers.websocket import ( WebsocketProvider, ) from web3.testing import ( Testing, ) from web3.txpool import ( TxPool, ) from web3.version import ( Version, ) def get_default_modules(): return { "eth": Eth, "net": Net, "personal": Personal, "version": Version, "txpool": TxPool, "miner": Miner, "admin": Admin, "parity": Parity, "testing": Testing, } class Web3: # Providers HTTPProvider = HTTPProvider IPCProvider = IPCProvider EthereumTesterProvider = EthereumTesterProvider WebsocketProvider = WebsocketProvider # Managers RequestManager = DefaultRequestManager # Iban Iban = Iban # Encoding and Decoding toBytes = staticmethod(to_bytes) toInt = staticmethod(to_int) toHex = staticmethod(to_hex) toText = staticmethod(to_text) toJSON = staticmethod(to_json) # Currency Utility toWei = staticmethod(to_wei) fromWei = staticmethod(from_wei) # Address Utility isAddress = staticmethod(is_address) isChecksumAddress = staticmethod(is_checksum_address) toChecksumAddress = staticmethod(to_checksum_address) def __init__(self, provider=None, middlewares=None, modules=None, ens=empty): self.manager = self.RequestManager(self, provider, middlewares) if modules is None: modules = get_default_modules() for module_name, module_class in modules.items(): module_class.attach(self, module_name) self.ens = ens @property def middleware_onion(self): return self.manager.middleware_onion @property def provider(self): return self.manager.provider @provider.setter def provider(self, provider): self.manager.provider = provider @staticmethod @apply_to_return_value(HexBytes) def keccak(primitive=None, text=None, hexstr=None): if isinstance(primitive, (bytes, int, type(None))): input_bytes = to_bytes(primitive, hexstr=hexstr, text=text) return eth_utils_keccak(input_bytes) raise TypeError( "You called keccak with first arg %r and keywords %r. You must call it with one of " "these approaches: keccak(text='txt'), keccak(hexstr='0x747874'), " "keccak(b'\\x74\\x78\\x74'), or keccak(0x747874)." % ( primitive, {'text': text, 'hexstr': hexstr} ) ) @combomethod def solidityKeccak(cls, abi_types, values): """ Executes keccak256 exactly as Solidity does. Takes list of abi_types as inputs -- `[uint24, int8[], bool]` and list of corresponding values -- `[20, [-1, 5, 0], True]` """ if len(abi_types) != len(values): raise ValueError( "Length mismatch between provided abi types and values. Got " "{0} types and {1} values.".format(len(abi_types), len(values)) ) if isinstance(cls, type): w3 = None else: w3 = cls normalized_values = map_abi_data([abi_ens_resolver(w3)], abi_types, values) hex_string = add_0x_prefix(''.join( remove_0x_prefix(hex_encode_abi_type(abi_type, value)) for abi_type, value in zip(abi_types, normalized_values) )) return cls.keccak(hexstr=hex_string) def isConnected(self): return self.provider.isConnected() @property def ens(self): if self._ens is empty: return ENS.fromWeb3(self) else: return self._ens @ens.setter def ens(self, new_ens): self._ens = new_ens @property def pm(self): if hasattr(self, '_pm'): return self._pm else: raise AttributeError( "The Package Management feature is disabled by default until " "its API stabilizes. To use these features, please enable them by running " "`w3.enable_unstable_package_management_api()` and try again." ) def enable_unstable_package_management_api(self): from web3.pm import PM PM.attach(self, '_pm')
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/main.py
main.py
from abc import ( ABC, abstractmethod, ) import json from typing import ( Any, Dict, Iterable, List, NewType, Tuple, ) from eth_utils import ( is_canonical_address, is_checksum_address, to_bytes, to_canonical_address, to_checksum_address, to_text, to_tuple, ) from eth_utils.toolz import ( concat, ) from ethpm import ( ASSETS_DIR, Package, ) from ethpm.typing import ( URI, Address, Manifest, ) from ethpm.utils.backend import ( resolve_uri_contents, ) from ethpm.utils.ipfs import ( is_ipfs_uri, ) from ethpm.utils.manifest_validation import ( validate_manifest_against_schema, validate_raw_manifest_format, ) from ethpm.utils.uri import ( is_valid_content_addressed_github_uri, ) from ethpm.validation import ( validate_package_name, validate_package_version, ) from web3 import Web3 from web3._utils.ens import ( is_ens_name, ) from web3.exceptions import ( InvalidAddress, ManifestValidationError, NameNotFound, PMError, ) from web3.module import ( Module, ) TxReceipt = NewType("TxReceipt", Dict[str, Any]) # Package Management is still in alpha, and its API is likely to change, so it # is not automatically available on a web3 instance. To use the `PM` module, # please enable the package management API on an individual web3 instance. # # >>> from web3.auto import w3 # >>> w3.pm # AttributeError: The Package Management feature is disabled by default ... # >>> w3.enable_unstable_package_management_api() # >>> w3.pm # <web3.pm.PM at 0x....> class ERCRegistry(ABC): """ The ERCRegistry class is a base class for all registry implementations to inherit from. It defines the methods specified in `ERC 1319 <https://github.com/ethereum/EIPs/issues/1319>`__. All of these methods are prefixed with an underscore, since they are not intended to be accessed directly, but rather through the methods on ``web3.pm``. They are unlikely to change, but must be implemented in a `ERCRegistry` subclass in order to be compatible with the `PM` module. Any custom methods (eg. not definied in ERC1319) in a subclass should *not* be prefixed with an underscore. All of these methods must be implemented in any subclass in order to work with `web3.pm.PM`. Any implementation specific logic should be handled in a subclass. """ @abstractmethod def __init__(self, address: Address, w3: Web3) -> None: """ Initializes the class with the on-chain address of the registry, and a web3 instance connected to the chain where the registry can be found. Must set the following properties... * ``self.registry``: A `web3.contract` instance of the target registry. * ``self.address``: The address of the target registry. * ``self.w3``: The *web3* instance connected to the chain where the registry can be found. """ pass # # Write API # @abstractmethod def _release(self, package_name: str, version: str, manifest_uri: str) -> bytes: """ Returns the releaseId created by successfully adding a release to the registry. * Parameters: * ``package_name``: Valid package name according the spec. * ``version``: Version identifier string, can conform to any versioning scheme. * ``manifest_uri``: URI location of a manifest which details the release contents """ pass # # Read API # @abstractmethod def _get_package_name(self, package_id: bytes) -> str: """ Returns the package name associated with the given package id, if the package id exists on the connected registry. * Parameters: * ``package_id``: 32 byte package identifier. """ pass @abstractmethod def _get_all_package_ids(self) -> Tuple[bytes]: """ Returns a tuple containing all of the package ids found on the connected registry. """ pass @abstractmethod def _get_release_id(self, package_name: str, version: str) -> bytes: """ Returns the 32 bytes release id associated with the given package name and version, if the release exists on the connected registry. * Parameters: * ``package_name``: Valid package name according the spec. * ``version``: Version identifier string, can conform to any versioning scheme. """ pass @abstractmethod def _get_all_release_ids(self, package_name: str) -> Tuple[bytes]: """ Returns a tuple containg all of the release ids belonging to the given package name, if the package has releases on the connected registry. * Parameters: * ``package_name``: Valid package name according the spec. """ pass @abstractmethod def _get_release_data(self, release_id: bytes) -> Tuple[str, str, str]: """ Returns a tuple containing (package_name, version, manifest_uri) for the given release id, if the release exists on the connected registry. * Parameters: * ``release_id``: 32 byte release identifier. """ pass @abstractmethod def _generate_release_id(self, package_name: str, version: str) -> bytes: """ Returns the 32 byte release identifier that *would* be associated with the given package name and version according to the registry's hashing mechanism. The release *does not* have to exist on the connected registry. * Parameters: * ``package_name``: Valid package name according the spec. * ``version``: Version identifier string, can conform to any versioning scheme. """ pass @abstractmethod def _num_package_ids(self) -> int: """ Returns the number of packages that exist on the connected registry. """ pass @abstractmethod def _num_release_ids(self, package_name: str) -> int: """ Returns the number of releases found on the connected registry, that belong to the given package name. * Parameters: * ``package_name``: Valid package name according the spec. """ pass class VyperReferenceRegistry(ERCRegistry): """ The ``VyperReferenceRegistry`` class implements all of the methods found in ``ERCRegistry``, along with some custom methods included in the `implementation <https://github.com/ethpm/py-ethpm/blob/master/ethpm/assets/vyper_registry/registry.vy>`__. """ def __init__(self, address: Address, w3: Web3) -> None: # todo: validate runtime bytecode abi = get_vyper_registry_manifest()["contract_types"]["registry"]["abi"] self.registry = w3.eth.contract(address=address, abi=abi) self.address = to_checksum_address(address) self.w3 = w3 @classmethod def deploy_new_instance(cls, w3: Web3) -> "VyperReferenceRegistry": """ Returns a new instance of ```VyperReferenceRegistry`` representing a freshly deployed instance on the given ``web3`` instance of the Vyper Reference Registry implementation. """ manifest = get_vyper_registry_manifest() registry_package = Package(manifest, w3) registry_factory = registry_package.get_contract_factory("registry") tx_hash = registry_factory.constructor().transact() tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash) registry_address = to_canonical_address(tx_receipt.contractAddress) return cls(registry_address, w3) def _release(self, package_name: str, version: str, manifest_uri: str) -> bytes: if len(package_name) > 32 or len(version) > 32: raise PMError( "Vyper registry only works with package names and versions less than 32 chars." ) if len(manifest_uri) > 1000: raise PMError( "Vyper registry only works with manifest URIs shorter than 1000 chars." ) args = process_vyper_args(package_name, version, manifest_uri) tx_hash = self.registry.functions.release(*args).transact() self.w3.eth.waitForTransactionReceipt(tx_hash) return self._get_release_id(package_name, version) def _get_package_name(self, package_id: bytes) -> str: package_name = self.registry.functions.getPackageName(package_id).call() return to_text(package_name.rstrip(b"\x00")) @to_tuple def _get_all_package_ids(self) -> Iterable[Tuple[bytes]]: num_packages = self._num_package_ids() for index in range(0, num_packages, 4): package_ids = self.registry.functions.getAllPackageIds(index, 5).call() for package_id in package_ids: if package_id != b"\x00" * 32: yield package_id def _get_release_id(self, package_name: str, version: str) -> bytes: actual_args = process_vyper_args(package_name, version) return self.registry.functions.getReleaseId(*actual_args).call() @to_tuple def _get_all_release_ids(self, package_name: str) -> Iterable[Tuple[bytes]]: actual_name = process_vyper_args(package_name) num_releases = self.registry.functions.numReleaseIds(*actual_name).call() for index in range(0, num_releases, 4): release_ids = self.registry.functions.getAllReleaseIds( *actual_name, index, 5 ).call() for release_id in release_ids: if release_id != b"\x00" * 32: yield release_id @to_tuple def _get_release_data(self, release_id: bytes) -> Iterable[Tuple[str]]: release_data = self.registry.functions.getReleaseData(release_id).call() for data in release_data: if data != b"\x00" * 32: yield to_text(data.rstrip(b"\x00")) def _generate_release_id(self, package_name: str, version: str) -> bytes: args = process_vyper_args(package_name, version) return self.registry.functions.generateReleaseId(*args).call() def _num_package_ids(self) -> int: return self.registry.functions.numPackageIds().call() def _num_release_ids(self, package_name: str) -> int: args = process_vyper_args(package_name) return self.registry.functions.numReleaseIds(*args).call() def owner(self) -> Address: """ Returns the address of the ``owner`` of this registry instance. Only the ``owner`` is allowed to add releases to the Vyper Reference Registry implementation. """ return self.registry.functions.owner().call() def transfer_owner(self, new_owner: Address) -> TxReceipt: """ Transfers ownership of this registry instance to the given ``new_owner``. Only the ``owner`` is allowed to transfer ownership. * Parameters: * ``new_owner``: The address of the new owner. """ tx_hash = self.registry.functions.transferOwner(new_owner).transact() return self.w3.eth.waitForTransactionReceipt(tx_hash) class SolidityReferenceRegistry(ERCRegistry): """ This class represents an instance of the `Solidity Reference Registry implementation <https://github.com/ethpm/py-ethpm/tree/master/ethpm/assets/registry>`__. To use this subclass, you must manually set an instance of this class to the ``registry`` attribute on ``web3.pm``. """ def __init__(self, address: Address, w3: Web3) -> None: abi = get_solidity_registry_manifest()["contract_types"]["PackageRegistry"][ "abi" ] self.registry = w3.eth.contract(address=address, abi=abi) self.address = to_checksum_address(address) self.w3 = w3 def _release(self, package_name: str, version: str, manifest_uri: str) -> bytes: tx_hash = self.registry.functions.release( package_name, version, manifest_uri ).transact() self.w3.eth.waitForTransactionReceipt(tx_hash) return self._get_release_id(package_name, version) def _get_package_name(self, package_id: bytes) -> str: package_name = self.registry.functions.getPackageName(package_id).call() return package_name @to_tuple def _get_all_package_ids(self) -> Iterable[Tuple[bytes]]: num_packages = self._num_package_ids() # Logic here b/c Solidity Reference Registry implementation returns ids in reverse order package_ids = [ self.registry.functions.getAllPackageIds(index, (index + 4)).call()[0] for index in range(0, num_packages, 4) ] for package_id in concat([x[::-1] for x in package_ids]): yield package_id def _get_release_id(self, package_name: str, version: str) -> bytes: return self.registry.functions.getReleaseId(package_name, version).call() @to_tuple def _get_all_release_ids(self, package_name: str) -> Iterable[Tuple[bytes]]: num_releases = self._num_release_ids(package_name) # Logic here b/c Solidity Reference Registry implementation returns ids in reverse order release_ids = [ self.registry.functions.getAllReleaseIds( package_name, index, (index + 4) ).call()[0] for index in range(0, num_releases, 4) ] for release_id in concat([x[::-1] for x in release_ids]): yield release_id @to_tuple def _get_release_data(self, release_id: bytes) -> Iterable[Tuple[str]]: release_data = self.registry.functions.getReleaseData(release_id).call() for data in release_data: yield data def _generate_release_id(self, package_name: str, version: str) -> bytes: return self.registry.functions.generateReleaseId(package_name, version).call() def _num_package_ids(self) -> int: return self.registry.functions.numPackageIds().call() def _num_release_ids(self, package_name: str) -> int: return self.registry.functions.numReleaseIds(package_name).call() class PM(Module): """ By default, the PM module uses the Vyper Reference Registry `implementation <https://github.com/ethpm/py-ethpm/blob/master/ethpm/assets/vyper_registry/registry.vy>`__. However, it will work with any subclass of ``ERCRegistry``, tailored to a particular implementation of `ERC1319 <https://github.com/ethereum/EIPs/issues/1319>`__, set as its ``registry`` attribute. """ def get_package_from_manifest(self, manifest: Manifest) -> Package: """ Returns a `Package <https://github.com/ethpm/py-ethpm/blob/master/ethpm/package.py>`__ instance built with the given manifest. * Parameters: * ``manifest``: A dict representing a valid manifest """ return Package(manifest, self.web3) def get_package_from_uri(self, manifest_uri: URI) -> Package: """ Returns a `Package <https://github.com/ethpm/py-ethpm/blob/master/ethpm/package.py>`__ instance built with the Manifest stored at the URI. If you want to use a specific IPFS backend, set ``ETHPM_IPFS_BACKEND_CLASS`` to your desired backend. Defaults to Infura IPFS backend. * Parameters: * ``uri``: Must be a valid content-addressed URI """ return Package.from_uri(manifest_uri, self.web3) def set_registry(self, address: Address) -> None: """ Sets the current registry used in ``web3.pm`` functions that read/write to an on-chain registry. This method accepts checksummed/canonical addresses or ENS names. Addresses must point to an instance of the Vyper Reference Registry implementation. If you want to use a different registry implementation with ``web3.pm``, manually set the ``web3.pm.registry`` attribute to any subclass of ``ERCRegistry``. To use an ENS domain as the address, make sure a valid ENS instance set as ``web3.ens``. * Parameters: * ``address``: Address of on-chain Vyper Reference Registry. """ if is_canonical_address(address) or is_checksum_address(address): canonical_address = to_canonical_address(address) self.registry = VyperReferenceRegistry(canonical_address, self.web3) elif is_ens_name(address): self._validate_set_ens() addr_lookup = self.web3.ens.address(address) if not addr_lookup: raise NameNotFound( "No address found after ENS lookup for name: {0}.".format(address) ) self.registry = VyperReferenceRegistry( to_canonical_address(addr_lookup), self.web3 ) else: raise PMError( "Expected a canonical/checksummed address or ENS name for the address, " "instead received {0}.".format(type(address)) ) def deploy_and_set_registry(self) -> Address: """ Returns the address of a freshly deployed instance of the `vyper registry <https://github.com/ethpm/py-ethpm/blob/master/ethpm/assets/vyper_registry/registry.vy>`__, and sets the newly deployed registry as the active registry on ``web3.pm.registry``. To tie your registry to an ENS name, use web3's ENS module, ie. .. code-block:: python w3.ens.setup_address(ens_name, w3.pm.registry.address) """ self.registry = VyperReferenceRegistry.deploy_new_instance(self.web3) return to_checksum_address(self.registry.address) def release_package( self, package_name: str, version: str, manifest_uri: str ) -> bytes: """ Returns the release id generated by releasing a package on the current registry. Requires ``web3.PM`` to have a registry set. Requires ``web3.eth.defaultAccount`` to be the registry owner. * Parameters: * ``package_name``: Must be a valid package name, matching the given manifest. * ``version``: Must be a valid package version, matching the given manifest. * ``manifest_uri``: Must be a valid content-addressed URI. Currently, only IPFS and Github content-addressed URIs are supported. """ validate_is_supported_manifest_uri(manifest_uri) raw_manifest = to_text(resolve_uri_contents(manifest_uri)) validate_raw_manifest_format(raw_manifest) manifest = json.loads(raw_manifest) validate_manifest_against_schema(manifest) if package_name != manifest['package_name']: raise ManifestValidationError( f"Provided package name: {package_name} does not match the package name " f"found in the manifest: {manifest['package_name']}." ) if version != manifest['version']: raise ManifestValidationError( f"Provided package version: {version} does not match the package version " f"found in the manifest: {manifest['version']}." ) self._validate_set_registry() return self.registry._release(package_name, version, manifest_uri) @to_tuple def get_all_package_names(self) -> Iterable[str]: """ Returns a tuple containing all the package names available on the current registry. """ self._validate_set_registry() package_ids = self.registry._get_all_package_ids() for package_id in package_ids: yield self.registry._get_package_name(package_id) def get_package_count(self) -> int: """ Returns the number of packages available on the current registry. """ self._validate_set_registry() return self.registry._num_package_ids() def get_release_count(self, package_name: str) -> int: """ Returns the number of releases of the given package name available on the current registry. """ validate_package_name(package_name) self._validate_set_registry() return self.registry._num_release_ids(package_name) def get_release_id(self, package_name: str, version: str) -> bytes: """ Returns the 32 byte identifier of a release for the given package name and version, if they are available on the current registry. """ validate_package_name(package_name) validate_package_version(version) self._validate_set_registry() return self.registry._get_release_id(package_name, version) @to_tuple def get_all_package_releases(self, package_name: str) -> Iterable[Tuple[str, str]]: """ Returns a tuple of release data (version, manifest_ur) for every release of the given package name available on the current registry. """ validate_package_name(package_name) self._validate_set_registry() release_ids = self.registry._get_all_release_ids(package_name) for release_id in release_ids: _, version, manifest_uri = self.registry._get_release_data(release_id) yield (version, manifest_uri) def get_release_id_data(self, release_id: bytes) -> Tuple[str, str, str]: """ Returns ``(package_name, version, manifest_uri)`` associated with the given release id, *if* it is available on the current registry. * Parameters: * ``release_id``: 32 byte release identifier """ self._validate_set_registry() return self.registry._get_release_data(release_id) def get_release_data(self, package_name: str, version: str) -> Tuple[str, str, str]: """ Returns ``(package_name, version, manifest_uri)`` associated with the given package name and version, *if* they are published to the currently set registry. * Parameters: * ``name``: Must be a valid package name. * ``version``: Must be a valid package version. """ validate_package_name(package_name) validate_package_version(version) self._validate_set_registry() release_id = self.registry._get_release_id(package_name, version) return self.get_release_id_data(release_id) def get_package(self, package_name: str, version: str) -> Package: """ Returns a ``Package`` instance, generated by the ``manifest_uri`` associated with the given package name and version, if they are published to the currently set registry. * Parameters: * ``name``: Must be a valid package name. * ``version``: Must be a valid package version. """ validate_package_name(package_name) validate_package_version(version) self._validate_set_registry() _, _, release_uri = self.get_release_data(package_name, version) return self.get_package_from_uri(release_uri) def _validate_set_registry(self) -> None: try: self.registry except AttributeError: raise PMError( "web3.pm does not have a set registry. " "Please set registry with either: " "web3.pm.set_registry(address) or " "web3.pm.deploy_and_set_registry()" ) if not isinstance(self.registry, ERCRegistry): raise PMError( "web3.pm requires an instance of a subclass of ERCRegistry " "to be set as the web3.pm.registry attribute. Instead found: " f"{type(self.registry)}." ) def _validate_set_ens(self) -> None: if not self.web3: raise InvalidAddress( "Could not look up ENS address because no web3 " "connection available" ) elif not self.web3.ens: raise InvalidAddress( "Could not look up ENS address because web3.ens is " "set to None" ) def get_vyper_registry_manifest() -> Dict[str, Any]: return json.loads((ASSETS_DIR / "vyper_registry" / "0.1.0.json").read_text()) def get_solidity_registry_manifest() -> Dict[str, Any]: return json.loads((ASSETS_DIR / "registry" / "1.0.0.json").read_text()) def validate_is_supported_manifest_uri(uri): if not is_ipfs_uri(uri) and not is_valid_content_addressed_github_uri(uri): raise ManifestValidationError( f"URI: {uri} is not a valid content-addressed URI. " "Currently only IPFS and Github content-addressed URIs are supported." ) @to_tuple def process_vyper_args(*args: List[str]) -> Iterable[bytes]: for arg in args: yield to_bytes(text=arg)
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/pm.py
pm.py
import functools import re from eth_utils import ( is_string, to_checksum_address, ) from web3._utils.validation import ( validate_address, ) def pad_left_hex(value, num_bytes): return value.rjust(num_bytes * 2, '0') def iso13616Prepare(iban): """ Prepare an IBAN for mod 97 computation by moving the first 4 chars to the end and transforming the letters to numbers (A = 10, B = 11, ..., Z = 35), as specified in ISO13616. @method iso13616Prepare @param {String} iban the IBAN @returns {String} the prepared IBAN """ A = ord("A") Z = ord("Z") iban = iban.upper() iban = iban[4:] + iban[:4] def charfunc(n): code = ord(n) if code >= A and code <= Z: return str(code - A + 10) else: return str(n) return "".join(map(charfunc, list(iban))) def mod9710(iban): """ Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064. @method mod9710 @param {String} iban @returns {Number} """ remainder = iban block = None while len(remainder) > 2: block = remainder[:9] remainder = str(int(block) % 97) + remainder[len(block):] return int(remainder) % 97 def baseN(num, b, numerals="0123456789abcdefghijklmnopqrstuvwxyz"): """ This prototype should be used to create an iban object from iban correct string @param {String} iban """ return ((num == 0) and numerals[0]) or \ (baseN(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b]) class IsValid: """ Should be called to check if iban is correct Note: This is implemented as a descriptor so that it can be called as either an instance method. @method isValid @returns {Boolean} true if it is, otherwise false """ def __get__(self, instance, owner): if instance is None: return self.validate return functools.partial(self.validate, instance._iban) @staticmethod def validate(iban_address): if not is_string(iban_address): return False if re.match(r"^XE[0-9]{2}(ETH[0-9A-Z]{13}|[0-9A-Z]{30,31})$", iban_address) and \ mod9710(iso13616Prepare(iban_address)) == 1: return True return False class Iban: def __init__(self, iban): self._iban = iban @staticmethod def fromAddress(address): """ This method should be used to create an iban object from ethereum address @method fromAddress @param {String} address @return {Iban} the IBAN object """ validate_address(address) address_as_integer = int(address, 16) address_as_base36 = baseN(address_as_integer, 36) padded = pad_left_hex(address_as_base36, 15) return Iban.fromBban(padded.upper()) @staticmethod def fromBban(bban): """ Convert the passed BBAN to an IBAN for this country specification. Please note that <i>"generation of the IBAN shall be the exclusive responsibility of the bank/branch servicing the account"</i>. This method implements the preferred algorithm described in http://en.wikipedia.org/wiki/International_Bank_Account_Number#Generating_IBAN_check_digits @method fromBban @param {String} bban the BBAN to convert to IBAN @returns {Iban} the IBAN object """ countryCode = "XE" remainder = mod9710(iso13616Prepare(countryCode + "00" + bban)) checkDigit = ("0" + str(98 - remainder))[-2:] return Iban(countryCode + checkDigit + bban) @staticmethod def createIndirect(options): """ Should be used to create IBAN object for given institution and identifier @method createIndirect @param {Object} options, required options are "institution" and "identifier" @return {Iban} the IBAN object """ return Iban.fromBban("ETH" + options["institution"] + options["identifier"]) isValid = IsValid() def isDirect(self): """ Should be called to check if iban number is direct @method isDirect @returns {Boolean} true if it is, otherwise false """ return len(self._iban) in [34, 35] def isIndirect(self): """ Should be called to check if iban number if indirect @method isIndirect @returns {Boolean} true if it is, otherwise false """ return len(self._iban) == 20 def checksum(self): """ Should be called to get iban checksum Uses the mod-97-10 checksumming protocol (ISO/IEC 7064:2003) @method checksum @returns {String} checksum """ return self._iban[2:4] def institution(self): """ Should be called to get institution identifier eg. XREG @method institution @returns {String} institution identifier """ if self.isIndirect(): return self._iban[7:11] else: return "" def client(self): """ Should be called to get client identifier within institution eg. GAVOFYORK @method client @returns {String} client identifier """ if self.isIndirect(): return self._iban[11:] else: return "" def address(self): """ Should be called to get client direct address @method address @returns {String} client direct address """ if self.isDirect(): base36 = self._iban[4:] asInt = int(base36, 36) return to_checksum_address(pad_left_hex(baseN(asInt, 16), 20)) return "" def toString(self): return self._iban
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/iban.py
iban.py
from collections import ( Hashable, Mapping, MutableMapping, OrderedDict, Sequence, ) from eth_utils import ( is_integer, ) from web3._utils.formatters import ( recursive_map, ) # Hashable must be immutable: # "the implementation of hashable collections requires that a key's hash value is immutable" # https://docs.python.org/3/reference/datamodel.html#object.__hash__ class ReadableAttributeDict(Mapping): """ The read attributes for the AttributeDict types """ def __init__(self, dictionary, *args, **kwargs): self.__dict__ = dict(dictionary) self.__dict__.update(dict(*args, **kwargs)) def __getitem__(self, key): return self.__dict__[key] def __iter__(self): return iter(self.__dict__) def __len__(self): return len(self.__dict__) def __repr__(self): return self.__class__.__name__ + "(%r)" % self.__dict__ def _repr_pretty_(self, builder, cycle): """ Custom pretty output for the IPython console """ builder.text(self.__class__.__name__ + "(") if cycle: builder.text("<cycle>") else: builder.pretty(self.__dict__) builder.text(")") @classmethod def _apply_if_mapping(cls, value): if isinstance(value, Mapping): return cls(value) else: return value @classmethod def recursive(cls, value): return recursive_map(cls._apply_if_mapping, value) class MutableAttributeDict(MutableMapping, ReadableAttributeDict): def __setitem__(self, key, val): self.__dict__[key] = val def __delitem__(self, key): del self.__dict__[key] class AttributeDict(ReadableAttributeDict, Hashable): """ This provides superficial immutability, someone could hack around it """ def __setattr__(self, attr, val): if attr == '__dict__': super().__setattr__(attr, val) else: raise TypeError('This data is immutable -- create a copy instead of modifying') def __delattr__(self, key): raise TypeError('This data is immutable -- create a copy instead of modifying') def __hash__(self): return hash(tuple(sorted(self.items()))) def __eq__(self, other): if isinstance(other, Mapping): return self.__dict__ == dict(other) else: return False class NamedElementOnion(Mapping): """ Add layers to an onion-shaped structure. Optionally, inject to a specific layer. This structure is iterable, where the outermost layer is first, and innermost is last. """ def __init__(self, init_elements, valid_element=callable): self._queue = OrderedDict() for element in reversed(init_elements): if valid_element(element): self.add(element) else: self.add(*element) def add(self, element, name=None): if name is None: name = element if name in self._queue: if name is element: raise ValueError("You can't add the same un-named instance twice") else: raise ValueError("You can't add the same name again, use replace instead") self._queue[name] = element def inject(self, element, name=None, layer=None): """ Inject a named element to an arbitrary layer in the onion. The current implementation only supports insertion at the innermost layer, or at the outermost layer. Note that inserting to the outermost is equivalent to calling :meth:`add` . """ if not is_integer(layer): raise TypeError("The layer for insertion must be an int.") elif layer != 0 and layer != len(self._queue): raise NotImplementedError( "You can only insert to the beginning or end of a %s, currently. " "You tried to insert to %d, but only 0 and %d are permitted. " % ( type(self), layer, len(self._queue), ) ) self.add(element, name=name) if layer == 0: if name is None: name = element self._queue.move_to_end(name, last=False) elif layer == len(self._queue): return else: raise AssertionError("Impossible to reach: earlier validation raises an error") def clear(self): self._queue.clear() def replace(self, old, new): if old not in self._queue: raise ValueError("You can't replace unless one already exists, use add instead") to_be_replaced = self._queue[old] if to_be_replaced is old: # re-insert with new name in old slot self._replace_with_new_name(old, new) else: self._queue[old] = new return to_be_replaced def remove(self, old): if old not in self._queue: raise ValueError("You can only remove something that has been added") del self._queue[old] def _replace_with_new_name(self, old, new): self._queue[new] = new found_old = False for key in list(self._queue.keys()): if not found_old: if key == old: found_old = True continue elif key != new: self._queue.move_to_end(key) del self._queue[old] def __iter__(self): elements = self._queue.values() if not isinstance(elements, Sequence): elements = list(elements) return iter(reversed(elements)) def __add__(self, other): if not isinstance(other, NamedElementOnion): raise NotImplementedError("You can only combine with another NamedElementOnion") combined = self._queue.copy() combined.update(other._queue) return NamedElementOnion(combined.items()) def __contains__(self, element): return element in self._queue def __getitem__(self, element): return self._queue[element] def __len__(self): return len(self._queue) def __reversed__(self): elements = self._queue.values() if not isinstance(elements, Sequence): elements = list(elements) return iter(elements)
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/datastructures.py
datastructures.py
from web3.module import ( Module, ) class Testing(Module): def timeTravel(self, timestamp): return self.web3.manager.request_blocking("testing_timeTravel", [timestamp]) def mine(self, num_blocks=1): return self.web3.manager.request_blocking("evm_mine", [num_blocks]) def snapshot(self): self.last_snapshot_idx = self.web3.manager.request_blocking("evm_snapshot", []) return self.last_snapshot_idx def reset(self): return self.web3.manager.request_blocking("evm_reset", []) def revert(self, snapshot_idx=None): if snapshot_idx is None: revert_target = self.last_snapshot_idx else: revert_target = snapshot_idx return self.web3.manager.request_blocking("evm_revert", [revert_target])
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/testing.py
testing.py
from eth_utils.toolz import ( curry, pipe, ) @curry def retrieve_blocking_method_call_fn(w3, module, method): def caller(*args, **kwargs): (method_str, params), output_formatters = method.process_params(module, *args, **kwargs) return pipe( w3.manager.request_blocking(method_str, params), *output_formatters) return caller @curry def retrieve_async_method_call_fn(w3, module, method): async def caller(*args, **kwargs): (method_str, params), output_formatters = method.process_params(module, *args, **kwargs) raw_result = await w3.manager.coro_request(method_str, params) return pipe(raw_result, *output_formatters) return caller # TODO: Replace this with ModuleV2 when ready. class Module: web3 = None def __init__(self, web3): self.web3 = web3 @classmethod def attach(cls, target, module_name=None): if not module_name: module_name = cls.__name__.lower() if hasattr(target, module_name): raise AttributeError( "Cannot set {0} module named '{1}'. The web3 object " "already has an attribute with that name".format( target, module_name, ) ) if isinstance(target, Module): web3 = target.web3 else: web3 = target setattr(target, module_name, cls(web3)) # Module should no longer have access to the full web3 api. # Only the calling functions need access to the request methods. # Any "re-entrant" shinanigans can go in the middlewares, which do # have web3 access. class ModuleV2(Module): is_async = False def __init__(self, web3): if self.is_async: self.retrieve_caller_fn = retrieve_async_method_call_fn(web3, self) else: self.retrieve_caller_fn = retrieve_blocking_method_call_fn(web3, self)
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/module.py
module.py
from web3._utils.filters import ( ShhFilter, ) from web3.module import ( Module, ) class Shh(Module): @property def version(self): return self.web3.manager.request_blocking("shh_version", []) @property def info(self): return self.web3.manager.request_blocking("shh_info", []) def setMaxMessageSize(self, size): return self.web3.manager.request_blocking("shh_setMaxMessageSize", [size]) def setMinPoW(self, min_pow): return self.web3.manager.request_blocking("shh_setMinPoW", [min_pow]) def markTrustedPeer(self, enode): return self.web3.manager.request_blocking("shh_markTrustedPeer", [enode]) def newKeyPair(self): return self.web3.manager.request_blocking("shh_newKeyPair", []) def addPrivateKey(self, key): return self.web3.manager.request_blocking("shh_addPrivateKey", [key]) def deleteKeyPair(self, id): return self.web3.manager.request_blocking("shh_deleteKeyPair", [id]) def hasKeyPair(self, id): return self.web3.manager.request_blocking("shh_hasKeyPair", [id]) def getPublicKey(self, id): return self.web3.manager.request_blocking("shh_getPublicKey", [id]) def getPrivateKey(self, id): return self.web3.manager.request_blocking("shh_getPrivateKey", [id]) def newSymKey(self): return self.web3.manager.request_blocking("shh_newSymKey", []) def addSymKey(self, key): return self.web3.manager.request_blocking("shh_addSymKey", [key]) def generateSymKeyFromPassword(self, password): return self.web3.manager.request_blocking("shh_generateSymKeyFromPassword", [password]) def hasSymKey(self, id): return self.web3.manager.request_blocking("shh_hasSymKey", [id]) def getSymKey(self, id): return self.web3.manager.request_blocking("shh_getSymKey", [id]) def deleteSymKey(self, id): return self.web3.manager.request_blocking("shh_deleteSymKey", [id]) def post(self, message): if message and ("payload" in message): return self.web3.manager.request_blocking("shh_post", [message]) else: raise ValueError( "message cannot be None or does not contain field 'payload'" ) def newMessageFilter(self, criteria, poll_interval=None): filter_id = self.web3.manager.request_blocking("shh_newMessageFilter", [criteria]) return ShhFilter(self.web3, filter_id, poll_interval=poll_interval) def deleteMessageFilter(self, filter_id): return self.web3.manager.request_blocking("shh_deleteMessageFilter", [filter_id]) def getMessages(self, filter_id): return self.web3.manager.request_blocking("shh_getFilterMessages", [filter_id])
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/shh.py
shh.py
from web3.module import ( Module, ) class Personal(Module): """ https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal """ def importRawKey(self, private_key, passphrase): return self.web3.manager.request_blocking( "personal_importRawKey", [private_key, passphrase], ) def newAccount(self, password): return self.web3.manager.request_blocking( "personal_newAccount", [password], ) @property def listAccounts(self): return self.web3.manager.request_blocking( "personal_listAccounts", [], ) def sendTransaction(self, transaction, passphrase): return self.web3.manager.request_blocking( "personal_sendTransaction", [transaction, passphrase], ) def lockAccount(self, account): return self.web3.manager.request_blocking( "personal_lockAccount", [account], ) def unlockAccount(self, account, passphrase, duration=None): try: return self.web3.manager.request_blocking( "personal_unlockAccount", [account, passphrase, duration], ) except ValueError as err: if "could not decrypt" in str(err): # Hack to handle go-ethereum error response. return False else: raise def sign(self, message, signer, passphrase): return self.web3.manager.request_blocking( 'personal_sign', [message, signer, passphrase], ) def ecRecover(self, message, signature): return self.web3.manager.request_blocking( 'personal_ecRecover', [message, signature], )
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/personal.py
personal.py
from web3.module import ( Module, ) class TxPool(Module): @property def content(self): return self.web3.manager.request_blocking("txpool_content", []) @property def inspect(self): return self.web3.manager.request_blocking("txpool_inspect", []) @property def status(self): return self.web3.manager.request_blocking("txpool_status", [])
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/txpool.py
txpool.py
import logging import uuid from web3._utils.decorators import ( deprecated_for, ) from web3._utils.threads import ( spawn, ) from web3.datastructures import ( NamedElementOnion, ) from web3.middleware import ( abi_middleware, attrdict_middleware, gas_price_strategy_middleware, name_to_address_middleware, normalize_errors_middleware, pythonic_middleware, request_parameter_normalizer, validation_middleware, ) from web3.providers import ( AutoProvider, ) class RequestManager: logger = logging.getLogger("web3.RequestManager") def __init__(self, web3, provider=None, middlewares=None): self.web3 = web3 self.pending_requests = {} if middlewares is None: middlewares = self.default_middlewares(web3) self.middleware_onion = NamedElementOnion(middlewares) if provider is None: self.provider = AutoProvider() else: self.provider = provider web3 = None _provider = None @property def provider(self): return self._provider @provider.setter def provider(self, provider): self._provider = provider @staticmethod def default_middlewares(web3): """ List the default middlewares for the request manager. Leaving ens unspecified will prevent the middleware from resolving names. """ return [ (request_parameter_normalizer, 'request_param_normalizer'), (gas_price_strategy_middleware, 'gas_price_strategy'), (name_to_address_middleware(web3), 'name_to_address'), (attrdict_middleware, 'attrdict'), (pythonic_middleware, 'pythonic'), (normalize_errors_middleware, 'normalize_errors'), (validation_middleware, 'validation'), (abi_middleware, 'abi'), ] # # Provider requests and response # def _make_request(self, method, params): request_func = self.provider.request_func( self.web3, tuple(self.middleware_onion)) self.logger.debug("Making request. Method: %s", method) return request_func(method, params) async def _coro_make_request(self, method, params): request_func = self.provider.request_func( self.web3, tuple(self.middleware_onion)) self.logger.debug("Making request. Method: %s", method) return await request_func(method, params) def request_blocking(self, method, params): """ Make a synchronous request using the provider """ response = self._make_request(method, params) if "error" in response: raise ValueError(response["error"]) return response['result'] async def coro_request(self, method, params): """ Couroutine for making a request using the provider """ response = await self._coro_make_request(method, params) if "error" in response: raise ValueError(response["error"]) return response['result'] @deprecated_for("coro_request") def request_async(self, raw_method, raw_params): request_id = uuid.uuid4() self.pending_requests[request_id] = spawn( self.request_blocking, raw_method=raw_method, raw_params=raw_params, ) return request_id def receive_blocking(self, request_id, timeout=None): try: request = self.pending_requests.pop(request_id) except KeyError: raise KeyError("Request for id:{0} not found".format(request_id)) else: response = request.get(timeout=timeout) if "error" in response: raise ValueError(response["error"]) return response['result'] def receive_async(self, request_id, *args, **kwargs): raise NotImplementedError("Callback pattern not implemented")
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/manager.py
manager.py
from web3.method import ( Method, ) from web3.module import ( Module, ModuleV2, ) class BaseVersion(ModuleV2): retrieve_caller_fn = None _get_node_version = Method('web3_clientVersion') _get_protocol_version = Method('eth_protocolVersion') @property def api(self): from web3 import __version__ return __version__ class AsyncVersion(BaseVersion): is_async = True @property async def node(self): return await self._get_node_version() @property async def ethereum(self): return await self._get_protocol_version() class BlockingVersion(BaseVersion): @property def node(self): return self._get_node_version() @property def ethereum(self): return self._get_protocol_version() class Version(Module): @property def api(self): from web3 import __version__ return __version__ @property def node(self): return self.web3.manager.request_blocking("web3_clientVersion", []) @property def ethereum(self): return self.web3.manager.request_blocking("eth_protocolVersion", [])
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/version.py
version.py
import pkg_resources import sys import warnings if (3, 5) <= sys.version_info < (3, 6): warnings.warn( "Support for Python 3.5 will be removed in web3.py v5", category=DeprecationWarning, stacklevel=2) if sys.version_info < (3, 5): raise EnvironmentError( "Python 3.5 or above is required. " "Note that support for Python 3.5 will be remove in web3.py v5") from eth_account import Account # noqa: E402 from web3.main import Web3 # noqa: E402 from web3.providers.rpc import ( # noqa: E402 HTTPProvider, ) from web3.providers.eth_tester import ( # noqa: E402 EthereumTesterProvider, ) from web3.providers.ipc import ( # noqa: E402 IPCProvider, ) from web3.providers.websocket import ( # noqa: E402 WebsocketProvider, ) __version__ = pkg_resources.get_distribution("web3").version __all__ = [ "__version__", "Web3", "HTTPProvider", "IPCProvider", "WebsocketProvider", "TestRPCProvider", "EthereumTesterProvider", "Account", ]
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/__init__.py
__init__.py
import functools from eth_utils import ( to_tuple, ) from eth_utils.toolz import ( identity, pipe, ) def _munger_star_apply(fn): @functools.wraps(fn) def inner(args): return fn(*args) return inner def get_default_formatters(*args, **kwargs): return ([identity], [identity],) def default_munger(module, *args, **kwargs): if not args and not kwargs: return tuple() else: raise TypeError("Parameters passed to method without parameter mungers defined.") class Method: """Method object for web3 module methods Calls to the Method go through these steps: 1. input munging - includes normalization, parameter checking, early parameter formatting. Any processing on the input parameters that need to happen before json_rpc method string selection occurs. A note about mungers: The first (root) munger should reflect the desired api function arguments. In other words, if the api function wants to behave as: `getBalance(account, block_identifier=None)`, the root munger should accept these same arguments, with the addition of the module as the first argument e.g.: ``` def getBalance_root_munger(module, account, block_identifier=None): if block_identifier is None: block_identifier = DEFAULT_BLOCK return module, [account, block_identifier] ``` all mungers should return an argument list. if no munger is provided, a default munger expecting no method arguments will be used. 2. method selection - The json_rpc_method argument can be method string or a function that returns a method string. If a callable is provided the processed method inputs are passed to the method selection function, and the returned method string is used. 3. request and response formatters are retrieved - formatters are retrieved using the json rpc method string. The lookup function provided by the formatter_lookup_fn configuration is passed the method string and is expected to return a 2-tuple of lists containing the request_formatters and response_formatters in that order. e.g. ([*request_formatters], [*response_formatters]). 4. After the parameter processing from steps 1-3 the request is made using the calling function returned by the module attribute ``retrieve_caller_fn`` and the reponse formatters are applied to the output. """ def __init__( self, json_rpc_method=None, mungers=None, formatter_lookup_fn=None, web3=None): self.json_rpc_method = json_rpc_method self.mungers = mungers or [default_munger] self.formatter_lookup_fn = formatter_lookup_fn or get_default_formatters def __get__(self, obj=None, obj_type=None): if obj is None: raise TypeError( "Direct calls to methods are not supported. " "Methods must be called from an module instance, " "usually attached to a web3 instance.") return obj.retrieve_caller_fn(self) @property def method_selector_fn(self): """Gets the method selector from the config. """ if callable(self.json_rpc_method): return self.json_rpc_method elif isinstance(self.json_rpc_method, (str,)): return lambda *_: self.json_rpc_method raise ValueError("``json_rpc_method`` config invalid. May be a string or function") def get_formatters(self, method_string): """Lookup the request formatters for the rpc_method The lookup_fn output is expected to be a 2 length tuple of lists of the request and output formatters, respectively. """ formatters = self.formatter_lookup_fn(method_string) return formatters or get_default_formatters() def input_munger(self, val): try: module, args, kwargs = val except TypeError: raise ValueError("input_munger expects a 3-tuple") # TODO: Create friendly error output. mungers_iter = iter(self.mungers) root_munger = next(mungers_iter) munged_inputs = pipe( root_munger(module, *args, **kwargs), *map(lambda m: _munger_star_apply(functools.partial(m, module)), mungers_iter)) return munged_inputs def process_params(self, module, *args, **kwargs): # takes in input params, steps 1-3 params, method, (req_formatters, ret_formatters) = _pipe_and_accumulate( (module, args, kwargs,), [self.input_munger, self.method_selector_fn, self.get_formatters]) return (method, pipe(params, *req_formatters)), ret_formatters @to_tuple def _pipe_and_accumulate(val, fns): """pipes val through a list of fns while accumulating results from each function, returning a tuple. e.g.: >>> _pipe_and_accumulate([lambda x: x**2, lambda x: x*10], 5) (25, 250) """ for fn in fns: val = fn(val) yield val
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/method.py
method.py
import datetime import time class BadFunctionCallOutput(Exception): """ We failed to decode ABI output. Most likely ABI mismatch. """ pass class BlockNumberOutofRange(Exception): """ block_identifier passed does not match known block. """ pass class CannotHandleRequest(Exception): """ Raised by a provider to signal that it cannot handle an RPC request and that the manager should proceed to the next provider. """ pass class InvalidAddress(ValueError): """ The supplied address does not have a valid checksum, as defined in EIP-55 """ pass class NameNotFound(ValueError): """ Raised when a caller provides an Ethereum Name Service name that does not resolve to an address. """ pass class StaleBlockchain(Exception): """ Raised by the stalecheck_middleware when the latest block is too old. """ def __init__(self, block, allowable_delay): last_block_date = datetime.datetime.fromtimestamp(block.timestamp).strftime('%c') message = ( "The latest block, #%d, is %d seconds old, but is only allowed to be %d s old. " "The date of the most recent block is %s. Continue syncing and try again..." % (block.number, time.time() - block.timestamp, allowable_delay, last_block_date) ) super().__init__(message, block, allowable_delay) def __str__(self): return self.args[0] class MismatchedABI(Exception): """ Raised when an ABI does not match with supplied parameters, or when an attempt is made to access a function/event that does not exist in the ABI. """ pass class FallbackNotFound(Exception): """ Raised when fallback function doesn't exist in contract. """ pass class ValidationError(Exception): """ Raised when a supplied value is invalid. """ pass class NoABIFunctionsFound(AttributeError): """ Raised when an ABI is present, but doesn't contain any functions. """ pass class NoABIFound(AttributeError): """ Raised when no ABI is present. """ pass class NoABIEventsFound(AttributeError): """ Raised when an ABI doesn't contain any events. """ pass class InsufficientData(Exception): """ Raised when there are insufficient data points to complete a calculation """ pass class TimeExhausted(Exception): """ Raised when a method has not retrieved the desired result within a specified timeout. """ pass class PMError(Exception): """ Raised when an error occurs in the PM module. """ pass class ManifestValidationError(PMError): """ Raised when a provided manifest cannot be published, since it's invalid. """ pass
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/exceptions.py
exceptions.py
from web3 import ( HTTPProvider, Web3, ) w3 = Web3(HTTPProvider())
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/auto/http.py
http.py
from web3 import ( IPCProvider, Web3, ) from web3.middleware import ( geth_poa_middleware, ) from web3.providers.ipc import ( get_dev_ipc_path, ) w3 = Web3(IPCProvider(get_dev_ipc_path())) w3.middleware_onion.inject(geth_poa_middleware, layer=0)
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/auto/gethdev.py
gethdev.py
from web3 import ( Web3, WebsocketProvider, ) w3 = Web3(WebsocketProvider())
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/auto/websocket.py
websocket.py
from web3 import Web3 w3 = Web3()
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/auto/__init__.py
__init__.py
from web3 import ( IPCProvider, Web3, ) w3 = Web3(IPCProvider())
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/auto/ipc.py
ipc.py
from web3 import Web3 from web3.providers.auto import ( load_provider_from_uri, ) from .endpoints import ( INFURA_ROPSTEN_DOMAIN, build_infura_url, ) _infura_url = build_infura_url(INFURA_ROPSTEN_DOMAIN) w3 = Web3(load_provider_from_uri(_infura_url))
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/auto/infura/ropsten.py
ropsten.py
from web3 import Web3 from web3.providers.auto import ( load_provider_from_uri, ) from .endpoints import ( INFURA_KOVAN_DOMAIN, build_infura_url, ) _infura_url = build_infura_url(INFURA_KOVAN_DOMAIN) w3 = Web3(load_provider_from_uri(_infura_url))
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/auto/infura/kovan.py
kovan.py
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_stack.inject(geth_poa_middleware, layer=0)
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/auto/infura/rinkeby.py
rinkeby.py
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))
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/auto/infura/__init__.py
__init__.py
import logging import os from eth_utils import ( ValidationError, ) INFURA_MAINNET_DOMAIN = 'mainnet.infura.io' INFURA_ROPSTEN_DOMAIN = 'ropsten.infura.io' INFURA_RINKEBY_DOMAIN = 'rinkeby.infura.io' INFURA_KOVAN_DOMAIN = 'kovan.infura.io' WEBSOCKET_SCHEME = 'wss' HTTP_SCHEME = 'https' def load_api_key(): # at web3py v5, drop old variable name INFURA_API_KEY key = os.environ.get( 'WEB3_INFURA_API_KEY', os.environ.get('INFURA_API_KEY', '') ) if key == '': logging.getLogger('web3.auto.infura').warning( "No Infura API Key found. Add environment variable WEB3_INFURA_API_KEY to ensure " "continued API access. New keys are available at https://infura.io/register" ) return key def build_infura_url(domain): scheme = os.environ.get('WEB3_INFURA_SCHEME', WEBSOCKET_SCHEME) if scheme == WEBSOCKET_SCHEME: # websockets doesn't use the API key (yet?) return "%s://%s/ws" % (scheme, domain) elif scheme == HTTP_SCHEME: key = load_api_key() return "%s://%s/%s" % (scheme, domain, key) else: raise ValidationError("Cannot connect to Infura with scheme %r" % scheme)
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/auto/infura/endpoints.py
endpoints.py
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))
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/auto/infura/mainnet.py
mainnet.py
from hypothesis import ( strategies as st, ) def hexstr_strategy(): return st.from_regex(r'\A(0[xX])?[0-9a-fA-F]*\Z')
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/hypothesis.py
hypothesis.py
import collections import hashlib from eth_utils import ( is_boolean, is_bytes, is_dict, is_list_like, is_null, is_number, is_text, to_bytes, ) def generate_cache_key(value): """ Generates a cache key for the *args and **kwargs """ if is_bytes(value): return hashlib.md5(value).hexdigest() elif is_text(value): return generate_cache_key(to_bytes(text=value)) elif is_boolean(value) or is_null(value) or is_number(value): return generate_cache_key(repr(value)) elif is_dict(value): return generate_cache_key(( (key, value[key]) for key in sorted(value.keys()) )) elif is_list_like(value) or isinstance(value, collections.abc.Generator): return generate_cache_key("".join(( generate_cache_key(item) for item in value ))) else: raise TypeError("Cannot generate cache key for value {0} of type {1}".format( value, type(value), ))
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/caching.py
caching.py
import functools import threading import warnings class combomethod: def __init__(self, method): self.method = method def __get__(self, obj=None, objtype=None): @functools.wraps(self.method) def _wrapper(*args, **kwargs): if obj is not None: return self.method(obj, *args, **kwargs) else: return self.method(objtype, *args, **kwargs) return _wrapper def reject_recursive_repeats(to_wrap): """ Prevent simple cycles by returning None when called recursively with same instance """ to_wrap.__already_called = {} @functools.wraps(to_wrap) def wrapped(*args): arg_instances = tuple(map(id, args)) thread_id = threading.get_ident() thread_local_args = (thread_id,) + arg_instances if thread_local_args in to_wrap.__already_called: raise ValueError('Recursively called %s with %r' % (to_wrap, args)) to_wrap.__already_called[thread_local_args] = True try: wrapped_val = to_wrap(*args) finally: del to_wrap.__already_called[thread_local_args] return wrapped_val return wrapped def deprecated_for(replace_message): """ Decorate a deprecated function, with info about what to use instead, like: @deprecated_for("toBytes()") def toAscii(arg): ... """ def decorator(to_wrap): @functools.wraps(to_wrap) def wrapper(*args, **kwargs): warnings.warn( "%s is deprecated in favor of %s" % (to_wrap.__name__, replace_message), category=DeprecationWarning, stacklevel=2) return to_wrap(*args, **kwargs) return wrapper return decorator
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/decorators.py
decorators.py
import codecs from distutils.version import ( LooseVersion, ) import functools import json import eth_abi from eth_utils import ( to_checksum_address, ) from eth_utils.address import ( is_binary_address, ) from hexbytes import ( HexBytes, ) from web3._utils.abi import ( process_type, ) from web3._utils.encoding import ( hexstr_if_str, text_if_str, to_bytes, to_hex, to_text, ) from web3._utils.ens import ( StaticENS, is_ens_name, validate_name_has_address, ) from web3._utils.toolz import ( curry, ) from web3._utils.validation import ( validate_abi, validate_address, ) from web3.exceptions import ( InvalidAddress, ) def implicitly_identity(to_wrap): @functools.wraps(to_wrap) def wrapper(abi_type, data): modified = to_wrap(abi_type, data) if modified is None: return abi_type, data else: return modified return wrapper # # Return Normalizers # @implicitly_identity def addresses_checksummed(abi_type, data): if abi_type == 'address': return abi_type, to_checksum_address(data) @implicitly_identity def decode_abi_strings(abi_type, data): if abi_type == 'string': return abi_type, codecs.decode(data, 'utf8', 'backslashreplace') # # Argument Normalizers # @implicitly_identity def abi_bytes_to_hex(abi_type, data): base, sub, arrlist = process_type(abi_type) if base == 'bytes' and not arrlist: bytes_data = hexstr_if_str(to_bytes, data) if not sub: return abi_type, to_hex(bytes_data) else: num_bytes = int(sub) if len(bytes_data) <= num_bytes: padded = bytes_data.ljust(num_bytes, b'\0') return abi_type, to_hex(padded) else: raise ValueError( "This value was expected to be at most %d bytes, but instead was %d: %r" % ( (num_bytes, len(bytes_data), data) ) ) @implicitly_identity def abi_int_to_hex(abi_type, data): base, _sub, arrlist = process_type(abi_type) if base == 'uint' and not arrlist: return abi_type, hexstr_if_str(to_hex, data) @implicitly_identity def abi_string_to_hex(abi_type, data): if abi_type == 'string': return abi_type, text_if_str(to_hex, data) @implicitly_identity def abi_string_to_text(abi_type, data): if abi_type == 'string': return abi_type, text_if_str(to_text, data) @implicitly_identity def abi_bytes_to_bytes(abi_type, data): base, sub, arrlist = process_type(abi_type) if base == 'bytes' and not arrlist: return abi_type, hexstr_if_str(to_bytes, data) @implicitly_identity def abi_address_to_hex(abi_type, data): if abi_type == 'address': validate_address(data) if is_binary_address(data): return abi_type, to_checksum_address(data) @curry def abi_ens_resolver(w3, abi_type, val): if abi_type == 'address' and is_ens_name(val): if w3 is None: raise InvalidAddress( "Could not look up name %r because no web3" " connection available" % (val) ) elif w3.ens is None: raise InvalidAddress( "Could not look up name %r because ENS is" " set to None" % (val) ) elif int(w3.net.version) is not 1 and not isinstance(w3.ens, StaticENS): raise InvalidAddress( "Could not look up name %r because web3 is" " not connected to mainnet" % (val) ) else: return (abi_type, validate_name_has_address(w3.ens, val)) else: return (abi_type, val) BASE_RETURN_NORMALIZERS = [ addresses_checksummed, ] if LooseVersion(eth_abi.__version__) < LooseVersion("2"): BASE_RETURN_NORMALIZERS.append(decode_abi_strings) # # Property Normalizers # def normalize_abi(abi): if isinstance(abi, str): abi = json.loads(abi) validate_abi(abi) return abi def normalize_address(ens, address): if address: if is_ens_name(address): validate_name_has_address(ens, address) else: validate_address(address) return address def normalize_bytecode(bytecode): if bytecode: bytecode = HexBytes(bytecode) return bytecode
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/normalizers.py
normalizers.py
from eth_abi import ( decode_abi, is_encodable, ) from eth_abi.grammar import ( parse as parse_type_string, ) from eth_utils import ( is_list_like, is_string, is_text, ) from hexbytes import ( HexBytes, ) from web3._utils.formatters import ( apply_formatter_if, ) from web3._utils.threads import ( TimerClass, ) from web3._utils.toolz import ( complement, curry, ) from web3._utils.validation import ( validate_address, ) from .events import ( construct_event_data_set, construct_event_topic_set, ) def construct_event_filter_params(event_abi, contract_address=None, argument_filters=None, topics=None, fromBlock=None, toBlock=None, address=None): filter_params = {} topic_set = construct_event_topic_set(event_abi, argument_filters) if topics is not None: if len(topic_set) > 1: raise TypeError( "Merging the topics argument with topics generated " "from argument_filters is not supported.") topic_set = topics if len(topic_set) == 1 and is_list_like(topic_set[0]): filter_params['topics'] = topic_set[0] else: filter_params['topics'] = topic_set if address and contract_address: if is_list_like(address): filter_params['address'] = address + [contract_address] elif is_string(address): filter_params['address'] = [address, contract_address] else: raise ValueError( "Unsupported type for `address` parameter: {0}".format(type(address)) ) elif address: filter_params['address'] = address elif contract_address: filter_params['address'] = contract_address if 'address' not in filter_params: pass elif is_list_like(filter_params['address']): for addr in filter_params['address']: validate_address(addr) else: validate_address(filter_params['address']) if fromBlock is not None: filter_params['fromBlock'] = fromBlock if toBlock is not None: filter_params['toBlock'] = toBlock data_filters_set = construct_event_data_set(event_abi, argument_filters) return data_filters_set, filter_params class Filter: callbacks = None stopped = False poll_interval = None filter_id = None def __init__(self, web3, filter_id): self.web3 = web3 self.filter_id = filter_id self.callbacks = [] super().__init__() def __str__(self): return "Filter for {0}".format(self.filter_id) def format_entry(self, entry): """ Hook for subclasses to change the format of the value that is passed into the callback functions. """ return entry def is_valid_entry(self, entry): """ Hook for subclasses to implement additional filtering layers. """ return True def _filter_valid_entries(self, entries): return filter(self.is_valid_entry, entries) def get_new_entries(self): log_entries = self._filter_valid_entries(self.web3.eth.getFilterChanges(self.filter_id)) return self._format_log_entries(log_entries) def get_all_entries(self): log_entries = self._filter_valid_entries(self.web3.eth.getFilterLogs(self.filter_id)) return self._format_log_entries(log_entries) def _format_log_entries(self, log_entries=None): if log_entries is None: return [] formatted_log_entries = [ self.format_entry(log_entry) for log_entry in log_entries ] return formatted_log_entries class BlockFilter(Filter): pass class TransactionFilter(Filter): pass class LogFilter(Filter): data_filter_set = None data_filter_set_regex = None log_entry_formatter = None def __init__(self, *args, **kwargs): self.log_entry_formatter = kwargs.pop( 'log_entry_formatter', self.log_entry_formatter, ) if 'data_filter_set' in kwargs: self.set_data_filters(kwargs.pop('data_filter_set')) super().__init__(*args, **kwargs) def format_entry(self, entry): if self.log_entry_formatter: return self.log_entry_formatter(entry) return entry def set_data_filters(self, data_filter_set): """Sets the data filters (non indexed argument filters) Expects a set of tuples with the type and value, e.g.: (('uint256', [12345, 54321]), ('string', ('a-single-string',))) """ self.data_filter_set = data_filter_set if any(data_filter_set): self.data_filter_set_function = match_fn(data_filter_set) def is_valid_entry(self, entry): if not self.data_filter_set: return True return bool(self.data_filter_set_function(entry['data'])) def decode_utf8_bytes(value): return value.decode("utf-8") not_text = complement(is_text) normalize_to_text = apply_formatter_if(not_text, decode_utf8_bytes) def normalize_data_values(type_string, data_value): """Decodes utf-8 bytes to strings for abi string values. eth-abi v1 returns utf-8 bytes for string values. This can be removed once eth-abi v2 is required. """ _type = parse_type_string(type_string) if _type.base == "string": if _type.arrlist is not None: return tuple((normalize_to_text(value) for value in data_value)) else: return normalize_to_text(data_value) return data_value @curry def match_fn(match_values_and_abi, data): """Match function used for filtering non-indexed event arguments. Values provided through the match_values_and_abi parameter are compared to the abi decoded log data. """ abi_types, all_match_values = zip(*match_values_and_abi) decoded_values = decode_abi(abi_types, HexBytes(data)) for data_value, match_values, abi_type in zip(decoded_values, all_match_values, abi_types): if match_values is None: continue normalized_data = normalize_data_values(abi_type, data_value) for value in match_values: if not is_encodable(abi_type, value): raise ValueError( "Value {0} is of the wrong abi type. " "Expected {1} typed value.".format(value, abi_type)) if value == normalized_data: break else: return False return True class ShhFilter(Filter): def __init__(self, *args, **kwargs): self.poll_interval = kwargs.pop( 'poll_interval', self.poll_interval, ) super().__init__(*args, **kwargs) def get_new_entries(self): log_entries = self._filter_valid_entries(self.web3.shh.getMessages(self.filter_id)) return self._format_log_entries(log_entries) def get_all_entries(self): raise NotImplementedError() def watch(self, callback): def callback_wrapper(): entries = self.get_new_entries() if entries: callback(entries) timer = TimerClass(self.poll_interval, callback_wrapper) timer.daemon = True timer.start() return timer
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/filters.py
filters.py
from eth_utils import ( to_dict, ) from web3._utils.abi import ( map_abi_data, ) from web3._utils.formatters import ( apply_formatter_at_index, ) from web3._utils.toolz import ( curry, ) TRANSACTION_PARAMS_ABIS = { 'data': 'bytes', 'from': 'address', 'gas': 'uint', 'gasPrice': 'uint', 'nonce': 'uint', 'to': 'address', 'value': 'uint', } FILTER_PARAMS_ABIS = { 'to': 'address', 'address': 'address[]', } TRACE_PARAMS_ABIS = { 'to': 'address', 'from': 'address', } RPC_ABIS = { # eth 'eth_call': TRANSACTION_PARAMS_ABIS, 'eth_estimateGas': TRANSACTION_PARAMS_ABIS, 'eth_getBalance': ['address', None], 'eth_getBlockByHash': ['bytes32', 'bool'], 'eth_getBlockTransactionCountByHash': ['bytes32'], 'eth_getCode': ['address', None], 'eth_getLogs': FILTER_PARAMS_ABIS, 'eth_getStorageAt': ['address', 'uint', None], 'eth_getTransactionByBlockHashAndIndex': ['bytes32', 'uint'], 'eth_getTransactionByHash': ['bytes32'], 'eth_getTransactionCount': ['address', None], 'eth_getTransactionReceipt': ['bytes32'], 'eth_getUncleCountByBlockHash': ['bytes32'], 'eth_newFilter': FILTER_PARAMS_ABIS, 'eth_sendRawTransaction': ['bytes'], 'eth_sendTransaction': TRANSACTION_PARAMS_ABIS, 'eth_sign': ['address', 'bytes'], # personal 'personal_sendTransaction': TRANSACTION_PARAMS_ABIS, 'personal_lockAccount': ['address'], 'personal_unlockAccount': ['address', None, None], 'personal_sign': [None, 'address', None], 'trace_call': TRACE_PARAMS_ABIS, # parity 'parity_listStorageKeys': ['address', None, None, None], } @curry def apply_abi_formatters_to_dict(normalizers, abi_dict, data): fields = list(set(abi_dict.keys()) & set(data.keys())) formatted_values = map_abi_data( normalizers, [abi_dict[field] for field in fields], [data[field] for field in fields], ) formatted_dict = dict(zip(fields, formatted_values)) return dict(data, **formatted_dict) @to_dict def abi_request_formatters(normalizers, abis): for method, abi_types in abis.items(): if isinstance(abi_types, list): yield method, map_abi_data(normalizers, abi_types) elif isinstance(abi_types, dict): single_dict_formatter = apply_abi_formatters_to_dict(normalizers, abi_types) yield method, apply_formatter_at_index(single_dict_formatter, 0) else: raise TypeError("ABI definitions must be a list or dictionary, got %r" % abi_types)
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/rpc_abi.py
rpc_abi.py
def construct_user_agent(class_name): from web3 import __version__ as web3_version user_agent = 'Web3.py/{version}/{class_name}'.format( version=web3_version, class_name=class_name, ) return user_agent
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/http.py
http.py
from contextlib import ( contextmanager, ) from eth_utils import ( is_0x_prefixed, is_hex, is_hex_address, ) from ens import ENS from web3.exceptions import ( NameNotFound, ) def is_ens_name(value): if not isinstance(value, str): return False elif is_hex_address(value): return False elif is_0x_prefixed(value) and is_hex(value): return False else: return ENS.is_valid_name(value) def validate_name_has_address(ens, name): addr = ens.address(name, guess_tld=False) if addr: return addr else: raise NameNotFound("Could not find address for name %r" % name) class StaticENS: def __init__(self, name_addr_pairs): self.registry = dict(name_addr_pairs) def address(self, name, guess_tld=True): # no automated web3 usages should be guessing the TLD assert not guess_tld return self.registry.get(name, None) @contextmanager def ens_addresses(w3, name_addr_pairs): original_ens = w3.ens w3.ens = StaticENS(name_addr_pairs) yield w3.ens = original_ens @contextmanager def contract_ens_addresses(contract, name_addr_pairs): """ Use this context manager to temporarily resolve name/address pairs supplied as the argument. For example: with contract_ens_addresses(mycontract, [('resolve-as-1s.eth', '0x111...111')]): # any contract call or transaction in here would only resolve the above ENS pair """ with ens_addresses(contract.web3, name_addr_pairs): yield
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/ens.py
ens.py
# String encodings and numeric representations import json import re from eth_abi.encoding import ( BaseArrayEncoder, ) from eth_utils import ( add_0x_prefix, big_endian_to_int, decode_hex, encode_hex, int_to_big_endian, is_boolean, is_bytes, is_hex, is_integer, is_list_like, remove_0x_prefix, to_hex, ) from hexbytes import ( HexBytes, ) from web3._utils.abi import ( is_address_type, is_array_type, is_bool_type, is_bytes_type, is_int_type, is_string_type, is_uint_type, size_of_type, sub_type_of_array_type, ) from web3._utils.toolz import ( curry, ) from web3._utils.validation import ( assert_one_val, validate_abi_type, validate_abi_value, ) from web3.datastructures import ( AttributeDict, ) def hex_encode_abi_type(abi_type, value, force_size=None): """ Encodes value into a hex string in format of abi_type """ validate_abi_type(abi_type) validate_abi_value(abi_type, value) data_size = force_size or size_of_type(abi_type) if is_array_type(abi_type): sub_type = sub_type_of_array_type(abi_type) return "".join([remove_0x_prefix(hex_encode_abi_type(sub_type, v, 256)) for v in value]) elif is_bool_type(abi_type): return to_hex_with_size(value, data_size) elif is_uint_type(abi_type): return to_hex_with_size(value, data_size) elif is_int_type(abi_type): return to_hex_twos_compliment(value, data_size) elif is_address_type(abi_type): return pad_hex(value, data_size) elif is_bytes_type(abi_type): if is_bytes(value): return encode_hex(value) else: return value elif is_string_type(abi_type): return to_hex(text=value) else: raise ValueError( "Unsupported ABI type: {0}".format(abi_type) ) def to_hex_twos_compliment(value, bit_size): """ Converts integer value to twos compliment hex representation with given bit_size """ if value >= 0: return to_hex_with_size(value, bit_size) value = (1 << bit_size) + value hex_value = hex(value) hex_value = hex_value.rstrip("L") return hex_value def to_hex_with_size(value, bit_size): """ Converts a value to hex with given bit_size: """ return pad_hex(to_hex(value), bit_size) def pad_hex(value, bit_size): """ Pads a hex string up to the given bit_size """ value = remove_0x_prefix(value) return add_0x_prefix(value.zfill(int(bit_size / 4))) def trim_hex(hexstr): if hexstr.startswith('0x0'): hexstr = re.sub('^0x0+', '0x', hexstr) if hexstr == '0x': hexstr = '0x0' return hexstr def to_int(value=None, hexstr=None, text=None): """ Converts value to it's integer representation. Values are converted this way: * value: * bytes: big-endian integer * bool: True => 1, False => 0 * hexstr: interpret hex as integer * text: interpret as string of digits, like '12' => 12 """ assert_one_val(value, hexstr=hexstr, text=text) if hexstr is not None: return int(hexstr, 16) elif text is not None: return int(text) elif isinstance(value, bytes): return big_endian_to_int(value) elif isinstance(value, str): raise TypeError("Pass in strings with keyword hexstr or text") else: return int(value) @curry def pad_bytes(fill_with, num_bytes, unpadded): return unpadded.rjust(num_bytes, fill_with) zpad_bytes = pad_bytes(b'\0') def to_bytes(primitive=None, hexstr=None, text=None): assert_one_val(primitive, hexstr=hexstr, text=text) if is_boolean(primitive): return b'\x01' if primitive else b'\x00' elif isinstance(primitive, bytes): return primitive elif is_integer(primitive): return to_bytes(hexstr=to_hex(primitive)) elif hexstr is not None: if len(hexstr) % 2: hexstr = '0x0' + remove_0x_prefix(hexstr) return decode_hex(hexstr) elif text is not None: return text.encode('utf-8') raise TypeError("expected an int in first arg, or keyword of hexstr or text") def to_text(primitive=None, hexstr=None, text=None): assert_one_val(primitive, hexstr=hexstr, text=text) if hexstr is not None: return to_bytes(hexstr=hexstr).decode('utf-8') elif text is not None: return text elif isinstance(primitive, str): return to_text(hexstr=primitive) elif isinstance(primitive, bytes): return primitive.decode('utf-8') elif is_integer(primitive): byte_encoding = int_to_big_endian(primitive) return to_text(byte_encoding) raise TypeError("Expected an int, bytes or hexstr.") @curry def text_if_str(to_type, text_or_primitive): """ Convert to a type, assuming that strings can be only unicode text (not a hexstr) @param to_type is a function that takes the arguments (primitive, hexstr=hexstr, text=text), eg~ to_bytes, to_text, to_hex, to_int, etc @param hexstr_or_primitive in bytes, str, or int. """ if isinstance(text_or_primitive, str): (primitive, text) = (None, text_or_primitive) else: (primitive, text) = (text_or_primitive, None) return to_type(primitive, text=text) @curry def hexstr_if_str(to_type, hexstr_or_primitive): """ Convert to a type, assuming that strings can be only hexstr (not unicode text) @param to_type is a function that takes the arguments (primitive, hexstr=hexstr, text=text), eg~ to_bytes, to_text, to_hex, to_int, etc @param text_or_primitive in bytes, str, or int. """ if isinstance(hexstr_or_primitive, str): (primitive, hexstr) = (None, hexstr_or_primitive) if remove_0x_prefix(hexstr) and not is_hex(hexstr): raise ValueError( "when sending a str, it must be a hex string. Got: {0!r}".format( hexstr_or_primitive, ) ) else: (primitive, hexstr) = (hexstr_or_primitive, None) return to_type(primitive, hexstr=hexstr) class FriendlyJsonSerde: """ Friendly JSON serializer & deserializer When encoding or decoding fails, this class collects information on which fields failed, to show more helpful information in the raised error messages. """ def _json_mapping_errors(self, mapping): for key, val in mapping.items(): try: self._friendly_json_encode(val) except TypeError as exc: yield "%r: because (%s)" % (key, exc) def _json_list_errors(self, iterable): for index, element in enumerate(iterable): try: self._friendly_json_encode(element) except TypeError as exc: yield "%d: because (%s)" % (index, exc) def _friendly_json_encode(self, obj, cls=None): try: encoded = json.dumps(obj, cls=cls) return encoded except TypeError as full_exception: if hasattr(obj, 'items'): item_errors = '; '.join(self._json_mapping_errors(obj)) raise TypeError("dict had unencodable value at keys: {{{}}}".format(item_errors)) elif is_list_like(obj): element_errors = '; '.join(self._json_list_errors(obj)) raise TypeError("list had unencodable value at index: [{}]".format(element_errors)) else: raise full_exception def json_decode(self, json_str): try: decoded = json.loads(json_str) return decoded except json.decoder.JSONDecodeError as exc: err_msg = 'Could not decode {} because of {}.'.format(repr(json_str), exc) # Calling code may rely on catching JSONDecodeError to recognize bad json # so we have to re-raise the same type. raise json.decoder.JSONDecodeError(err_msg, exc.doc, exc.pos) def json_encode(self, obj, cls=None): try: return self._friendly_json_encode(obj, cls=cls) except TypeError as exc: raise TypeError("Could not encode to JSON: {}".format(exc)) def to_4byte_hex(hex_or_str_or_bytes): size_of_4bytes = 4 * 8 byte_str = hexstr_if_str(to_bytes, hex_or_str_or_bytes) if len(byte_str) > 4: raise ValueError( 'expected value of size 4 bytes. Got: %d bytes' % len(byte_str) ) hex_str = encode_hex(byte_str) return pad_hex(hex_str, size_of_4bytes) class DynamicArrayPackedEncoder(BaseArrayEncoder): is_dynamic = True def encode(self, value): encoded_elements = self.encode_elements(value) encoded_value = encoded_elements return encoded_value # TODO: Replace with eth-abi packed encoder once web3 requires eth-abi>=2 def encode_single_packed(_type, value): import codecs from eth_abi import ( grammar as abi_type_parser, ) from eth_abi.registry import has_arrlist, registry abi_type = abi_type_parser.parse(_type) if has_arrlist(_type): item_encoder = registry.get_encoder(str(abi_type.item_type)) if abi_type.arrlist[-1] != 1: return DynamicArrayPackedEncoder(item_encoder=item_encoder).encode(value) else: raise NotImplementedError( "Fixed arrays are not implemented in this packed encoder prototype") elif abi_type.base == "string": return codecs.encode(value, 'utf8') elif abi_type.base == "bytes": return value class Web3JsonEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, AttributeDict): return {k: v for k, v in obj.items()} if isinstance(obj, HexBytes): return obj.hex() return json.JSONEncoder.default(self, obj) def to_json(obj): ''' Convert a complex object (like a transaction object) to a JSON string ''' return FriendlyJsonSerde().json_encode(obj, cls=Web3JsonEncoder)
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/encoding.py
encoding.py
""" A minimal implementation of the various gevent APIs used within this codebase. """ import threading import time class Timeout(Exception): """ A limited subset of the `gevent.Timeout` context manager. """ seconds = None exception = None begun_at = None is_running = None def __init__(self, seconds=None, exception=None, *args, **kwargs): self.seconds = seconds self.exception = exception def __enter__(self): self.start() return self def __exit__(self, exc_type, exc_val, exc_tb): return False def __str__(self): if self.seconds is None: return '' return "{0} seconds".format(self.seconds) @property def expire_at(self): if self.seconds is None: raise ValueError("Timeouts with `seconds == None` do not have an expiration time") elif self.begun_at is None: raise ValueError("Timeout has not been started") return self.begun_at + self.seconds def start(self): if self.is_running is not None: raise ValueError("Timeout has already been started") self.begun_at = time.time() self.is_running = True def check(self): if self.is_running is None: raise ValueError("Timeout has not been started") elif self.is_running is False: raise ValueError("Timeout has already been cancelled") elif self.seconds is None: return elif time.time() > self.expire_at: self.is_running = False if isinstance(self.exception, type): raise self.exception(str(self)) elif isinstance(self.exception, Exception): raise self.exception else: raise self def cancel(self): self.is_running = False def sleep(self, seconds): time.sleep(seconds) self.check() class ThreadWithReturn(threading.Thread): def __init__(self, target=None, args=None, kwargs=None): super().__init__( target=target, args=args or tuple(), kwargs=kwargs or {}, ) self.target = target self.args = args self.kwargs = kwargs def run(self): self._return = self.target(*self.args, **self.kwargs) def get(self, timeout=None): self.join(timeout) try: return self._return except AttributeError: raise RuntimeError("Something went wrong. No `_return` property was set") class TimerClass(threading.Thread): def __init__(self, interval, callback, *args): threading.Thread.__init__(self) self.callback = callback self.terminate_event = threading.Event() self.interval = interval self.args = args def run(self): while not self.terminate_event.is_set(): self.callback(*self.args) self.terminate_event.wait(self.interval) def stop(self): self.terminate_event.set() def spawn(target, *args, thread_class=ThreadWithReturn, **kwargs): thread = thread_class( target=target, args=args, kwargs=kwargs, ) thread.daemon = True thread.start() return thread
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/threads.py
threads.py
from web3.exceptions import ( InsufficientData, ) def percentile(values=None, percentile=None): """Calculates a simplified weighted average percentile """ if values in [None, tuple(), []] or len(values) < 1: raise InsufficientData( "Expected a sequence of at least 1 integers, got {0!r}".format(values)) if percentile is None: raise ValueError("Expected a percentile choice, got {0}".format(percentile)) sorted_values = sorted(values) rank = len(values) * percentile / 100 if rank > 0: index = rank - 1 if index < 0: return sorted_values[0] else: index = rank if index % 1 == 0: return sorted_values[int(index)] else: fractional = index % 1 integer = int(index - fractional) lower = sorted_values[integer] higher = sorted_values[integer + 1] return lower + fractional * (higher - lower)
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/math.py
math.py
import itertools from eth_utils import ( function_abi_to_4byte_selector, is_0x_prefixed, is_binary_address, is_boolean, is_bytes, is_checksum_address, is_dict, is_hex_address, is_integer, is_list_like, is_string, ) from eth_utils.hexadecimal import ( encode_hex, ) from web3._utils.abi import ( abi_to_signature, filter_by_type, is_address_type, is_array_type, is_bool_type, is_bytes_type, is_int_type, is_recognized_type, is_string_type, is_uint_type, length_of_array_type, sub_type_of_array_type, ) from web3._utils.formatters import ( apply_formatter_to_array, ) from web3._utils.toolz import ( compose, groupby, valfilter, valmap, ) from web3.exceptions import ( InvalidAddress, ) def _prepare_selector_collision_msg(duplicates): dup_sel = valmap(apply_formatter_to_array(abi_to_signature), duplicates) joined_funcs = valmap(lambda funcs: ', '.join(funcs), dup_sel) func_sel_msg_list = [funcs + ' have selector ' + sel for sel, funcs in joined_funcs.items()] return ' and\n'.join(func_sel_msg_list) def validate_abi(abi): """ Helper function for validating an ABI """ if not is_list_like(abi): raise ValueError("'abi' is not a list") if not all(is_dict(e) for e in abi): raise ValueError("'abi' is not a list of dictionaries") functions = filter_by_type('function', abi) selectors = groupby( compose(encode_hex, function_abi_to_4byte_selector), functions ) duplicates = valfilter(lambda funcs: len(funcs) > 1, selectors) if duplicates: raise ValueError( 'Abi contains functions with colliding selectors. ' 'Functions {0}'.format(_prepare_selector_collision_msg(duplicates)) ) def validate_abi_type(abi_type): """ Helper function for validating an abi_type """ if not is_recognized_type(abi_type): raise ValueError("Unrecognized abi_type: {abi_type}".format(abi_type=abi_type)) def validate_abi_value(abi_type, value): """ Helper function for validating a value against the expected abi_type Note: abi_type 'bytes' must either be python3 'bytes' object or '' """ if is_array_type(abi_type) and is_list_like(value): # validate length specified_length = length_of_array_type(abi_type) if specified_length is not None: if specified_length < 1: raise TypeError( "Invalid abi-type: {abi_type}. Length of fixed sized arrays" "must be greater than 0." .format(abi_type=abi_type) ) if specified_length != len(value): raise TypeError( "The following array length does not the length specified" "by the abi-type, {abi_type}: {value}" .format(abi_type=abi_type, value=value) ) # validate sub_types sub_type = sub_type_of_array_type(abi_type) for v in value: validate_abi_value(sub_type, v) return elif is_bool_type(abi_type) and is_boolean(value): return elif is_uint_type(abi_type) and is_integer(value) and value >= 0: return elif is_int_type(abi_type) and is_integer(value): return elif is_address_type(abi_type): validate_address(value) return elif is_bytes_type(abi_type): if is_bytes(value): return elif is_string(value): if is_0x_prefixed(value): return else: raise TypeError( "ABI values of abi-type 'bytes' must be either" "a python3 'bytes' object or an '0x' prefixed string." ) elif is_string_type(abi_type) and is_string(value): return raise TypeError( "The following abi value is not a '{abi_type}': {value}" .format(abi_type=abi_type, value=value) ) def validate_address(value): """ Helper function for validating an address """ if is_bytes(value): if not is_binary_address(value): raise InvalidAddress("Address must be 20 bytes when input type is bytes", value) return if not isinstance(value, str): raise TypeError('Address {} must be provided as a string'.format(value)) if not is_hex_address(value): raise InvalidAddress("Address must be 20 bytes, as a hex string with a 0x prefix", value) if not is_checksum_address(value): if value == value.lower(): raise InvalidAddress( "Web3.py only accepts checksum addresses. " "The software that gave you this non-checksum address should be considered unsafe, " "please file it as a bug on their platform. " "Try using an ENS name instead. Or, if you must accept lower safety, " "use Web3.toChecksumAddress(lower_case_address).", value, ) else: raise InvalidAddress( "Address has an invalid EIP-55 checksum. " "After looking up the address from the original source, try again.", value, ) def has_one_val(*args, **kwargs): vals = itertools.chain(args, kwargs.values()) not_nones = list(filter(lambda val: val is not None, vals)) return len(not_nones) == 1 def assert_one_val(*args, **kwargs): if not has_one_val(*args, **kwargs): raise TypeError( "Exactly one of the passed values can be specified. " "Instead, values were: %r, %r" % (args, kwargs) )
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/validation.py
validation.py
import functools from eth_abi import ( encode_abi as eth_abi_encode_abi, ) from eth_utils import ( add_0x_prefix, encode_hex, function_abi_to_4byte_selector, is_text, ) from hexbytes import ( HexBytes, ) from web3._utils.abi import ( abi_to_signature, check_if_arguments_can_be_encoded, filter_by_argument_count, filter_by_argument_name, filter_by_encodability, filter_by_name, filter_by_type, get_abi_input_types, get_abi_inputs, get_fallback_func_abi, map_abi_data, merge_args_and_kwargs, ) from web3._utils.encoding import ( to_hex, ) from web3._utils.function_identifiers import ( FallbackFn, ) from web3._utils.normalizers import ( abi_address_to_hex, abi_bytes_to_bytes, abi_ens_resolver, abi_string_to_text, ) from web3._utils.toolz import ( pipe, valmap, ) from web3.exceptions import ( ValidationError, ) def find_matching_event_abi(abi, event_name=None, argument_names=None): filters = [ functools.partial(filter_by_type, 'event'), ] if event_name is not None: filters.append(functools.partial(filter_by_name, event_name)) if argument_names is not None: filters.append( functools.partial(filter_by_argument_name, argument_names) ) event_abi_candidates = pipe(abi, *filters) if len(event_abi_candidates) == 1: return event_abi_candidates[0] elif not event_abi_candidates: raise ValueError("No matching events found") else: raise ValueError("Multiple events found") def find_matching_fn_abi(abi, fn_identifier=None, args=None, kwargs=None): args = args or tuple() kwargs = kwargs or dict() num_arguments = len(args) + len(kwargs) if fn_identifier is FallbackFn: return get_fallback_func_abi(abi) if not is_text(fn_identifier): raise TypeError("Unsupported function identifier") name_filter = functools.partial(filter_by_name, fn_identifier) arg_count_filter = functools.partial(filter_by_argument_count, num_arguments) encoding_filter = functools.partial(filter_by_encodability, args, kwargs) function_candidates = pipe(abi, name_filter, arg_count_filter, encoding_filter) if len(function_candidates) == 1: return function_candidates[0] else: matching_identifiers = name_filter(abi) matching_function_signatures = [abi_to_signature(func) for func in matching_identifiers] arg_count_matches = len(arg_count_filter(matching_identifiers)) encoding_matches = len(encoding_filter(matching_identifiers)) if arg_count_matches == 0: diagnosis = "\nFunction invocation failed due to improper number of arguments." elif encoding_matches == 0: diagnosis = "\nFunction invocation failed due to no matching argument types." elif encoding_matches > 1: diagnosis = ( "\nAmbiguous argument encoding. " "Provided arguments can be encoded to multiple functions matching this call." ) message = ( "\nCould not identify the intended function with name `{name}`, " "positional argument(s) of type `{arg_types}` and " "keyword argument(s) of type `{kwarg_types}`." "\nFound {num_candidates} function(s) with the name `{name}`: {candidates}" "{diagnosis}" ).format( name=fn_identifier, arg_types=tuple(map(type, args)), kwarg_types=valmap(type, kwargs), num_candidates=len(matching_identifiers), candidates=matching_function_signatures, diagnosis=diagnosis, ) raise ValidationError(message) def encode_abi(web3, abi, arguments, data=None): argument_types = get_abi_input_types(abi) if not check_if_arguments_can_be_encoded(abi, arguments, {}): raise TypeError( "One or more arguments could not be encoded to the necessary " "ABI type. Expected types are: {0}".format( ', '.join(argument_types), ) ) normalizers = [ abi_ens_resolver(web3), abi_address_to_hex, abi_bytes_to_bytes, abi_string_to_text, ] normalized_arguments = map_abi_data( normalizers, argument_types, arguments, ) encoded_arguments = eth_abi_encode_abi( argument_types, normalized_arguments, ) if data: return to_hex(HexBytes(data) + encoded_arguments) else: return encode_hex(encoded_arguments) def prepare_transaction( address, web3, fn_identifier, contract_abi=None, fn_abi=None, transaction=None, fn_args=None, fn_kwargs=None): """ :parameter `is_function_abi` is used to distinguish function abi from contract abi Returns a dictionary of the transaction that could be used to call this TODO: make this a public API TODO: add new prepare_deploy_transaction API """ if fn_abi is None: fn_abi = find_matching_fn_abi(contract_abi, fn_identifier, fn_args, fn_kwargs) validate_payable(transaction, fn_abi) if transaction is None: prepared_transaction = {} else: prepared_transaction = dict(**transaction) if 'data' in prepared_transaction: raise ValueError("Transaction parameter may not contain a 'data' key") if address: prepared_transaction.setdefault('to', address) prepared_transaction['data'] = encode_transaction_data( web3, fn_identifier, contract_abi, fn_abi, fn_args, fn_kwargs, ) return prepared_transaction def encode_transaction_data( web3, fn_identifier, contract_abi=None, fn_abi=None, args=None, kwargs=None): if fn_identifier is FallbackFn: fn_abi, fn_selector, fn_arguments = get_fallback_function_info(contract_abi, fn_abi) elif is_text(fn_identifier): fn_abi, fn_selector, fn_arguments = get_function_info( fn_identifier, contract_abi, fn_abi, args, kwargs, ) else: raise TypeError("Unsupported function identifier") return add_0x_prefix(encode_abi(web3, fn_abi, fn_arguments, fn_selector)) def get_fallback_function_info(contract_abi=None, fn_abi=None): if fn_abi is None: fn_abi = get_fallback_func_abi(contract_abi) fn_selector = encode_hex(b'') fn_arguments = tuple() return fn_abi, fn_selector, fn_arguments def get_function_info(fn_name, contract_abi=None, fn_abi=None, args=None, kwargs=None): if args is None: args = tuple() if kwargs is None: kwargs = {} if fn_abi is None: fn_abi = find_matching_fn_abi(contract_abi, fn_name, args, kwargs) fn_selector = encode_hex(function_abi_to_4byte_selector(fn_abi)) fn_arguments = merge_args_and_kwargs(fn_abi, args, kwargs) _, fn_arguments = get_abi_inputs(fn_abi, fn_arguments) return fn_abi, fn_selector, fn_arguments def validate_payable(transaction, abi): """Raise ValidationError if non-zero ether is sent to a non payable function. """ if 'value' in transaction: if transaction['value'] != 0: if "payable" in abi and not abi["payable"]: raise ValidationError( "Sending non-zero ether to a contract function " "with payable=False. Please ensure that " "transaction's value is 0." )
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/contracts.py
contracts.py
import math from web3._utils.threads import ( Timeout, ) from web3._utils.toolz import ( assoc, curry, merge, ) VALID_TRANSACTION_PARAMS = [ 'from', 'to', 'gas', 'gasPrice', 'value', 'data', 'nonce', 'chainId', ] TRANSACTION_DEFAULTS = { 'value': 0, 'data': b'', 'gas': lambda web3, tx: web3.eth.estimateGas(tx), 'gasPrice': lambda web3, tx: web3.eth.generateGasPrice(tx) or web3.eth.gasPrice, 'chainId': lambda web3, tx: web3.net.chainId, } @curry def fill_nonce(web3, transaction): if 'from' in transaction and 'nonce' not in transaction: return assoc( transaction, 'nonce', web3.eth.getTransactionCount( transaction['from'], block_identifier='pending')) else: return transaction @curry def fill_transaction_defaults(web3, transaction): """ if web3 is None, fill as much as possible while offline """ defaults = {} for key, default_getter in TRANSACTION_DEFAULTS.items(): if key not in transaction: if callable(default_getter): if web3 is not None: default_val = default_getter(web3, transaction) else: raise ValueError("You must specify %s in the transaction" % key) else: default_val = default_getter defaults[key] = default_val return merge(defaults, transaction) def wait_for_transaction_receipt(web3, txn_hash, timeout=120, poll_latency=0.1): with Timeout(timeout) as _timeout: while True: txn_receipt = web3.eth.getTransactionReceipt(txn_hash) # FIXME: The check for a null `blockHash` is due to parity's # non-standard implementation of the JSON-RPC API and should # be removed once the formal spec for the JSON-RPC endpoints # has been finalized. if txn_receipt is not None and txn_receipt['blockHash'] is not None: break _timeout.sleep(poll_latency) return txn_receipt def get_block_gas_limit(web3, block_identifier=None): if block_identifier is None: block_identifier = web3.eth.blockNumber block = web3.eth.getBlock(block_identifier) return block['gasLimit'] def get_buffered_gas_estimate(web3, transaction, gas_buffer=100000): gas_estimate_transaction = dict(**transaction) gas_estimate = web3.eth.estimateGas(gas_estimate_transaction) gas_limit = get_block_gas_limit(web3) if gas_estimate > gas_limit: raise ValueError( "Contract does not appear to be deployable within the " "current network gas limits. Estimated: {0}. Current gas " "limit: {1}".format(gas_estimate, gas_limit) ) return min(gas_limit, gas_estimate + gas_buffer) def get_required_transaction(web3, transaction_hash): current_transaction = web3.eth.getTransaction(transaction_hash) if not current_transaction: raise ValueError('Supplied transaction with hash {} does not exist' .format(transaction_hash)) return current_transaction def extract_valid_transaction_params(transaction_params): extracted_params = {key: transaction_params[key] for key in VALID_TRANSACTION_PARAMS if key in transaction_params} if extracted_params.get('data') is not None: if transaction_params.get('input') is not None: if extracted_params['data'] != transaction_params['input']: msg = 'failure to handle this transaction due to both "input: {}" and' msg += ' "data: {}" are populated. You need to resolve this conflict.' err_vals = (transaction_params['input'], extracted_params['data']) raise AttributeError(msg.format(*err_vals)) else: return extracted_params else: return extracted_params elif extracted_params.get('data') is None: if transaction_params.get('input') is not None: return assoc(extracted_params, 'data', transaction_params['input']) else: return extracted_params else: raise Exception("Unreachable path: transaction's 'data' is either set or not set") def assert_valid_transaction_params(transaction_params): for param in transaction_params: if param not in VALID_TRANSACTION_PARAMS: raise ValueError('{} is not a valid transaction parameter'.format(param)) def prepare_replacement_transaction(web3, current_transaction, new_transaction): if current_transaction['blockHash'] is not None: raise ValueError('Supplied transaction with hash {} has already been mined' .format(current_transaction['hash'])) if 'nonce' in new_transaction and new_transaction['nonce'] != current_transaction['nonce']: raise ValueError('Supplied nonce in new_transaction must match the pending transaction') if 'nonce' not in new_transaction: new_transaction = assoc(new_transaction, 'nonce', current_transaction['nonce']) if 'gasPrice' in new_transaction: if new_transaction['gasPrice'] <= current_transaction['gasPrice']: raise ValueError('Supplied gas price must exceed existing transaction gas price') else: generated_gas_price = web3.eth.generateGasPrice(new_transaction) minimum_gas_price = int(math.ceil(current_transaction['gasPrice'] * 1.1)) if generated_gas_price and generated_gas_price > minimum_gas_price: new_transaction = assoc(new_transaction, 'gasPrice', generated_gas_price) else: new_transaction = assoc(new_transaction, 'gasPrice', minimum_gas_price) return new_transaction def replace_transaction(web3, current_transaction, new_transaction): new_transaction = prepare_replacement_transaction( web3, current_transaction, new_transaction ) return web3.eth.sendTransaction(new_transaction)
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/transactions.py
transactions.py
class Empty: def __bool__(self): return False def __nonzero__(self): return False empty = Empty()
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/empty.py
empty.py
from collections import ( Iterable, Mapping, ) from eth_utils import ( is_dict, is_list_like, is_string, to_dict, to_list, ) from web3._utils.decorators import ( reject_recursive_repeats, ) from web3._utils.toolz import ( compose, curry, dissoc, ) def hex_to_integer(value): return int(value, 16) integer_to_hex = hex @curry @to_list def apply_formatter_at_index(formatter, at_index, value): if at_index + 1 > len(value): raise IndexError( "Not enough values in iterable to apply formatter. Got: {0}. " "Need: {1}".format(len(value), at_index + 1) ) for index, item in enumerate(value): if index == at_index: yield formatter(item) else: yield item def apply_formatters_to_args(*formatters): return compose(*( apply_formatter_at_index(formatter, index) for index, formatter in enumerate(formatters) )) @curry def apply_formatter_if(condition, formatter, value): if condition(value): return formatter(value) else: return value @curry @to_dict def apply_formatters_to_dict(formatters, value): for key, item in value.items(): if key in formatters: try: yield key, formatters[key](item) except (TypeError, ValueError) as exc: raise type(exc)("Could not format value %r as field %r" % (item, key)) from exc else: yield key, item @curry @to_list def apply_formatter_to_array(formatter, value): for item in value: yield formatter(item) @curry def apply_one_of_formatters(formatter_condition_pairs, value): for formatter, condition in formatter_condition_pairs: if condition(value): return formatter(value) else: raise ValueError("The provided value did not satisfy any of the formatter conditions") def map_collection(func, collection): """ Apply func to each element of a collection, or value of a dictionary. If the value is not a collection, return it unmodified """ datatype = type(collection) if isinstance(collection, Mapping): return datatype((key, func(val)) for key, val in collection.items()) if is_string(collection): return collection elif isinstance(collection, Iterable): return datatype(map(func, collection)) else: return collection @reject_recursive_repeats def recursive_map(func, data): """ Apply func to data, and any collection items inside data (using map_collection). Define func so that it only applies to the type of value that you want it to apply to. """ def recurse(item): return recursive_map(func, item) items_mapped = map_collection(recurse, data) return func(items_mapped) def static_return(value): def inner(*args, **kwargs): return value return inner def static_result(value): def inner(*args, **kwargs): return {'result': value} return inner @curry @to_dict def apply_key_map(key_mappings, value): for key, item in value.items(): if key in key_mappings: yield key_mappings[key], item else: yield key, item def is_array_of_strings(value): if not is_list_like(value): return False return all((is_string(item) for item in value)) def is_array_of_dicts(value): if not is_list_like(value): return False return all((is_dict(item) for item in value)) @curry def remove_key_if(key, remove_if, input_dict): if key in input_dict and remove_if(input_dict): return dissoc(input_dict, key) else: return input_dict
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/formatters.py
formatters.py
from eth_utils import ( is_bytes, is_hex, is_integer, is_string, is_text, remove_0x_prefix, ) def is_predefined_block_number(value): if is_text(value): value_text = value elif is_bytes(value): # `value` could either be random bytes or the utf-8 encoding of # one of the words in: {"latest", "pending", "earliest"} # We cannot decode the bytes as utf8, because random bytes likely won't be valid. # So we speculatively decode as 'latin-1', which cannot fail. value_text = value.decode('latin-1') elif is_integer(value): return False else: raise TypeError("unrecognized block reference: %r" % value) return value_text in {"latest", "pending", "earliest"} def is_hex_encoded_block_hash(value): if not is_string(value): return False return len(remove_0x_prefix(value)) == 64 and is_hex(value) def is_hex_encoded_block_number(value): if not is_string(value): return False elif is_hex_encoded_block_hash(value): return False try: value_as_int = int(value, 16) except ValueError: return False return 0 <= value_as_int < 2**256 def select_method_for_block_identifier(value, if_hash, if_number, if_predefined): if is_predefined_block_number(value): return if_predefined elif isinstance(value, bytes): return if_hash elif is_hex_encoded_block_hash(value): return if_hash elif is_integer(value) and (0 <= value < 2**256): return if_number elif is_hex_encoded_block_number(value): return if_number else: raise ValueError( "Value did not match any of the recognized block identifiers: {0}".format(value) )
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/blocks.py
blocks.py
class FallbackFn: pass
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/function_identifiers.py
function_identifiers.py
from abc import ( ABC, abstractmethod, ) import itertools from eth_abi import ( decode_abi, decode_single, encode_single, ) from eth_utils import ( encode_hex, event_abi_to_log_topic, is_list_like, keccak, to_dict, to_hex, to_tuple, ) import web3 from web3._utils.encoding import ( encode_single_packed, hexstr_if_str, to_bytes, ) from web3._utils.formatters import ( apply_formatter_if, ) from web3._utils.normalizers import ( BASE_RETURN_NORMALIZERS, ) from web3._utils.toolz import ( complement, compose, cons, curry, valfilter, ) from web3.datastructures import ( AttributeDict, ) from web3.exceptions import ( MismatchedABI, ) from .abi import ( exclude_indexed_event_inputs, get_abi_input_names, get_indexed_event_inputs, map_abi_data, normalize_event_input_types, process_type, ) def construct_event_topic_set(event_abi, arguments=None): if arguments is None: arguments = {} if isinstance(arguments, (list, tuple)): if len(arguments) != len(event_abi['inputs']): raise ValueError( "When passing an argument list, the number of arguments must " "match the event constructor." ) arguments = { arg['name']: [arg_value] for arg, arg_value in zip(event_abi['inputs'], arguments) } normalized_args = { key: value if is_list_like(value) else [value] for key, value in arguments.items() } event_topic = encode_hex(event_abi_to_log_topic(event_abi)) indexed_args = get_indexed_event_inputs(event_abi) zipped_abi_and_args = [ (arg, normalized_args.get(arg['name'], [None])) for arg in indexed_args ] encoded_args = [ [ None if option is None else encode_hex(encode_single(arg['type'], option)) for option in arg_options] for arg, arg_options in zipped_abi_and_args ] topics = list(normalize_topic_list([event_topic] + encoded_args)) return topics def construct_event_data_set(event_abi, arguments=None): if arguments is None: arguments = {} if isinstance(arguments, (list, tuple)): if len(arguments) != len(event_abi['inputs']): raise ValueError( "When passing an argument list, the number of arguments must " "match the event constructor." ) arguments = { arg['name']: [arg_value] for arg, arg_value in zip(event_abi['inputs'], arguments) } normalized_args = { key: value if is_list_like(value) else [value] for key, value in arguments.items() } non_indexed_args = exclude_indexed_event_inputs(event_abi) zipped_abi_and_args = [ (arg, normalized_args.get(arg['name'], [None])) for arg in non_indexed_args ] encoded_args = [ [ None if option is None else encode_hex(encode_single(arg['type'], option)) for option in arg_options] for arg, arg_options in zipped_abi_and_args ] data = [ list(permutation) if any(value is not None for value in permutation) else [] for permutation in itertools.product(*encoded_args) ] return data def is_dynamic_sized_type(_type): base_type, type_size, arrlist = process_type(_type) if arrlist: return True elif base_type == 'string': return True elif base_type == 'bytes' and type_size == '': return True return False @to_tuple def get_event_abi_types_for_decoding(event_inputs): """ Event logs use the `sha3(value)` for indexed inputs of type `bytes` or `string`. Because of this we need to modify the types so that we can decode the log entries using the correct types. """ for input_abi in event_inputs: if input_abi['indexed'] and is_dynamic_sized_type(input_abi['type']): yield 'bytes32' else: yield input_abi['type'] @curry def get_event_data(event_abi, log_entry): """ Given an event ABI and a log entry for that event, return the decoded event data """ if event_abi['anonymous']: log_topics = log_entry['topics'] elif not log_entry['topics']: raise MismatchedABI("Expected non-anonymous event to have 1 or more topics") elif event_abi_to_log_topic(event_abi) != log_entry['topics'][0]: raise MismatchedABI("The event signature did not match the provided ABI") else: log_topics = log_entry['topics'][1:] log_topics_abi = get_indexed_event_inputs(event_abi) log_topic_normalized_inputs = normalize_event_input_types(log_topics_abi) log_topic_types = get_event_abi_types_for_decoding(log_topic_normalized_inputs) log_topic_names = get_abi_input_names({'inputs': log_topics_abi}) if len(log_topics) != len(log_topic_types): raise ValueError("Expected {0} log topics. Got {1}".format( len(log_topic_types), len(log_topics), )) log_data = hexstr_if_str(to_bytes, log_entry['data']) log_data_abi = exclude_indexed_event_inputs(event_abi) log_data_normalized_inputs = normalize_event_input_types(log_data_abi) log_data_types = get_event_abi_types_for_decoding(log_data_normalized_inputs) log_data_names = get_abi_input_names({'inputs': log_data_abi}) # sanity check that there are not name intersections between the topic # names and the data argument names. duplicate_names = set(log_topic_names).intersection(log_data_names) if duplicate_names: raise ValueError( "Invalid Event ABI: The following argument names are duplicated " "between event inputs: '{0}'".format(', '.join(duplicate_names)) ) decoded_log_data = decode_abi(log_data_types, log_data) normalized_log_data = map_abi_data( BASE_RETURN_NORMALIZERS, log_data_types, decoded_log_data ) decoded_topic_data = [ decode_single(topic_type, topic_data) for topic_type, topic_data in zip(log_topic_types, log_topics) ] normalized_topic_data = map_abi_data( BASE_RETURN_NORMALIZERS, log_topic_types, decoded_topic_data ) event_args = dict(itertools.chain( zip(log_topic_names, normalized_topic_data), zip(log_data_names, normalized_log_data), )) event_data = { 'args': event_args, 'event': event_abi['name'], 'logIndex': log_entry['logIndex'], 'transactionIndex': log_entry['transactionIndex'], 'transactionHash': log_entry['transactionHash'], 'address': log_entry['address'], 'blockHash': log_entry['blockHash'], 'blockNumber': log_entry['blockNumber'], } return AttributeDict.recursive(event_data) @to_tuple def pop_singlets(seq): yield from (i[0] if is_list_like(i) and len(i) == 1 else i for i in seq) @curry def remove_trailing_from_seq(seq, remove_value=None): index = len(seq) while index > 0 and seq[index - 1] == remove_value: index -= 1 return seq[:index] normalize_topic_list = compose( remove_trailing_from_seq(remove_value=None), pop_singlets,) def is_indexed(arg): if isinstance(arg, TopicArgumentFilter) is True: return True return False is_not_indexed = complement(is_indexed) class EventFilterBuilder: formatter = None _fromBlock = None _toBlock = None _address = None _immutable = False def __init__(self, event_abi, formatter=None): self.event_abi = event_abi self.formatter = formatter self.event_topic = initialize_event_topics(self.event_abi) self.args = AttributeDict( _build_argument_filters_from_event_abi(event_abi)) self._ordered_arg_names = tuple(arg['name'] for arg in event_abi['inputs']) @property def fromBlock(self): return self._fromBlock @fromBlock.setter def fromBlock(self, value): if self._fromBlock is None and not self._immutable: self._fromBlock = value else: raise ValueError( "fromBlock is already set to {0}. " "Resetting filter parameters is not permitted".format(self._fromBlock)) @property def toBlock(self): return self._toBlock @toBlock.setter def toBlock(self, value): if self._toBlock is None and not self._immutable: self._toBlock = value else: raise ValueError( "toBlock is already set to {0}. " "Resetting filter parameters is not permitted".format(self._toBlock)) @property def address(self): return self._address @address.setter def address(self, value): if self._address is None and not self._immutable: self._address = value else: raise ValueError( "address is already set to {0}. " "Resetting filter parameters is not permitted".format(self.address)) @property def ordered_args(self): return tuple(map(self.args.__getitem__, self._ordered_arg_names)) @property @to_tuple def indexed_args(self): return tuple(filter(is_indexed, self.ordered_args)) @property @to_tuple def data_args(self): return tuple(filter(is_not_indexed, self.ordered_args)) @property def topics(self): arg_topics = tuple(arg.match_values for arg in self.indexed_args) return normalize_topic_list(cons(to_hex(self.event_topic), arg_topics)) @property def data_argument_values(self): if self.data_args is not None: return tuple(arg.match_values for arg in self.data_args) else: return (None,) @property def filter_params(self): params = { "topics": self.topics, "fromBlock": self.fromBlock, "toBlock": self.toBlock, "address": self.address } return valfilter(lambda x: x is not None, params) def deploy(self, w3): if not isinstance(w3, web3.Web3): raise ValueError("Invalid web3 argument: got: {0}".format(repr(w3))) for arg in self.args.values(): arg._immutable = True self._immutable = True log_filter = w3.eth.filter(self.filter_params) log_filter.filter_params = self.filter_params log_filter.set_data_filters(self.data_argument_values) log_filter.builder = self if self.formatter is not None: log_filter.log_entry_formatter = self.formatter return log_filter def initialize_event_topics(event_abi): if event_abi['anonymous'] is False: return event_abi_to_log_topic(event_abi) else: return list() @to_dict def _build_argument_filters_from_event_abi(event_abi): for item in event_abi['inputs']: key = item['name'] if item['indexed'] is True: value = TopicArgumentFilter(arg_type=item['type']) else: value = DataArgumentFilter(arg_type=item['type']) yield key, value array_to_tuple = apply_formatter_if(is_list_like, tuple) @to_tuple def _normalize_match_values(match_values): for value in match_values: yield array_to_tuple(value) class BaseArgumentFilter(ABC): _match_values = None _immutable = False def __init__(self, arg_type): self.arg_type = arg_type def match_single(self, value): if self._immutable: raise ValueError("Setting values is forbidden after filter is deployed.") if self._match_values is None: self._match_values = _normalize_match_values((value,)) else: raise ValueError("An argument match value/s has already been set.") def match_any(self, *values): if self._immutable: raise ValueError("Setting values is forbidden after filter is deployed.") if self._match_values is None: self._match_values = _normalize_match_values(values) else: raise ValueError("An argument match value/s has already been set.") @property @abstractmethod def match_values(self): pass class DataArgumentFilter(BaseArgumentFilter): @property def match_values(self): return (self.arg_type, self._match_values) class TopicArgumentFilter(BaseArgumentFilter): @to_tuple def _get_match_values(self): yield from (self._encode(value) for value in self._match_values) @property def match_values(self): if self._match_values is not None: return self._get_match_values() else: return None def _encode(self, value): if is_dynamic_sized_type(self.arg_type): return to_hex(keccak(encode_single_packed(self.arg_type, value))) else: return to_hex(encode_single(self.arg_type, value))
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/events.py
events.py
import web3._utils.formatters from web3._utils.toolz import ( concat, ) def verify_attr(class_name, key, namespace): if key not in namespace: raise AttributeError( "Property {0} not found on {1} class. " "`{1}.factory` only accepts keyword arguments which are " "present on the {1} class".format(key, class_name) ) class PropertyCheckingFactory(type): def __init__(cls, name, bases, namespace, **kargs): # see PEP487. To accept kwargs in __new__, they need to be # filtered out here. super().__init__(name, bases, namespace) def __new__(mcs, name, bases, namespace, normalizers=None): all_bases = set(concat(base.__mro__ for base in bases)) all_keys = set(concat(base.__dict__.keys() for base in all_bases)) for key in namespace: verify_attr(name, key, all_keys) if normalizers: processed_namespace = web3._utils.formatters.apply_formatters_to_dict( normalizers, namespace, ) else: processed_namespace = namespace return super().__new__(mcs, name, bases, processed_namespace)
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/datatypes.py
datatypes.py
import binascii from collections import ( namedtuple, ) import itertools import re from eth_abi import ( decoding, encoding, ) from eth_abi.codec import ( ABICodec, ) from eth_abi.grammar import ( parse as parse_type_string, ) from eth_abi.registry import ( BaseEquals, registry as default_registry, ) from eth_utils import ( decode_hex, is_bytes, is_list_like, is_text, to_text, to_tuple, ) from eth_utils.abi import ( collapse_if_tuple, ) from web3._utils.ens import ( is_ens_name, ) from web3._utils.formatters import ( recursive_map, ) from web3._utils.toolz import ( curry, partial, pipe, ) from web3.exceptions import ( FallbackNotFound, ) def filter_by_type(_type, contract_abi): return [abi for abi in contract_abi if abi['type'] == _type] def filter_by_name(name, contract_abi): return [ abi for abi in contract_abi if ( abi['type'] not in ('fallback', 'constructor') and abi['name'] == name ) ] def get_abi_input_types(abi): if 'inputs' not in abi and abi['type'] == 'fallback': return [] else: return [collapse_if_tuple(abi_input) for abi_input in abi['inputs']] def get_abi_output_types(abi): if abi['type'] == 'fallback': return [] else: return [collapse_if_tuple(arg) for arg in abi['outputs']] def get_abi_input_names(abi): if 'inputs' not in abi and abi['type'] == 'fallback': return [] else: return [arg['name'] for arg in abi['inputs']] def get_fallback_func_abi(contract_abi): fallback_abis = filter_by_type('fallback', contract_abi) if fallback_abis: return fallback_abis[0] else: raise FallbackNotFound("No fallback function was found in the contract ABI.") def fallback_func_abi_exists(contract_abi): return filter_by_type('fallback', contract_abi) def get_indexed_event_inputs(event_abi): return [arg for arg in event_abi['inputs'] if arg['indexed'] is True] def exclude_indexed_event_inputs(event_abi): return [arg for arg in event_abi['inputs'] if arg['indexed'] is False] def filter_by_argument_count(num_arguments, contract_abi): return [ abi for abi in contract_abi if len(abi['inputs']) == num_arguments ] def filter_by_argument_name(argument_names, contract_abi): return [ abi for abi in contract_abi if set(argument_names).intersection( get_abi_input_names(abi) ) == set(argument_names) ] try: from eth_abi.abi import ( process_type, collapse_type, ) except ImportError: from eth_abi.grammar import ( normalize as normalize_type_string, ) def process_type(type_str): normalized_type_str = normalize_type_string(type_str) abi_type = parse_type_string(normalized_type_str) abi_type.validate() if hasattr(abi_type, 'base'): base = abi_type.base else: base = str(abi_type.item_type) if hasattr(abi_type, 'sub'): sub = abi_type.sub else: sub = None if isinstance(sub, tuple): sub = 'x'.join(map(str, sub)) elif isinstance(sub, int): sub = str(sub) else: sub = '' arrlist = abi_type.arrlist if isinstance(arrlist, tuple): arrlist = list(map(list, arrlist)) else: arrlist = [] return base, sub, arrlist def collapse_type(base, sub, arrlist): return base + str(sub) + ''.join(map(repr, arrlist)) class AddressEncoder(encoding.AddressEncoder): @classmethod def validate_value(cls, value): if is_ens_name(value): return super().validate_value(value) class AcceptsHexStrMixin: def validate_value(self, value): if is_text(value): try: value = decode_hex(value) except binascii.Error: self.invalidate_value( value, msg='invalid hex string', ) super().validate_value(value) class BytesEncoder(AcceptsHexStrMixin, encoding.BytesEncoder): pass class ByteStringEncoder(AcceptsHexStrMixin, encoding.ByteStringEncoder): pass class TextStringEncoder(encoding.TextStringEncoder): @classmethod def validate_value(cls, value): if is_bytes(value): try: value = to_text(value) except UnicodeDecodeError: cls.invalidate_value( value, msg='not decodable as unicode string', ) super().validate_value(value) # We make a copy here just to make sure that eth-abi's default registry is not # affected by our custom encoder subclasses registry = default_registry.copy() registry.unregister('address') registry.unregister('bytes<M>') registry.unregister('bytes') registry.unregister('string') registry.register( BaseEquals('address'), AddressEncoder, decoding.AddressDecoder, label='address', ) registry.register( BaseEquals('bytes', with_sub=True), BytesEncoder, decoding.BytesDecoder, label='bytes<M>', ) registry.register( BaseEquals('bytes', with_sub=False), ByteStringEncoder, decoding.ByteStringDecoder, label='bytes', ) registry.register( BaseEquals('string'), TextStringEncoder, decoding.StringDecoder, label='string', ) codec = ABICodec(registry) is_encodable = codec.is_encodable def filter_by_encodability(args, kwargs, contract_abi): return [ function_abi for function_abi in contract_abi if check_if_arguments_can_be_encoded(function_abi, args, kwargs) ] def get_abi_inputs(function_abi, arg_values): """Similar to get_abi_input_types(), but gets values too. Returns a zip of types and their corresponding argument values. Importantly, looks in `function_abi` for tuples, and for any found, (a) translates them from the ABI dict representation to the parenthesized type list representation that's expected by eth_abi, and (b) translates their corresponding arguments values from the python dict representation to the tuple representation expected by eth_abi. >>> get_abi_inputs( ... { ... 'inputs': [ ... { ... 'components': [ ... {'name': 'anAddress', 'type': 'address'}, ... {'name': 'anInt', 'type': 'uint256'}, ... {'name': 'someBytes', 'type': 'bytes'} ... ], ... 'name': 'arg', ... 'type': 'tuple' ... } ... ], ... 'type': 'function' ... }, ... ( ... { ... 'anInt': 12345, ... 'anAddress': '0x0000000000000000000000000000000000000000', ... 'someBytes': b'0000', ... }, ... ), ... ) (['(address,uint256,bytes)'], (('0x0000000000000000000000000000000000000000', 12345, b'0000'),)) """ if "inputs" not in function_abi: return ([], ()) def collate_tuple_components(components, values): """Collates tuple components with their values. :param components: is an array of ABI components, such as one extracted from an input element of a function ABI. :param values: can be any of a list, tuple, or dict. If a dict, key names must correspond to component names specified in the components parameter. If a list or array, the order of the elements should correspond to the order of elements in the components array. Returns a two-element tuple. The first element is a string comprised of the parenthesized list of tuple component types. The second element is a tuple of the values corresponding to the types in the first element. >>> collate_tuple_components( ... [ ... {'name': 'anAddress', 'type': 'address'}, ... {'name': 'anInt', 'type': 'uint256'}, ... {'name': 'someBytes', 'type': 'bytes'} ... ], ... ( ... { ... 'anInt': 12345, ... 'anAddress': '0x0000000000000000000000000000000000000000', ... 'someBytes': b'0000', ... }, ... ), ... ) """ component_types = [] component_values = [] for component, value in zip(components, values): component_types.append(component["type"]) if isinstance(values, dict): component_values.append(values[component["name"]]) elif is_list_like(values): component_values.append(value) else: raise TypeError( "Unknown value type {} for ABI type 'tuple'" .format(type(values)) ) return component_types, component_values types = [] values = tuple() for abi_input, arg_value in zip(function_abi["inputs"], arg_values): if abi_input["type"] == "tuple[]": value_array = [] for arg_arr_elem_val in arg_value: component_types, component_values = collate_tuple_components( abi_input["components"], arg_arr_elem_val ) value_array.append(component_values) types.append("(" + ",".join(component_types) + ")[]") values += (value_array,) elif abi_input["type"] == "tuple": component_types, component_values = collate_tuple_components( abi_input["components"], arg_value ) types.append("(" + ",".join(component_types) + ")") values += (tuple(component_values),) else: types.append(abi_input["type"]) values += (arg_value,) return types, values def check_if_arguments_can_be_encoded(function_abi, args, kwargs): try: arguments = merge_args_and_kwargs(function_abi, args, kwargs) except TypeError: return False if len(function_abi.get('inputs', [])) != len(arguments): return False types, arguments = get_abi_inputs(function_abi, arguments) return all( is_encodable(_type, arg) for _type, arg in zip(types, arguments) ) def merge_args_and_kwargs(function_abi, args, kwargs): """ Takes a list of positional args (``args``) and a dict of keyword args (``kwargs``) defining values to be passed to a call to the contract function described by ``function_abi``. Checks to ensure that the correct number of args were given, no duplicate args were given, and no unknown args were given. Returns a list of argument values aligned to the order of inputs defined in ``function_abi``. """ # Ensure the function is being applied to the correct number of args if len(args) + len(kwargs) != len(function_abi.get('inputs', [])): raise TypeError( "Incorrect argument count. Expected '{0}'. Got '{1}'".format( len(function_abi['inputs']), len(args) + len(kwargs), ) ) # If no keyword args were given, we don't need to align them if not kwargs: return args kwarg_names = set(kwargs.keys()) sorted_arg_names = tuple(arg_abi['name'] for arg_abi in function_abi['inputs']) args_as_kwargs = dict(zip(sorted_arg_names, args)) # Check for duplicate args duplicate_args = kwarg_names.intersection(args_as_kwargs.keys()) if duplicate_args: raise TypeError( "{fn_name}() got multiple values for argument(s) '{dups}'".format( fn_name=function_abi['name'], dups=', '.join(duplicate_args), ) ) # Check for unknown args unknown_args = kwarg_names.difference(sorted_arg_names) if unknown_args: if function_abi.get('name'): raise TypeError( "{fn_name}() got unexpected keyword argument(s) '{dups}'".format( fn_name=function_abi.get('name'), dups=', '.join(unknown_args), ) ) raise TypeError( "Type: '{_type}' got unexpected keyword argument(s) '{dups}'".format( _type=function_abi.get('type'), dups=', '.join(unknown_args), ) ) # Sort args according to their position in the ABI and unzip them from their # names sorted_args = tuple(zip( *sorted( itertools.chain(kwargs.items(), args_as_kwargs.items()), key=lambda kv: sorted_arg_names.index(kv[0]), ) )) if sorted_args: return sorted_args[1] else: return tuple() def get_constructor_abi(contract_abi): candidates = [ abi for abi in contract_abi if abi['type'] == 'constructor' ] if len(candidates) == 1: return candidates[0] elif len(candidates) == 0: return None elif len(candidates) > 1: raise ValueError("Found multiple constructors.") DYNAMIC_TYPES = ['bytes', 'string'] INT_SIZES = range(8, 257, 8) BYTES_SIZES = range(1, 33) UINT_TYPES = ['uint{0}'.format(i) for i in INT_SIZES] INT_TYPES = ['int{0}'.format(i) for i in INT_SIZES] BYTES_TYPES = ['bytes{0}'.format(i) for i in BYTES_SIZES] + ['bytes32.byte'] STATIC_TYPES = list(itertools.chain( ['address', 'bool'], UINT_TYPES, INT_TYPES, BYTES_TYPES, )) BASE_TYPE_REGEX = '|'.join(( _type + '(?![a-z0-9])' for _type in itertools.chain(STATIC_TYPES, DYNAMIC_TYPES) )) SUB_TYPE_REGEX = ( r'\[' '[0-9]*' r'\]' ) TYPE_REGEX = ( '^' '(?:{base_type})' '(?:(?:{sub_type})*)?' '$' ).format( base_type=BASE_TYPE_REGEX, sub_type=SUB_TYPE_REGEX, ) def is_recognized_type(abi_type): return bool(re.match(TYPE_REGEX, abi_type)) def is_bool_type(abi_type): return abi_type == 'bool' def is_uint_type(abi_type): return abi_type in UINT_TYPES def is_int_type(abi_type): return abi_type in INT_TYPES def is_address_type(abi_type): return abi_type == 'address' def is_bytes_type(abi_type): return abi_type in BYTES_TYPES + ['bytes'] def is_string_type(abi_type): return abi_type == 'string' @curry def is_length(target_length, value): return len(value) == target_length def size_of_type(abi_type): """ Returns size in bits of abi_type """ if 'string' in abi_type: return None if 'byte' in abi_type: return None if '[' in abi_type: return None if abi_type == 'bool': return 8 if abi_type == 'address': return 160 return int(re.sub(r"\D", "", abi_type)) END_BRACKETS_OF_ARRAY_TYPE_REGEX = r"\[[^]]*\]$" def sub_type_of_array_type(abi_type): if not is_array_type(abi_type): raise ValueError( "Cannot parse subtype of nonarray abi-type: {0}".format(abi_type) ) return re.sub(END_BRACKETS_OF_ARRAY_TYPE_REGEX, '', abi_type, 1) def length_of_array_type(abi_type): if not is_array_type(abi_type): raise ValueError( "Cannot parse length of nonarray abi-type: {0}".format(abi_type) ) inner_brackets = re.search(END_BRACKETS_OF_ARRAY_TYPE_REGEX, abi_type).group(0).strip("[]") if not inner_brackets: return None else: return int(inner_brackets) ARRAY_REGEX = ( "^" "[a-zA-Z0-9_]+" "({sub_type})+" "$" ).format(sub_type=SUB_TYPE_REGEX) def is_array_type(abi_type): return bool(re.match(ARRAY_REGEX, abi_type)) NAME_REGEX = ( '[a-zA-Z_]' '[a-zA-Z0-9_]*' ) ENUM_REGEX = ( '^' '{lib_name}' r'\.' '{enum_name}' '$' ).format(lib_name=NAME_REGEX, enum_name=NAME_REGEX) def is_probably_enum(abi_type): return bool(re.match(ENUM_REGEX, abi_type)) @to_tuple def normalize_event_input_types(abi_args): for arg in abi_args: if is_recognized_type(arg['type']): yield arg elif is_probably_enum(arg['type']): yield {k: 'uint8' if k == 'type' else v for k, v in arg.items()} else: yield arg def abi_to_signature(abi): function_signature = "{fn_name}({fn_input_types})".format( fn_name=abi['name'], fn_input_types=','.join([ arg['type'] for arg in normalize_event_input_types(abi.get('inputs', [])) ]), ) return function_signature ######################################################## # # Conditionally modifying data, tagged with ABI Types # ######################################################## @curry def map_abi_data(normalizers, types, data): """ This function will apply normalizers to your data, in the context of the relevant types. Each normalizer is in the format: def normalizer(datatype, data): # Conditionally modify data return (datatype, data) Where datatype is a valid ABI type string, like "uint". In case of an array, like "bool[2]", normalizer will receive `data` as an iterable of typed data, like `[("bool", True), ("bool", False)]`. Internals --- This is accomplished by: 1. Decorating the data tree with types 2. Recursively mapping each of the normalizers to the data 3. Stripping the types back out of the tree """ pipeline = itertools.chain( [abi_data_tree(types)], map(data_tree_map, normalizers), [partial(recursive_map, strip_abi_type)], ) return pipe(data, *pipeline) @curry def abi_data_tree(types, data): """ Decorate the data tree with pairs of (type, data). The pair tuple is actually an ABITypedData, but can be accessed as a tuple. As an example: >>> abi_data_tree(types=["bool[2]", "uint"], data=[[True, False], 0]) [ABITypedData(abi_type='bool[2]', data=[ABITypedData(abi_type='bool', data=True), ABITypedData(abi_type='bool', data=False)]), ABITypedData(abi_type='uint256', data=0)] """ # noqa: E501 (line too long) return [ abi_sub_tree(data_type, data_value) for data_type, data_value in zip(types, data) ] @curry def data_tree_map(func, data_tree): """ Map func to every ABITypedData element in the tree. func will receive two args: abi_type, and data """ def map_to_typed_data(elements): if ( isinstance(elements, ABITypedData) and elements.abi_type is not None and not ( isinstance(elements.abi_type, str) and elements.abi_type[0] == "(" ) ): return ABITypedData(func(*elements)) else: return elements return recursive_map(map_to_typed_data, data_tree) class ABITypedData(namedtuple('ABITypedData', 'abi_type, data')): """ This class marks data as having a certain ABI-type. >>> addr1 = "0x" + "0" * 20 >>> addr2 = "0x" + "f" * 20 >>> a1 = ABITypedData(['address', addr1]) >>> a2 = ABITypedData(['address', addr2]) >>> addrs = ABITypedData(['address[]', [a1, a2]]) You can access the fields using tuple() interface, or with attributes: >>> assert a1.abi_type == a1[0] >>> assert a1.data == a1[1] Unlike a typical `namedtuple`, you initialize with a single positional argument that is iterable, to match the init interface of all other relevant collections. """ def __new__(cls, iterable): return super().__new__(cls, *iterable) def abi_sub_tree(data_type, data_value): if ( isinstance(data_type, str) and data_type[0] == "(" and isinstance(data_value, tuple) ): return ABITypedData([data_type, data_value]) if data_type is None: return ABITypedData([None, data_value]) try: base, sub, arrlist = data_type except ValueError: base, sub, arrlist = process_type(data_type) collapsed = collapse_type(base, sub, arrlist) if arrlist: sub_type = (base, sub, arrlist[:-1]) return ABITypedData([ collapsed, [ abi_sub_tree(sub_type, sub_value) for sub_value in data_value ], ]) else: return ABITypedData([collapsed, data_value]) def strip_abi_type(elements): if isinstance(elements, ABITypedData): return elements.data else: return elements
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/abi.py
abi.py
import lru import requests from web3._utils.caching import ( generate_cache_key, ) def _remove_session(key, session): session.close() _session_cache = lru.LRU(8, callback=_remove_session) def _get_session(*args, **kwargs): cache_key = generate_cache_key((args, kwargs)) if cache_key not in _session_cache: _session_cache[cache_key] = requests.Session() return _session_cache[cache_key] def make_post_request(endpoint_uri, data, *args, **kwargs): kwargs.setdefault('timeout', 10) session = _get_session(endpoint_uri) response = session.post(endpoint_uri, data=data, *args, **kwargs) response.raise_for_status() return response.content
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/request.py
request.py
import sys import pywintypes # noqa: E402 import win32file # noqa: E402 if sys.platform != 'win32': raise ImportError("This module should not be imported on non `win32` platforms") class NamedPipe: def __init__(self, ipc_path): try: self.handle = win32file.CreateFile( ipc_path, win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, None) except pywintypes.error as err: raise IOError(err) def recv(self, max_length): (err, data) = win32file.ReadFile(self.handle, max_length) if err: raise IOError(err) return data def sendall(self, data): return win32file.WriteFile(self.handle, data) def close(self): self.handle.close()
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/windows.py
windows.py
try: from cytoolz import ( assoc, complement, compose, concat, cons, curry, dicttoolz, dissoc, excepts, functoolz, groupby, identity, itertoolz, merge, partial, pipe, sliding_window, valfilter, valmap, ) except ImportError: from toolz import ( # noqa: F401 assoc, complement, compose, concat, cons, curry, dicttoolz, dissoc, excepts, functoolz, groupby, identity, itertoolz, merge, partial, pipe, sliding_window, valfilter, valmap, )
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/toolz/__init__.py
__init__.py
try: from cytoolz.curried import ( keymap, valmap, ) except ImportError: from toolz.curried import ( # noqa: F401 keymap, valmap, )
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/toolz/curried.py
curried.py
# -*- coding: utf-8 -*- import pytest from eth_abi import ( decode_single, ) from eth_utils import ( is_boolean, is_bytes, is_checksum_address, is_dict, is_integer, is_list_like, is_same_address, is_string, ) from hexbytes import ( HexBytes, ) from web3.exceptions import ( InvalidAddress, ) UNKNOWN_ADDRESS = '0xdEADBEeF00000000000000000000000000000000' UNKNOWN_HASH = '0xdeadbeef00000000000000000000000000000000000000000000000000000000' class EthModuleTest: def test_eth_protocolVersion(self, web3): protocol_version = web3.version.ethereum assert is_string(protocol_version) assert protocol_version.isdigit() def test_eth_syncing(self, web3): syncing = web3.eth.syncing assert is_boolean(syncing) or is_dict(syncing) if is_boolean(syncing): assert syncing is False elif is_dict(syncing): assert 'startingBlock' in syncing assert 'currentBlock' in syncing assert 'highestBlock' in syncing assert is_integer(syncing['startingBlock']) assert is_integer(syncing['currentBlock']) assert is_integer(syncing['highestBlock']) def test_eth_coinbase(self, web3): coinbase = web3.eth.coinbase assert is_checksum_address(coinbase) def test_eth_mining(self, web3): mining = web3.eth.mining assert is_boolean(mining) def test_eth_hashrate(self, web3): hashrate = web3.eth.hashrate assert is_integer(hashrate) assert hashrate >= 0 def test_eth_gasPrice(self, web3): gas_price = web3.eth.gasPrice assert is_integer(gas_price) assert gas_price > 0 def test_eth_accounts(self, web3): accounts = web3.eth.accounts assert is_list_like(accounts) assert len(accounts) != 0 assert all(( is_checksum_address(account) for account in accounts )) assert web3.eth.coinbase in accounts def test_eth_blockNumber(self, web3): block_number = web3.eth.blockNumber assert is_integer(block_number) assert block_number >= 0 def test_eth_getBalance(self, web3): coinbase = web3.eth.coinbase with pytest.raises(InvalidAddress): web3.eth.getBalance(coinbase.lower()) balance = web3.eth.getBalance(coinbase) assert is_integer(balance) assert balance >= 0 def test_eth_getStorageAt(self, web3, emitter_contract_address): storage = web3.eth.getStorageAt(emitter_contract_address, 0) assert isinstance(storage, HexBytes) def test_eth_getStorageAt_invalid_address(self, web3): coinbase = web3.eth.coinbase with pytest.raises(InvalidAddress): web3.eth.getStorageAt(coinbase.lower(), 0) def test_eth_getTransactionCount(self, web3, unlocked_account_dual_type): transaction_count = web3.eth.getTransactionCount(unlocked_account_dual_type) assert is_integer(transaction_count) assert transaction_count >= 0 def test_eth_getTransactionCount_invalid_address(self, web3): coinbase = web3.eth.coinbase with pytest.raises(InvalidAddress): web3.eth.getTransactionCount(coinbase.lower()) def test_eth_getBlockTransactionCountByHash_empty_block(self, web3, empty_block): transaction_count = web3.eth.getBlockTransactionCount(empty_block['hash']) assert is_integer(transaction_count) assert transaction_count == 0 def test_eth_getBlockTransactionCountByNumber_empty_block(self, web3, empty_block): transaction_count = web3.eth.getBlockTransactionCount(empty_block['number']) assert is_integer(transaction_count) assert transaction_count == 0 def test_eth_getBlockTransactionCountByHash_block_with_txn(self, web3, block_with_txn): transaction_count = web3.eth.getBlockTransactionCount(block_with_txn['hash']) assert is_integer(transaction_count) assert transaction_count >= 1 def test_eth_getBlockTransactionCountByNumber_block_with_txn(self, web3, block_with_txn): transaction_count = web3.eth.getBlockTransactionCount(block_with_txn['number']) assert is_integer(transaction_count) assert transaction_count >= 1 def test_eth_getUncleCountByBlockHash(self, web3, empty_block): uncle_count = web3.eth.getUncleCount(empty_block['hash']) assert is_integer(uncle_count) assert uncle_count == 0 def test_eth_getUncleCountByBlockNumber(self, web3, empty_block): uncle_count = web3.eth.getUncleCount(empty_block['number']) assert is_integer(uncle_count) assert uncle_count == 0 def test_eth_getCode(self, web3, math_contract_address): code = web3.eth.getCode(math_contract_address) assert isinstance(code, HexBytes) assert len(code) > 0 def test_eth_getCode_invalid_address(self, web3, math_contract): with pytest.raises(InvalidAddress): web3.eth.getCode(math_contract.address.lower()) def test_eth_getCode_with_block_identifier(self, web3, emitter_contract): code = web3.eth.getCode(emitter_contract.address, block_identifier=web3.eth.blockNumber) assert isinstance(code, HexBytes) assert len(code) > 0 def test_eth_sign(self, web3, unlocked_account_dual_type): signature = web3.eth.sign( unlocked_account_dual_type, text='Message tö sign. Longer than hash!' ) assert is_bytes(signature) assert len(signature) == 32 + 32 + 1 # test other formats hexsign = web3.eth.sign( unlocked_account_dual_type, hexstr='0x4d6573736167652074c3b6207369676e2e204c6f6e676572207468616e206861736821' ) assert hexsign == signature intsign = web3.eth.sign( unlocked_account_dual_type, 0x4d6573736167652074c3b6207369676e2e204c6f6e676572207468616e206861736821 ) assert intsign == signature bytessign = web3.eth.sign( unlocked_account_dual_type, b'Message t\xc3\xb6 sign. Longer than hash!' ) assert bytessign == signature new_signature = web3.eth.sign( unlocked_account_dual_type, text='different message is different' ) assert new_signature != signature def test_eth_sendTransaction_addr_checksum_required(self, web3, unlocked_account): non_checksum_addr = unlocked_account.lower() txn_params = { 'from': unlocked_account, 'to': unlocked_account, 'value': 1, 'gas': 21000, 'gasPrice': web3.eth.gasPrice, } with pytest.raises(InvalidAddress): invalid_params = dict(txn_params, **{'from': non_checksum_addr}) web3.eth.sendTransaction(invalid_params) with pytest.raises(InvalidAddress): invalid_params = dict(txn_params, **{'to': non_checksum_addr}) web3.eth.sendTransaction(invalid_params) def test_eth_sendTransaction(self, web3, unlocked_account_dual_type): txn_params = { 'from': unlocked_account_dual_type, 'to': unlocked_account_dual_type, 'value': 1, 'gas': 21000, 'gasPrice': web3.eth.gasPrice, } txn_hash = web3.eth.sendTransaction(txn_params) txn = web3.eth.getTransaction(txn_hash) assert is_same_address(txn['from'], txn_params['from']) assert is_same_address(txn['to'], txn_params['to']) assert txn['value'] == 1 assert txn['gas'] == 21000 assert txn['gasPrice'] == txn_params['gasPrice'] def test_eth_sendTransaction_with_nonce(self, web3, unlocked_account): txn_params = { 'from': unlocked_account, 'to': unlocked_account, 'value': 1, 'gas': 21000, # Increased gas price to ensure transaction hash different from other tests 'gasPrice': web3.eth.gasPrice * 2, 'nonce': web3.eth.getTransactionCount(unlocked_account), } txn_hash = web3.eth.sendTransaction(txn_params) txn = web3.eth.getTransaction(txn_hash) assert is_same_address(txn['from'], txn_params['from']) assert is_same_address(txn['to'], txn_params['to']) assert txn['value'] == 1 assert txn['gas'] == 21000 assert txn['gasPrice'] == txn_params['gasPrice'] assert txn['nonce'] == txn_params['nonce'] def test_eth_replaceTransaction(self, web3, unlocked_account_dual_type): txn_params = { 'from': unlocked_account_dual_type, 'to': unlocked_account_dual_type, 'value': 1, 'gas': 21000, 'gasPrice': web3.eth.gasPrice, } txn_hash = web3.eth.sendTransaction(txn_params) txn_params['gasPrice'] = web3.eth.gasPrice * 2 replace_txn_hash = web3.eth.replaceTransaction(txn_hash, txn_params) replace_txn = web3.eth.getTransaction(replace_txn_hash) assert is_same_address(replace_txn['from'], txn_params['from']) assert is_same_address(replace_txn['to'], txn_params['to']) assert replace_txn['value'] == 1 assert replace_txn['gas'] == 21000 assert replace_txn['gasPrice'] == txn_params['gasPrice'] def test_eth_replaceTransaction_non_existing_transaction( self, web3, unlocked_account_dual_type): txn_params = { 'from': unlocked_account_dual_type, 'to': unlocked_account_dual_type, 'value': 1, 'gas': 21000, 'gasPrice': web3.eth.gasPrice, } with pytest.raises(ValueError): web3.eth.replaceTransaction( '0x98e8cc09b311583c5079fa600f6c2a3bea8611af168c52e4b60b5b243a441997', txn_params ) # auto mine is enabled for this test def test_eth_replaceTransaction_already_mined(self, web3, unlocked_account_dual_type): txn_params = { 'from': unlocked_account_dual_type, 'to': unlocked_account_dual_type, 'value': 1, 'gas': 21000, 'gasPrice': web3.eth.gasPrice, } txn_hash = web3.eth.sendTransaction(txn_params) txn_params['gasPrice'] = web3.eth.gasPrice * 2 with pytest.raises(ValueError): web3.eth.replaceTransaction(txn_hash, txn_params) def test_eth_replaceTransaction_incorrect_nonce(self, web3, unlocked_account): txn_params = { 'from': unlocked_account, 'to': unlocked_account, 'value': 1, 'gas': 21000, 'gasPrice': web3.eth.gasPrice, } txn_hash = web3.eth.sendTransaction(txn_params) txn = web3.eth.getTransaction(txn_hash) txn_params['gasPrice'] = web3.eth.gasPrice * 2 txn_params['nonce'] = txn['nonce'] + 1 with pytest.raises(ValueError): web3.eth.replaceTransaction(txn_hash, txn_params) def test_eth_replaceTransaction_gas_price_too_low(self, web3, unlocked_account_dual_type): txn_params = { 'from': unlocked_account_dual_type, 'to': unlocked_account_dual_type, 'value': 1, 'gas': 21000, 'gasPrice': 10, } txn_hash = web3.eth.sendTransaction(txn_params) txn_params['gasPrice'] = 9 with pytest.raises(ValueError): web3.eth.replaceTransaction(txn_hash, txn_params) def test_eth_replaceTransaction_gas_price_defaulting_minimum(self, web3, unlocked_account): txn_params = { 'from': unlocked_account, 'to': unlocked_account, 'value': 1, 'gas': 21000, 'gasPrice': 10, } txn_hash = web3.eth.sendTransaction(txn_params) txn_params.pop('gasPrice') replace_txn_hash = web3.eth.replaceTransaction(txn_hash, txn_params) replace_txn = web3.eth.getTransaction(replace_txn_hash) assert replace_txn['gasPrice'] == 11 # minimum gas price def test_eth_replaceTransaction_gas_price_defaulting_strategy_higher(self, web3, unlocked_account): txn_params = { 'from': unlocked_account, 'to': unlocked_account, 'value': 1, 'gas': 21000, 'gasPrice': 10, } txn_hash = web3.eth.sendTransaction(txn_params) def higher_gas_price_strategy(web3, txn): return 20 web3.eth.setGasPriceStrategy(higher_gas_price_strategy) txn_params.pop('gasPrice') replace_txn_hash = web3.eth.replaceTransaction(txn_hash, txn_params) replace_txn = web3.eth.getTransaction(replace_txn_hash) assert replace_txn['gasPrice'] == 20 # Strategy provides higher gas price def test_eth_replaceTransaction_gas_price_defaulting_strategy_lower(self, web3, unlocked_account): txn_params = { 'from': unlocked_account, 'to': unlocked_account, 'value': 1, 'gas': 21000, 'gasPrice': 10, } txn_hash = web3.eth.sendTransaction(txn_params) def lower_gas_price_strategy(web3, txn): return 5 web3.eth.setGasPriceStrategy(lower_gas_price_strategy) txn_params.pop('gasPrice') replace_txn_hash = web3.eth.replaceTransaction(txn_hash, txn_params) replace_txn = web3.eth.getTransaction(replace_txn_hash) # Strategy provices lower gas price - minimum preferred assert replace_txn['gasPrice'] == 11 def test_eth_modifyTransaction(self, web3, unlocked_account): txn_params = { 'from': unlocked_account, 'to': unlocked_account, 'value': 1, 'gas': 21000, 'gasPrice': web3.eth.gasPrice, } txn_hash = web3.eth.sendTransaction(txn_params) modified_txn_hash = web3.eth.modifyTransaction( txn_hash, gasPrice=(txn_params['gasPrice'] * 2), value=2 ) modified_txn = web3.eth.getTransaction(modified_txn_hash) assert is_same_address(modified_txn['from'], txn_params['from']) assert is_same_address(modified_txn['to'], txn_params['to']) assert modified_txn['value'] == 2 assert modified_txn['gas'] == 21000 assert modified_txn['gasPrice'] == txn_params['gasPrice'] * 2 @pytest.mark.parametrize( 'raw_transaction, expected_hash', [ ( # address 0x39EEed73fb1D3855E90Cbd42f348b3D7b340aAA6 '0xf8648085174876e8008252089439eeed73fb1d3855e90cbd42f348b3d7b340aaa601801ba0ec1295f00936acd0c2cb90ab2cdaacb8bf5e11b3d9957833595aca9ceedb7aada05dfc8937baec0e26029057abd3a1ef8c505dca2cdc07ffacb046d090d2bea06a', # noqa: E501 '0x1f80f8ab5f12a45be218f76404bda64d37270a6f4f86ededd0eb599f80548c13', ), ( # private key 0x3c2ab4e8f17a7dea191b8c991522660126d681039509dc3bb31af7c9bdb63518 # This is an unfunded account, but the transaction has a 0 gas price, so is valid. # It never needs to be mined, we just want the transaction hash back to confirm. HexBytes('0xf85f808082c35094d898d5e829717c72e7438bad593076686d7d164a80801ba005c2e99ecee98a12fbf28ab9577423f42e9e88f2291b3acc8228de743884c874a077d6bc77a47ad41ec85c96aac2ad27f05a039c4787fca8a1e5ee2d8c7ec1bb6a'), # noqa: E501 '0x98eeadb99454427f6aad7b558bac13e9d225512a6f5e5c11cf48e8d4067e51b5', ), ] ) def test_eth_sendRawTransaction(self, web3, raw_transaction, funded_account_for_raw_txn, expected_hash): txn_hash = web3.eth.sendRawTransaction(raw_transaction) assert txn_hash == web3.toBytes(hexstr=expected_hash) def test_eth_call(self, web3, math_contract): coinbase = web3.eth.coinbase txn_params = math_contract._prepare_transaction( fn_name='add', fn_args=(7, 11), transaction={'from': coinbase, 'to': math_contract.address}, ) call_result = web3.eth.call(txn_params) assert is_string(call_result) result = decode_single('uint256', call_result) assert result == 18 def test_eth_call_with_0_result(self, web3, math_contract): coinbase = web3.eth.coinbase txn_params = math_contract._prepare_transaction( fn_name='add', fn_args=(0, 0), transaction={'from': coinbase, 'to': math_contract.address}, ) call_result = web3.eth.call(txn_params) assert is_string(call_result) result = decode_single('uint256', call_result) assert result == 0 def test_eth_estimateGas(self, web3, unlocked_account_dual_type): gas_estimate = web3.eth.estimateGas({ 'from': unlocked_account_dual_type, 'to': unlocked_account_dual_type, 'value': 1, }) assert is_integer(gas_estimate) assert gas_estimate > 0 def test_eth_estimateGas_with_block(self, web3, unlocked_account_dual_type): gas_estimate = web3.eth.estimateGas({ 'from': unlocked_account_dual_type, 'to': unlocked_account_dual_type, 'value': 1, }, 'latest') assert is_integer(gas_estimate) assert gas_estimate > 0 def test_eth_getBlockByHash(self, web3, empty_block): block = web3.eth.getBlock(empty_block['hash']) assert block['hash'] == empty_block['hash'] def test_eth_getBlockByHash_not_found(self, web3, empty_block): block = web3.eth.getBlock(UNKNOWN_HASH) assert block is None def test_eth_getBlockByNumber_with_integer(self, web3, empty_block): block = web3.eth.getBlock(empty_block['number']) assert block['number'] == empty_block['number'] def test_eth_getBlockByNumber_latest(self, web3, empty_block): current_block_number = web3.eth.blockNumber block = web3.eth.getBlock('latest') assert block['number'] == current_block_number def test_eth_getBlockByNumber_not_found(self, web3, empty_block): block = web3.eth.getBlock(12345) assert block is None def test_eth_getBlockByNumber_pending(self, web3, empty_block): current_block_number = web3.eth.blockNumber block = web3.eth.getBlock('pending') assert block['number'] == current_block_number + 1 def test_eth_getBlockByNumber_earliest(self, web3, empty_block): genesis_block = web3.eth.getBlock(0) block = web3.eth.getBlock('earliest') assert block['number'] == 0 assert block['hash'] == genesis_block['hash'] def test_eth_getBlockByNumber_full_transactions(self, web3, block_with_txn): block = web3.eth.getBlock(block_with_txn['number'], True) transaction = block['transactions'][0] assert transaction['hash'] == block_with_txn['transactions'][0] def test_eth_getTransactionByHash(self, web3, mined_txn_hash): transaction = web3.eth.getTransaction(mined_txn_hash) assert is_dict(transaction) assert transaction['hash'] == HexBytes(mined_txn_hash) def test_eth_getTransactionByHash_contract_creation(self, web3, math_contract_deploy_txn_hash): transaction = web3.eth.getTransaction(math_contract_deploy_txn_hash) assert is_dict(transaction) assert transaction['to'] is None, "to field is %r" % transaction['to'] def test_eth_getTransactionFromBlockHashAndIndex(self, web3, block_with_txn, mined_txn_hash): transaction = web3.eth.getTransactionFromBlock(block_with_txn['hash'], 0) assert is_dict(transaction) assert transaction['hash'] == HexBytes(mined_txn_hash) def test_eth_getTransactionFromBlockNumberAndIndex(self, web3, block_with_txn, mined_txn_hash): transaction = web3.eth.getTransactionFromBlock(block_with_txn['number'], 0) assert is_dict(transaction) assert transaction['hash'] == HexBytes(mined_txn_hash) def test_eth_getTransactionByBlockHashAndIndex(self, web3, block_with_txn, mined_txn_hash): transaction = web3.eth.getTransactionByBlock(block_with_txn['hash'], 0) assert is_dict(transaction) assert transaction['hash'] == HexBytes(mined_txn_hash) def test_eth_getTransactionByBlockNumberAndIndex(self, web3, block_with_txn, mined_txn_hash): transaction = web3.eth.getTransactionByBlock(block_with_txn['number'], 0) assert is_dict(transaction) assert transaction['hash'] == HexBytes(mined_txn_hash) def test_eth_getTransactionReceipt_mined(self, web3, block_with_txn, mined_txn_hash): receipt = web3.eth.getTransactionReceipt(mined_txn_hash) assert is_dict(receipt) assert receipt['blockNumber'] == block_with_txn['number'] assert receipt['blockHash'] == block_with_txn['hash'] assert receipt['transactionIndex'] == 0 assert receipt['transactionHash'] == HexBytes(mined_txn_hash) def test_eth_getTransactionReceipt_unmined(self, web3, unlocked_account_dual_type): txn_hash = web3.eth.sendTransaction({ 'from': unlocked_account_dual_type, 'to': unlocked_account_dual_type, 'value': 1, 'gas': 21000, 'gasPrice': web3.eth.gasPrice, }) receipt = web3.eth.getTransactionReceipt(txn_hash) assert receipt is None def test_eth_getTransactionReceipt_with_log_entry(self, web3, block_with_txn_with_log, emitter_contract, txn_hash_with_log): receipt = web3.eth.getTransactionReceipt(txn_hash_with_log) assert is_dict(receipt) assert receipt['blockNumber'] == block_with_txn_with_log['number'] assert receipt['blockHash'] == block_with_txn_with_log['hash'] assert receipt['transactionIndex'] == 0 assert receipt['transactionHash'] == HexBytes(txn_hash_with_log) assert len(receipt['logs']) == 1 log_entry = receipt['logs'][0] assert log_entry['blockNumber'] == block_with_txn_with_log['number'] assert log_entry['blockHash'] == block_with_txn_with_log['hash'] assert log_entry['logIndex'] == 0 assert is_same_address(log_entry['address'], emitter_contract.address) assert log_entry['transactionIndex'] == 0 assert log_entry['transactionHash'] == HexBytes(txn_hash_with_log) def test_eth_getUncleByBlockHashAndIndex(self, web3): # TODO: how do we make uncles.... pass def test_eth_getUncleByBlockNumberAndIndex(self, web3): # TODO: how do we make uncles.... pass def test_eth_getCompilers(self, web3): # TODO: do we want to test this? pass def test_eth_compileSolidity(self, web3): # TODO: do we want to test this? pass def test_eth_compileLLL(self, web3): # TODO: do we want to test this? pass def test_eth_compileSerpent(self, web3): # TODO: do we want to test this? pass def test_eth_newFilter(self, web3): filter = web3.eth.filter({}) changes = web3.eth.getFilterChanges(filter.filter_id) assert is_list_like(changes) assert not changes logs = web3.eth.getFilterLogs(filter.filter_id) assert is_list_like(logs) assert not logs result = web3.eth.uninstallFilter(filter.filter_id) assert result is True def test_eth_newBlockFilter(self, web3): filter = web3.eth.filter('latest') assert is_string(filter.filter_id) changes = web3.eth.getFilterChanges(filter.filter_id) assert is_list_like(changes) assert not changes # TODO: figure out why this fails in go-ethereum # logs = web3.eth.getFilterLogs(filter.filter_id) # assert is_list_like(logs) # assert not logs result = web3.eth.uninstallFilter(filter.filter_id) assert result is True def test_eth_newPendingTransactionFilter(self, web3): filter = web3.eth.filter('pending') assert is_string(filter.filter_id) changes = web3.eth.getFilterChanges(filter.filter_id) assert is_list_like(changes) assert not changes # TODO: figure out why this fails in go-ethereum # logs = web3.eth.getFilterLogs(filter.filter_id) # assert is_list_like(logs) # assert not logs result = web3.eth.uninstallFilter(filter.filter_id) assert result is True def test_eth_getLogs_without_logs(self, web3, block_with_txn_with_log): # Test with block range filter_params = { "fromBlock": 0, "toBlock": block_with_txn_with_log['number'] - 1, } result = web3.eth.getLogs(filter_params) assert len(result) == 0 # the range is wrong filter_params = { "fromBlock": block_with_txn_with_log['number'], "toBlock": block_with_txn_with_log['number'] - 1, } result = web3.eth.getLogs(filter_params) assert len(result) == 0 # Test with `address` # filter with other address filter_params = { "fromBlock": 0, "address": UNKNOWN_ADDRESS, } result = web3.eth.getLogs(filter_params) assert len(result) == 0 # Test with multiple `address` # filter with other address filter_params = { "fromBlock": 0, "address": [UNKNOWN_ADDRESS, UNKNOWN_ADDRESS], } result = web3.eth.getLogs(filter_params) assert len(result) == 0 def test_eth_getLogs_with_logs( self, web3, block_with_txn_with_log, emitter_contract_address, txn_hash_with_log): def assert_contains_log(result): assert len(result) == 1 log_entry = result[0] assert log_entry['blockNumber'] == block_with_txn_with_log['number'] assert log_entry['blockHash'] == block_with_txn_with_log['hash'] assert log_entry['logIndex'] == 0 assert is_same_address(log_entry['address'], emitter_contract_address) assert log_entry['transactionIndex'] == 0 assert log_entry['transactionHash'] == HexBytes(txn_hash_with_log) # Test with block range # the range includes the block where the log resides in filter_params = { "fromBlock": block_with_txn_with_log['number'], "toBlock": block_with_txn_with_log['number'], } result = web3.eth.getLogs(filter_params) assert_contains_log(result) # specify only `from_block`. by default `to_block` should be 'latest' filter_params = { "fromBlock": 0, } result = web3.eth.getLogs(filter_params) assert_contains_log(result) # Test with `address` # filter with emitter_contract.address filter_params = { "fromBlock": 0, "address": emitter_contract_address, } def test_eth_getLogs_with_logs_topic_args( self, web3, block_with_txn_with_log, emitter_contract_address, txn_hash_with_log): def assert_contains_log(result): assert len(result) == 1 log_entry = result[0] assert log_entry['blockNumber'] == block_with_txn_with_log['number'] assert log_entry['blockHash'] == block_with_txn_with_log['hash'] assert log_entry['logIndex'] == 0 assert is_same_address(log_entry['address'], emitter_contract_address) assert log_entry['transactionIndex'] == 0 assert log_entry['transactionHash'] == HexBytes(txn_hash_with_log) # Test with None event sig filter_params = { "fromBlock": 0, "topics": [ None, '0x000000000000000000000000000000000000000000000000000000000000d431'], } result = web3.eth.getLogs(filter_params) assert_contains_log(result) # Test with None indexed arg filter_params = { "fromBlock": 0, "topics": [ '0x057bc32826fbe161da1c110afcdcae7c109a8b69149f727fc37a603c60ef94ca', None], } result = web3.eth.getLogs(filter_params) assert_contains_log(result) def test_eth_getLogs_with_logs_none_topic_args( self, web3): # Test with None overflowing filter_params = { "fromBlock": 0, "topics": [None, None, None], } result = web3.eth.getLogs(filter_params) assert len(result) == 0 def test_eth_call_old_contract_state(self, web3, math_contract, unlocked_account): start_block = web3.eth.getBlock('latest') block_num = start_block.number block_hash = start_block.hash math_contract.functions.increment().transact({'from': unlocked_account}) # This isn't an incredibly convincing test since we can't mine, and # the default resolved block is latest, So if block_identifier was ignored # we would get the same result. For now, we mostly depend on core tests. # Ideas to improve this test: # - Enable on-demand mining in more clients # - Increment the math contract in all of the fixtures, and check the value in an old block block_hash_call_result = math_contract.functions.counter().call(block_identifier=block_hash) block_num_call_result = math_contract.functions.counter().call(block_identifier=block_num) latest_call_result = math_contract.functions.counter().call(block_identifier='latest') default_call_result = math_contract.functions.counter().call() pending_call_result = math_contract.functions.counter().call(block_identifier='pending') assert block_hash_call_result == 0 assert block_num_call_result == 0 assert latest_call_result == 0 assert default_call_result == 0 if pending_call_result != 1: raise AssertionError("pending call result was %d instead of 1" % pending_call_result) def test_eth_uninstallFilter(self, web3): filter = web3.eth.filter({}) assert is_string(filter.filter_id) success = web3.eth.uninstallFilter(filter.filter_id) assert success is True failure = web3.eth.uninstallFilter(filter.filter_id) assert failure is False
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/module_testing/eth_module.py
eth_module.py
EMITTER_BYTECODE = ( "60606040526104ae806100126000396000f3606060405236156100615760e060020a60003504630b" "b563d6811461006357806317c0c1801461013657806320f0256e1461017057806390b41d8b146101" "ca5780639c37705314610215578063aa6fd82214610267578063e17bf956146102a9575b005b6020" "6004803580820135601f810184900490930260809081016040526060848152610061946024939192" "918401918190838280828437509496505050505050507fa95e6e2a182411e7a6f9ed114a85c3761d" "87f9b8f453d842c71235aa64fff99f81604051808060200182810382528381815181526020019150" "80519060200190808383829060006004602084601f0104600f02600301f150905090810190601f16" "80156101255780820380516001836020036101000a031916815260200191505b5092505050604051" "80910390a15b50565b610061600435600181141561037a577f1e86022f78f8d04f8e3dfd13a2bdb2" "80403e6632877c0dbee5e4eeb259908a5c60006060a1610133565b61006160043560243560443560" "64356084356005851415610392576060848152608084815260a084905260c08390527ff039d147f2" "3fe975a4254bdf6b1502b8c79132ae1833986b7ccef2638e73fdf991a15b5050505050565b610061" "60043560243560443560038314156103d457606082815260808290527fdf0cb1dea99afceb3ea698" "d62e705b736f1345a7eee9eb07e63d1f8f556c1bc590604090a15b505050565b6100616004356024" "356044356064356004841415610428576060838152608083905260a08290527f4a25b279c7c585f2" "5eda9788ac9420ebadae78ca6b206a0e6ab488fd81f550629080a15b50505050565b610061600435" "60243560028214156104655760608181527f56d2ef3c5228bf5d88573621e325a4672ab50e033749" "a601e4f4a5e1dce905d490602090a15b5050565b60206004803580820135601f8101849004909302" "60809081016040526060848152610061946024939192918401918190838280828437509496505050" "505050507f532fd6ea96cfb78bb46e09279a26828b8b493de1a2b8b1ee1face527978a15a5816040" "51808060200182810382528381815181526020019150805190602001908083838290600060046020" "84601f0104600f02600301f150905090810190601f16801561012557808203805160018360200361" "01000a03191681526020019150509250505060405180910390a150565b600081141561038d576000" "6060a0610133565b610002565b600b85141561038d5760608481526080849052819083907fa30ece" "802b64cd2b7e57dabf4010aabf5df26d1556977affb07b98a77ad955b590604090a36101c3565b60" "0983141561040f57606082815281907f057bc32826fbe161da1c110afcdcae7c109a8b69149f727f" "c37a603c60ef94ca90602090a2610210565b600883141561038d5760608281528190602090a16102" "10565b600a84141561038d576060838152819083907ff16c999b533366ca5138d78e85da51611089" "cd05749f098d6c225d4cd42ee6ec90602090a3610261565b600782141561049a57807ff70fe689e2" "90d8ce2b2a388ac28db36fbb0e16a6d89c6804c461f65a1b40bb1560006060a26102a5565b600682" "141561038d578060006060a16102a556" ) EMITTER_ABI = [ { "constant": False, "inputs": [{"name": "v", "type": "string"}], "name": "logString", "outputs": [], "type": "function", }, { "constant": False, "inputs": [{"name": "which", "type": "uint8"}], "name": "logNoArgs", "outputs": [], "type": "function", }, { "constant": False, "inputs": [ {"name": "which", "type": "uint8"}, {"name": "arg0", "type": "uint256"}, {"name": "arg1", "type": "uint256"}, {"name": "arg2", "type": "uint256"}, {"name": "arg3", "type": "uint256"}, ], "name": "logQuadruple", "outputs": [], "type": "function", }, { "constant": False, "inputs": [ {"name": "which", "type": "uint8"}, {"name": "arg0", "type": "uint256"}, {"name": "arg1", "type": "uint256"}, ], "name": "logDouble", "outputs": [], "type": "function", }, { "constant": False, "inputs": [ {"name": "which", "type": "uint8"}, {"name": "arg0", "type": "uint256"}, {"name": "arg1", "type": "uint256"}, {"name": "arg2", "type": "uint256"}, ], "name": "logTriple", "outputs": [], "type": "function", }, { "constant": False, "inputs": [ {"name": "which", "type": "uint8"}, {"name": "arg0", "type": "uint256"}, ], "name": "logSingle", "outputs": [], "type": "function", }, { "constant": False, "inputs": [{"name": "v", "type": "bytes"}], "name": "logBytes", "outputs": [], "type": "function", }, { "anonymous": True, "inputs": [], "name": "LogAnonymous", "type": "event", }, { "anonymous": False, "inputs": [], "name": "LogNoArguments", "type": "event", }, { "anonymous": False, "inputs": [{"indexed": False, "name": "arg0", "type": "uint256"}], "name": "LogSingleArg", "type": "event", }, { "anonymous": False, "inputs": [ {"indexed": False, "name": "arg0", "type": "uint256"}, {"indexed": False, "name": "arg1", "type": "uint256"}, ], "name": "LogDoubleArg", "type": "event", }, { "anonymous": False, "inputs": [ {"indexed": False, "name": "arg0", "type": "uint256"}, {"indexed": False, "name": "arg1", "type": "uint256"}, {"indexed": False, "name": "arg2", "type": "uint256"}, ], "name": "LogTripleArg", "type": "event", }, { "anonymous": False, "inputs": [ {"indexed": False, "name": "arg0", "type": "uint256"}, {"indexed": False, "name": "arg1", "type": "uint256"}, {"indexed": False, "name": "arg2", "type": "uint256"}, {"indexed": False, "name": "arg3", "type": "uint256"}, ], "name": "LogQuadrupleArg", "type": "event", }, { "anonymous": True, "inputs": [{"indexed": True, "name": "arg0", "type": "uint256"}], "name": "LogSingleAnonymous", "type": "event", }, { "anonymous": False, "inputs": [{"indexed": True, "name": "arg0", "type": "uint256"}], "name": "LogSingleWithIndex", "type": "event", }, { "anonymous": True, "inputs": [ {"indexed": False, "name": "arg0", "type": "uint256"}, {"indexed": True, "name": "arg1", "type": "uint256"}, ], "name": "LogDoubleAnonymous", "type": "event", }, { "anonymous": False, "inputs": [ {"indexed": False, "name": "arg0", "type": "uint256"}, {"indexed": True, "name": "arg1", "type": "uint256"}, ], "name": "LogDoubleWithIndex", "type": "event", }, { "anonymous": False, "inputs": [ {"indexed": False, "name": "arg0", "type": "uint256"}, {"indexed": True, "name": "arg1", "type": "uint256"}, {"indexed": True, "name": "arg2", "type": "uint256"}, ], "name": "LogTripleWithIndex", "type": "event", }, { "anonymous": False, "inputs": [ {"indexed": False, "name": "arg0", "type": "uint256"}, {"indexed": False, "name": "arg1", "type": "uint256"}, {"indexed": True, "name": "arg2", "type": "uint256"}, {"indexed": True, "name": "arg3", "type": "uint256"}, ], "name": "LogQuadrupleWithIndex", "type": "event", }, { "anonymous": False, "inputs": [{"indexed": False, "name": "v", "type": "bytes"}], "name": "LogBytes", "type": "event", }, { "anonymous": False, "inputs": [{"indexed": False, "name": "v", "type": "string"}], "name": "LogString", "type": "event", }, ] EMITTER_ENUM = { 'LogAnonymous': 0, 'LogNoArguments': 1, 'LogSingleArg': 2, 'LogDoubleArg': 3, 'LogTripleArg': 4, 'LogQuadrupleArg': 5, 'LogSingleAnonymous': 6, 'LogSingleWithIndex': 7, 'LogDoubleAnonymous': 8, 'LogDoubleWithIndex': 9, 'LogTripleWithIndex': 10, 'LogQuadrupleWithInde': 11, }
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/module_testing/emitter_contract.py
emitter_contract.py
MATH_BYTECODE = ( "606060405261022e806100126000396000f360606040523615610074576000357c01000000000000" "000000000000000000000000000000000000000000009004806316216f391461007657806361bc22" "1a146100995780637cf5dab0146100bc578063a5f3c23b146100e8578063d09de08a1461011d5780" "63dcf537b11461014057610074565b005b610083600480505061016c565b60405180828152602001" "91505060405180910390f35b6100a6600480505061017f565b604051808281526020019150506040" "5180910390f35b6100d26004808035906020019091905050610188565b6040518082815260200191" "505060405180910390f35b61010760048080359060200190919080359060200190919050506101ea" "565b6040518082815260200191505060405180910390f35b61012a6004805050610201565b604051" "8082815260200191505060405180910390f35b610156600480803590602001909190505061021756" "5b6040518082815260200191505060405180910390f35b6000600d9050805080905061017c565b90" "565b60006000505481565b6000816000600082828250540192505081905550600060005054905080" "507f3496c3ede4ec3ab3686712aa1c238593ea6a42df83f98a5ec7df9834cfa577c5816040518082" "815260200191505060405180910390a18090506101e5565b919050565b6000818301905080508090" "506101fb565b92915050565b600061020d6001610188565b9050610214565b90565b600060078202" "90508050809050610229565b91905056" ) MATH_ABI = [ { "constant": False, "inputs": [], "name": "return13", "outputs": [ {"name": "result", "type": "int256"}, ], "type": "function", }, { "constant": True, "inputs": [], "name": "counter", "outputs": [ {"name": "", "type": "uint256"}, ], "type": "function", }, { "constant": False, "inputs": [ {"name": "amt", "type": "uint256"}, ], "name": "increment", "outputs": [ {"name": "result", "type": "uint256"}, ], "type": "function", }, { "constant": False, "inputs": [ {"name": "a", "type": "int256"}, {"name": "b", "type": "int256"}, ], "name": "add", "outputs": [ {"name": "result", "type": "int256"}, ], "type": "function", }, { "constant": False, "inputs": [], "name": "increment", "outputs": [ {"name": "", "type": "uint256"}, ], "type": "function" }, { "constant": False, "inputs": [ {"name": "a", "type": "int256"}, ], "name": "multiply7", "outputs": [ {"name": "result", "type": "int256"}, ], "type": "function", }, { "anonymous": False, "inputs": [ {"indexed": False, "name": "value", "type": "uint256"}, ], "name": "Increased", "type": "event", }, ]
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/module_testing/math_contract.py
math_contract.py
import pytest from eth_utils import ( add_0x_prefix, ) from web3._utils.formatters import ( hex_to_integer, ) class ParityModuleTest: def test_list_storage_keys_no_support(self, web3, emitter_contract_address): keys = web3.parity.listStorageKeys(emitter_contract_address, 10, None) assert keys is None def test_trace_replay_transaction(self, web3, parity_fixture_data): trace = web3.parity.traceReplayTransaction(parity_fixture_data['mined_txn_hash']) assert trace['stateDiff'] is None assert trace['vmTrace'] is None assert trace['trace'][0]['action']['from'] == add_0x_prefix(parity_fixture_data['coinbase']) def test_trace_replay_block_with_transactions(self, web3, block_with_txn, parity_fixture_data): trace = web3.parity.traceReplayBlockTransactions(block_with_txn['number']) assert len(trace) > 0 trace_0_action = trace[0]['trace'][0]['action'] assert trace_0_action['from'] == add_0x_prefix(parity_fixture_data['coinbase']) def test_trace_replay_block_without_transactions(self, web3, empty_block): trace = web3.parity.traceReplayBlockTransactions(empty_block['number']) assert len(trace) == 0 def test_trace_block(self, web3, block_with_txn): trace = web3.parity.traceBlock(block_with_txn['number']) assert trace[0]['blockNumber'] == block_with_txn['number'] def test_trace_transaction(self, web3, parity_fixture_data): trace = web3.parity.traceTransaction(parity_fixture_data['mined_txn_hash']) assert trace[0]['action']['from'] == add_0x_prefix(parity_fixture_data['coinbase']) def test_trace_call(self, web3, math_contract, math_contract_address): coinbase = web3.eth.coinbase txn_params = math_contract._prepare_transaction( fn_name='add', fn_args=(7, 11), transaction={'from': coinbase, 'to': math_contract_address}, ) trace = web3.parity.traceCall(txn_params) assert trace['stateDiff'] is None assert trace['vmTrace'] is None result = hex_to_integer(trace['output']) assert result == 18 def test_eth_call_with_0_result(self, web3, math_contract, math_contract_address): coinbase = web3.eth.coinbase txn_params = math_contract._prepare_transaction( fn_name='add', fn_args=(0, 0), transaction={'from': coinbase, 'to': math_contract_address}, ) trace = web3.parity.traceCall(txn_params) assert trace['stateDiff'] is None assert trace['vmTrace'] is None result = hex_to_integer(trace['output']) assert result == 0 @pytest.mark.parametrize( 'raw_transaction', [ ( # address 0x39EEed73fb1D3855E90Cbd42f348b3D7b340aAA6 '0xf8648085174876e8008252089439eeed73fb1d3855e90cbd42f348b3d7b340aaa601801ba0ec1295f00936acd0c2cb90ab2cdaacb8bf5e11b3d9957833595aca9ceedb7aada05dfc8937baec0e26029057abd3a1ef8c505dca2cdc07ffacb046d090d2bea06a' # noqa: E501 ), ] ) def test_trace_raw_transaction(self, web3, raw_transaction, funded_account_for_raw_txn): trace = web3.parity.traceRawTransaction(raw_transaction) assert trace['stateDiff'] is None assert trace['vmTrace'] is None assert trace['trace'][0]['action']['from'] == funded_account_for_raw_txn.lower() def test_trace_filter(self, web3, txn_filter_params, parity_fixture_data): trace = web3.parity.traceFilter(txn_filter_params) assert isinstance(trace, list) assert trace[0]['action']['from'] == add_0x_prefix(parity_fixture_data['coinbase'])
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/module_testing/parity_module.py
parity_module.py
from eth_utils import ( is_boolean, is_integer, is_string, ) class NetModuleTest: def test_net_version(self, web3): version = web3.net.version assert is_string(version) assert version.isdigit() def test_net_listening(self, web3): listening = web3.net.listening assert is_boolean(listening) def test_net_peerCount(self, web3): peer_count = web3.net.peerCount assert is_integer(peer_count)
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/module_testing/net_module.py
net_module.py
from eth_utils import ( is_string, ) class VersionModuleTest: def test_eth_protocolVersion(self, web3): protocol_version = web3.version.ethereum assert is_string(protocol_version) assert protocol_version.isdigit()
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/module_testing/version_module.py
version_module.py
from eth_utils import ( is_checksum_address, is_list_like, is_same_address, ) PRIVATE_KEY_HEX = '0x56ebb41875ceedd42e395f730e03b5c44989393c9f0484ee6bc05f933673458f' PASSWORD = 'web3-testing' ADDRESS = '0x844B417c0C58B02c2224306047B9fb0D3264fE8c' PRIVATE_KEY_FOR_UNLOCK = '0x392f63a79b1ff8774845f3fa69de4a13800a59e7083f5187f1558f0797ad0f01' ACCOUNT_FOR_UNLOCK = '0x12efDc31B1a8FA1A1e756DFD8A1601055C971E13' class PersonalModuleTest: def test_personal_importRawKey(self, web3): actual = web3.personal.importRawKey(PRIVATE_KEY_HEX, PASSWORD) assert actual == ADDRESS def test_personal_listAccounts(self, web3): accounts = web3.personal.listAccounts assert is_list_like(accounts) assert len(accounts) > 0 assert all(( is_checksum_address(item) for item in accounts )) def test_personal_lockAccount(self, web3, unlockable_account_dual_type): # TODO: how do we test this better? web3.personal.lockAccount(unlockable_account_dual_type) def test_personal_unlockAccount_success(self, web3, unlockable_account_dual_type, unlockable_account_pw): result = web3.personal.unlockAccount(unlockable_account_dual_type, unlockable_account_pw) assert result is True def test_personal_unlockAccount_failure(self, web3, unlockable_account_dual_type): result = web3.personal.unlockAccount(unlockable_account_dual_type, 'bad-password') assert result is False def test_personal_newAccount(self, web3): new_account = web3.personal.newAccount(PASSWORD) assert is_checksum_address(new_account) def test_personal_sendTransaction(self, web3, unlockable_account_dual_type, unlockable_account_pw): assert web3.eth.getBalance(unlockable_account_dual_type) > web3.toWei(1, 'ether') txn_params = { 'from': unlockable_account_dual_type, 'to': unlockable_account_dual_type, 'gas': 21000, 'value': 1, 'gasPrice': web3.toWei(1, 'gwei'), } txn_hash = web3.personal.sendTransaction(txn_params, unlockable_account_pw) assert txn_hash transaction = web3.eth.getTransaction(txn_hash) assert is_same_address(transaction['from'], txn_params['from']) assert is_same_address(transaction['to'], txn_params['to']) assert transaction['gas'] == txn_params['gas'] assert transaction['value'] == txn_params['value'] assert transaction['gasPrice'] == txn_params['gasPrice'] def test_personal_sign_and_ecrecover(self, web3, unlockable_account_dual_type, unlockable_account_pw): message = 'test-web3-personal-sign' signature = web3.personal.sign(message, unlockable_account_dual_type, unlockable_account_pw) signer = web3.personal.ecRecover(message, signature) assert is_same_address(signer, unlockable_account_dual_type)
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/module_testing/personal_module.py
personal_module.py
from .web3_module import ( # noqa: F401 Web3ModuleTest, ) from .eth_module import ( # noqa: F401 EthModuleTest, ) from .net_module import ( # noqa: F401 NetModuleTest, ) from .personal_module import ( # noqa: F401 PersonalModuleTest, ) from .version_module import ( # noqa: F401 VersionModuleTest, ) from .parity_module import ( # noqa: F401 ParityModuleTest, )
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/module_testing/__init__.py
__init__.py
import pytest from hexbytes import ( HexBytes, ) from web3 import Web3 from web3._utils.ens import ( ens_addresses, ) from web3.exceptions import ( InvalidAddress, ) class Web3ModuleTest: def test_web3_clientVersion(self, web3): client_version = web3.version.node self._check_web3_clientVersion(client_version) def _check_web3_clientVersion(self, client_version): raise NotImplementedError("Must be implemented by subclasses") # Contract that calculated test values can be found at # https://kovan.etherscan.io/address/0xb9be06f5b99372cf9afbccadbbb9954ccaf7f4bb#code @pytest.mark.parametrize( 'types,values,expected', ( ( ['bool'], [True], HexBytes("0x5fe7f977e71dba2ea1a68e21057beebb9be2ac30c6410aa38d4f3fbe41dcffd2"), ), ( ['uint8', 'uint8', 'uint8'], [97, 98, 99], HexBytes("0x4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45"), ), ( ['uint248'], [30], HexBytes("0x30f95d210785601eb33ae4d53d405b26f920e765dff87cca8e9a4aec99f82671"), ), ( ['bool', 'uint16'], [True, 299], HexBytes("0xed18599ccd80ee9fae9a28b0e34a5573c3233d7468f808fd659bc171cf0b43bd"), ), ( ['int256'], [-10], HexBytes("0xd6fb717f7e270a360f5093ce6a7a3752183e89c9a9afe5c0cb54b458a304d3d5"), ), ( ['int256'], [10], HexBytes("0xc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2a8"), ), ( ['int8', 'uint8'], [-10, 18], HexBytes("0x5c6ab1e634c08d9c0f4df4d789e8727943ef010dd7ca8e3c89de197a26d148be"), ), ( ['address'], ["0x49eddd3769c0712032808d86597b84ac5c2f5614"], InvalidAddress, ), ( ['address'], ["0x49EdDD3769c0712032808D86597B84ac5c2F5614"], HexBytes("0x2ff37b5607484cd4eecf6d13292e22bd6e5401eaffcc07e279583bc742c68882"), ), ( ['bytes2'], ['0x5402'], HexBytes("0x4ed9171bda52fca71ab28e7f452bd6eacc3e5a568a47e0fa53b503159a9b8910"), ), ( ['bytes3'], ['0x5402'], HexBytes("0x4ed9171bda52fca71ab28e7f452bd6eacc3e5a568a47e0fa53b503159a9b8910"), ), ( ['bytes'], [ '0x636865636b6c6f6e6762797465737472696e676167' '61696e7374736f6c6964697479736861336861736866756e6374696f6e' ], HexBytes("0xd78a84d65721b67e4011b10c99dafdedcdcd7cb30153064f773e210b4762e22f"), ), ( ['string'], ['testing a string!'], HexBytes("0xe8c275c0b4070a5ec6cfcb83f0ba394b30ddd283de785d43f2eabfb04bd96747"), ), ( ['string', 'bool', 'uint16', 'bytes2', 'address'], [ 'testing a string!', False, 299, '0x5402', "0x49eddd3769c0712032808d86597b84ac5c2f5614", ], InvalidAddress, ), ( ['string', 'bool', 'uint16', 'bytes2', 'address'], [ 'testing a string!', False, 299, '0x5402', "0x49EdDD3769c0712032808D86597B84ac5c2F5614", ], HexBytes("0x8cc6eabb25b842715e8ca39e2524ed946759aa37bfb7d4b81829cf5a7e266103"), ), ( ['bool[2][]'], [[[True, False], [False, True]]], HexBytes("0x1eef261f2eb51a8c736d52be3f91ff79e78a9ec5df2b7f50d0c6f98ed1e2bc06"), ), ( ['bool[]'], [[True, False, True]], HexBytes("0x5c6090c0461491a2941743bda5c3658bf1ea53bbd3edcde54e16205e18b45792"), ), ( ['uint24[]'], [[1, 0, 1]], HexBytes("0x5c6090c0461491a2941743bda5c3658bf1ea53bbd3edcde54e16205e18b45792"), ), ( ['uint8[2]'], [[8, 9]], HexBytes("0xc7694af312c4f286114180fd0ba6a52461fcee8a381636770b19a343af92538a"), ), ( ['uint256[2]'], [[8, 9]], HexBytes("0xc7694af312c4f286114180fd0ba6a52461fcee8a381636770b19a343af92538a"), ), ( ['uint8[]'], [[8]], HexBytes("0xf3f7a9fe364faab93b216da50a3214154f22a0a2b415b23a84c8169e8b636ee3"), ), ( ['address[]'], [[ "0x49EdDD3769c0712032808D86597B84ac5c2F5614", "0xA6b759bBbf4B59D24acf7E06e79f3a5D104fdCE5", ]], HexBytes("0xb98565c0c26a962fd54d93b0ed6fb9296e03e9da29d2281ed3e3473109ef7dde"), ), ( ['address[]'], [[ "0x49EdDD3769c0712032808D86597B84ac5c2F5614", "0xa6b759bbbf4b59d24acf7e06e79f3a5d104fdce5", ]], InvalidAddress, ), ), ) def test_solidityKeccak(self, web3, types, values, expected): if isinstance(expected, type) and issubclass(expected, Exception): with pytest.raises(expected): web3.solidityKeccak(types, values) return actual = web3.solidityKeccak(types, values) assert actual == expected @pytest.mark.parametrize( 'types, values, expected', ( ( ['address'], ['one.eth'], HexBytes("0x2ff37b5607484cd4eecf6d13292e22bd6e5401eaffcc07e279583bc742c68882"), ), ( ['address[]'], [['one.eth', 'two.eth']], HexBytes("0xb98565c0c26a962fd54d93b0ed6fb9296e03e9da29d2281ed3e3473109ef7dde"), ), ), ) def test_solidityKeccak_ens(self, web3, types, values, expected): with ens_addresses(web3, { 'one.eth': "0x49EdDD3769c0712032808D86597B84ac5c2F5614", 'two.eth': "0xA6b759bBbf4B59D24acf7E06e79f3a5D104fdCE5", }): # when called as class method, any name lookup attempt will fail with pytest.raises(InvalidAddress): Web3.solidityKeccak(types, values) # when called as instance method, ens lookups can succeed actual = web3.solidityKeccak(types, values) assert actual == expected @pytest.mark.parametrize( 'types,values', ( (['address'], ['0xA6b759bBbf4B59D24acf7E06e79f3a5D104fdCE5', True]), (['address', 'bool'], ['0xA6b759bBbf4B59D24acf7E06e79f3a5D104fdCE5']), ([], ['0xA6b759bBbf4B59D24acf7E06e79f3a5D104fdCE5']), ) ) def test_solidityKeccak_same_number_of_types_and_values(self, web3, types, values): with pytest.raises(ValueError): web3.solidityKeccak(types, values) def test_is_connected(self, web3): assert web3.isConnected()
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/_utils/module_testing/web3_module.py
web3_module.py
def rpc_gas_price_strategy(web3, transaction_params=None): """ A simple gas price strategy deriving it's value from the eth_gasPrice JSON-RPC call. """ return web3.manager.request_blocking("eth_gasPrice", [])
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/gas_strategies/rpc.py
rpc.py
import collections import math import operator from eth_utils import ( to_tuple, ) from web3._utils.math import ( percentile, ) from web3._utils.toolz import ( curry, groupby, sliding_window, ) from web3.exceptions import ( InsufficientData, ValidationError, ) MinerData = collections.namedtuple( 'MinerData', ['miner', 'num_blocks', 'min_gas_price', 'low_percentile_gas_price']) Probability = collections.namedtuple('Probability', ['gas_price', 'prob']) def _get_avg_block_time(w3, sample_size): latest = w3.eth.getBlock('latest') constrained_sample_size = min(sample_size, latest['number']) if constrained_sample_size == 0: raise ValidationError('Constrained sample size is 0') oldest = w3.eth.getBlock(latest['number'] - constrained_sample_size) return (latest['timestamp'] - oldest['timestamp']) / constrained_sample_size def _get_raw_miner_data(w3, sample_size): latest = w3.eth.getBlock('latest', full_transactions=True) for transaction in latest['transactions']: yield (latest['miner'], latest['hash'], transaction['gasPrice']) block = latest for _ in range(sample_size - 1): if block['number'] == 0: break # we intentionally trace backwards using parent hashes rather than # block numbers to make caching the data easier to implement. block = w3.eth.getBlock(block['parentHash'], full_transactions=True) for transaction in block['transactions']: yield (block['miner'], block['hash'], transaction['gasPrice']) def _aggregate_miner_data(raw_data): data_by_miner = groupby(0, raw_data) for miner, miner_data in data_by_miner.items(): _, block_hashes, gas_prices = map(set, zip(*miner_data)) try: price_percentile = percentile(gas_prices, percentile=20) except InsufficientData: price_percentile = min(gas_prices) yield MinerData( miner, len(set(block_hashes)), min(gas_prices), price_percentile) @to_tuple def _compute_probabilities(miner_data, wait_blocks, sample_size): """ Computes the probabilities that a txn will be accepted at each of the gas prices accepted by the miners. """ miner_data_by_price = tuple(sorted( miner_data, key=operator.attrgetter('low_percentile_gas_price'), reverse=True, )) for idx in range(len(miner_data_by_price)): low_percentile_gas_price = miner_data_by_price[idx].low_percentile_gas_price num_blocks_accepting_price = sum(m.num_blocks for m in miner_data_by_price[idx:]) inv_prob_per_block = (sample_size - num_blocks_accepting_price) / sample_size probability_accepted = 1 - inv_prob_per_block ** wait_blocks yield Probability(low_percentile_gas_price, probability_accepted) def _compute_gas_price(probabilities, desired_probability): """ Given a sorted range of ``Probability`` named-tuples returns a gas price computed based on where the ``desired_probability`` would fall within the range. :param probabilities: An iterable of `Probability` named-tuples sorted in reverse order. :param desired_probability: An floating point representation of the desired probability. (e.g. ``85% -> 0.85``) """ first = probabilities[0] last = probabilities[-1] if desired_probability >= first.prob: return first.gas_price elif desired_probability <= last.prob: return last.gas_price for left, right in sliding_window(2, probabilities): if desired_probability < right.prob: continue elif desired_probability > left.prob: # This code block should never be reachable as it would indicate # that we already passed by the probability window in which our # `desired_probability` is located. raise Exception('Invariant') adj_prob = desired_probability - right.prob window_size = left.prob - right.prob position = adj_prob / window_size gas_window_size = left.gas_price - right.gas_price gas_price = int(math.ceil(right.gas_price + gas_window_size * position)) return gas_price else: # The initial `if/else` clause in this function handles the case where # the `desired_probability` is either above or below the min/max # probability found in the `probabilities`. # # With these two cases handled, the only way this code block should be # reachable would be if the `probabilities` were not sorted correctly. # Otherwise, the `desired_probability` **must** fall between two of the # values in the `probabilities``. raise Exception('Invariant') @curry def construct_time_based_gas_price_strategy(max_wait_seconds, sample_size=120, probability=98): """ A gas pricing strategy that uses recently mined block data to derive a gas price for which a transaction is likely to be mined within X seconds with probability P. :param max_wait_seconds: The desired maxiumum number of seconds the transaction should take to mine. :param sample_size: The number of recent blocks to sample :param probability: An integer representation of the desired probability that the transaction will be mined within ``max_wait_seconds``. 0 means 0% and 100 means 100%. """ def time_based_gas_price_strategy(web3, transaction_params): avg_block_time = _get_avg_block_time(web3, sample_size=sample_size) wait_blocks = int(math.ceil(max_wait_seconds / avg_block_time)) raw_miner_data = _get_raw_miner_data(web3, sample_size=sample_size) miner_data = _aggregate_miner_data(raw_miner_data) probabilities = _compute_probabilities( miner_data, wait_blocks=wait_blocks, sample_size=sample_size, ) gas_price = _compute_gas_price(probabilities, probability / 100) return gas_price return time_based_gas_price_strategy # fast: mine within 1 minute fast_gas_price_strategy = construct_time_based_gas_price_strategy( max_wait_seconds=60, sample_size=120, ) # medium: mine within 10 minutes medium_gas_price_strategy = construct_time_based_gas_price_strategy( max_wait_seconds=600, sample_size=120, ) # slow: mine within 1 hour (60 minutes) slow_gas_price_strategy = construct_time_based_gas_price_strategy( max_wait_seconds=60 * 60, sample_size=120, ) # glacial: mine within the next 24 hours. glacial_gas_price_strategy = construct_time_based_gas_price_strategy( max_wait_seconds=24 * 60 * 60, sample_size=720, )
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/gas_strategies/time_based.py
time_based.py
from web3._utils import ( # noqa: F401 abi, blocks, caching, compat, contracts, datatypes, decorators, empty, encoding, ens, events, filters, formatters, function_identifiers, http, hypothesis, math, module_testing, normalizers, request, rpc_abi, threads, toolz, transactions, validation, )
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/utils/__init__.py
__init__.py
def construct_fixture_middleware(fixtures): """ Constructs a middleware which returns a static response for any method which is found in the provided fixtures. """ def fixture_middleware(make_request, web3): def middleware(method, params): if method in fixtures: result = fixtures[method] return {'result': result} else: return make_request(method, params) return middleware return fixture_middleware def construct_result_generator_middleware(result_generators): """ Constructs a middleware which intercepts requests for any method found in the provided mapping of endpoints to generator functions, returning whatever response the generator function returns. Callbacks must be functions with the signature `fn(method, params)`. """ def result_generator_middleware(make_request, web3): def middleware(method, params): if method in result_generators: result = result_generators[method](method, params) return {'result': result} else: return make_request(method, params) return middleware return result_generator_middleware def construct_error_generator_middleware(error_generators): """ Constructs a middleware which intercepts requests for any method found in the provided mapping of endpoints to generator functions, returning whatever error message the generator function returns. Callbacks must be functions with the signature `fn(method, params)`. """ def error_generator_middleware(make_request, web3): def middleware(method, params): if method in error_generators: error_msg = error_generators[method](method, params) return {'error': error_msg} else: return make_request(method, params) return middleware return error_generator_middleware
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/middleware/fixture.py
fixture.py
from eth_utils import ( is_string, ) from web3._utils.formatters import ( apply_formatter_at_index, apply_formatter_if, apply_formatters_to_dict, ) from .formatting import ( construct_formatting_middleware, ) FILTER_PARAM_NORMALIZERS = apply_formatters_to_dict({ 'address': apply_formatter_if(is_string, lambda x: [x])}) METHOD_NORMALIZERS = { 'eth_getLogs': apply_formatter_at_index(FILTER_PARAM_NORMALIZERS, 0), 'eth_newFilter': apply_formatter_at_index(FILTER_PARAM_NORMALIZERS, 0) } request_parameter_normalizer = construct_formatting_middleware( request_formatters=METHOD_NORMALIZERS, )
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/middleware/normalize_request_parameters.py
normalize_request_parameters.py
import codecs import operator from eth_utils.curried import ( combine_argument_formatters, is_address, is_bytes, is_integer, is_null, is_string, remove_0x_prefix, text_if_str, to_checksum_address, ) from hexbytes import ( HexBytes, ) from web3._utils.abi import ( is_length, ) from web3._utils.encoding import ( hexstr_if_str, to_hex, ) from web3._utils.formatters import ( apply_formatter_at_index, apply_formatter_if, apply_formatter_to_array, apply_formatters_to_dict, apply_one_of_formatters, hex_to_integer, integer_to_hex, is_array_of_dicts, is_array_of_strings, remove_key_if, ) from web3._utils.toolz import ( complement, compose, curry, partial, ) from web3._utils.toolz.curried import ( keymap, valmap, ) from .formatting import ( construct_formatting_middleware, ) def bytes_to_ascii(value): return codecs.decode(value, 'ascii') to_ascii_if_bytes = apply_formatter_if(is_bytes, bytes_to_ascii) to_integer_if_hex = apply_formatter_if(is_string, hex_to_integer) block_number_formatter = apply_formatter_if(is_integer, integer_to_hex) is_false = partial(operator.is_, False) is_not_false = complement(is_false) is_not_null = complement(is_null) @curry def to_hexbytes(num_bytes, val, variable_length=False): if isinstance(val, (str, int, bytes)): result = HexBytes(val) else: raise TypeError("Cannot convert %r to HexBytes" % val) extra_bytes = len(result) - num_bytes if extra_bytes == 0 or (variable_length and extra_bytes < 0): return result elif all(byte == 0 for byte in result[:extra_bytes]): return HexBytes(result[extra_bytes:]) else: raise ValueError( "The value %r is %d bytes, but should be %d" % ( result, len(result), num_bytes ) ) TRANSACTION_FORMATTERS = { 'blockHash': apply_formatter_if(is_not_null, to_hexbytes(32)), 'blockNumber': apply_formatter_if(is_not_null, to_integer_if_hex), 'transactionIndex': apply_formatter_if(is_not_null, to_integer_if_hex), 'nonce': to_integer_if_hex, 'gas': to_integer_if_hex, 'gasPrice': to_integer_if_hex, 'value': to_integer_if_hex, 'from': to_checksum_address, 'publicKey': apply_formatter_if(is_not_null, to_hexbytes(64)), 'r': to_hexbytes(32, variable_length=True), 'raw': HexBytes, 's': to_hexbytes(32, variable_length=True), 'to': apply_formatter_if(is_address, to_checksum_address), 'hash': to_hexbytes(32), 'v': apply_formatter_if(is_not_null, to_integer_if_hex), 'standardV': apply_formatter_if(is_not_null, to_integer_if_hex), } transaction_formatter = apply_formatters_to_dict(TRANSACTION_FORMATTERS) WHISPER_LOG_FORMATTERS = { 'sig': to_hexbytes(130), 'topic': to_hexbytes(8), 'payload': HexBytes, 'padding': apply_formatter_if(is_not_null, HexBytes), 'hash': to_hexbytes(64), 'recipientPublicKey': apply_formatter_if(is_not_null, to_hexbytes(130)), } whisper_log_formatter = apply_formatters_to_dict(WHISPER_LOG_FORMATTERS) LOG_ENTRY_FORMATTERS = { 'blockHash': apply_formatter_if(is_not_null, to_hexbytes(32)), 'blockNumber': apply_formatter_if(is_not_null, to_integer_if_hex), 'transactionIndex': apply_formatter_if(is_not_null, to_integer_if_hex), 'transactionHash': apply_formatter_if(is_not_null, to_hexbytes(32)), 'logIndex': to_integer_if_hex, 'address': to_checksum_address, 'topics': apply_formatter_to_array(to_hexbytes(32)), 'data': to_ascii_if_bytes, } log_entry_formatter = apply_formatters_to_dict(LOG_ENTRY_FORMATTERS) RECEIPT_FORMATTERS = { 'blockHash': apply_formatter_if(is_not_null, to_hexbytes(32)), 'blockNumber': apply_formatter_if(is_not_null, to_integer_if_hex), 'transactionIndex': apply_formatter_if(is_not_null, to_integer_if_hex), 'transactionHash': to_hexbytes(32), 'cumulativeGasUsed': to_integer_if_hex, 'status': to_integer_if_hex, 'gasUsed': to_integer_if_hex, 'contractAddress': apply_formatter_if(is_not_null, to_checksum_address), 'logs': apply_formatter_to_array(log_entry_formatter), 'logsBloom': to_hexbytes(256), } receipt_formatter = apply_formatters_to_dict(RECEIPT_FORMATTERS) BLOCK_FORMATTERS = { 'extraData': to_hexbytes(32, variable_length=True), 'gasLimit': to_integer_if_hex, 'gasUsed': to_integer_if_hex, 'size': to_integer_if_hex, 'timestamp': to_integer_if_hex, 'hash': apply_formatter_if(is_not_null, to_hexbytes(32)), 'logsBloom': to_hexbytes(256), 'miner': apply_formatter_if(is_not_null, to_checksum_address), 'mixHash': to_hexbytes(32), 'nonce': apply_formatter_if(is_not_null, to_hexbytes(8, variable_length=True)), 'number': apply_formatter_if(is_not_null, to_integer_if_hex), 'parentHash': apply_formatter_if(is_not_null, to_hexbytes(32)), 'sha3Uncles': apply_formatter_if(is_not_null, to_hexbytes(32)), 'uncles': apply_formatter_to_array(to_hexbytes(32)), 'difficulty': to_integer_if_hex, 'receiptsRoot': to_hexbytes(32), 'stateRoot': to_hexbytes(32), 'totalDifficulty': to_integer_if_hex, 'transactions': apply_one_of_formatters(( (apply_formatter_to_array(transaction_formatter), is_array_of_dicts), (apply_formatter_to_array(to_hexbytes(32)), is_array_of_strings), )), 'transactionsRoot': to_hexbytes(32), } block_formatter = apply_formatters_to_dict(BLOCK_FORMATTERS) SYNCING_FORMATTERS = { 'startingBlock': to_integer_if_hex, 'currentBlock': to_integer_if_hex, 'highestBlock': to_integer_if_hex, 'knownStates': to_integer_if_hex, 'pulledStates': to_integer_if_hex, } syncing_formatter = apply_formatters_to_dict(SYNCING_FORMATTERS) TRANSACTION_POOL_CONTENT_FORMATTERS = { 'pending': compose( keymap(to_ascii_if_bytes), valmap(transaction_formatter), ), 'queued': compose( keymap(to_ascii_if_bytes), valmap(transaction_formatter), ), } transaction_pool_content_formatter = apply_formatters_to_dict( TRANSACTION_POOL_CONTENT_FORMATTERS ) TRANSACTION_POOL_INSPECT_FORMATTERS = { 'pending': keymap(to_ascii_if_bytes), 'queued': keymap(to_ascii_if_bytes), } transaction_pool_inspect_formatter = apply_formatters_to_dict( TRANSACTION_POOL_INSPECT_FORMATTERS ) FILTER_PARAMS_FORMATTERS = { 'fromBlock': apply_formatter_if(is_integer, integer_to_hex), 'toBlock': apply_formatter_if(is_integer, integer_to_hex), } filter_params_formatter = apply_formatters_to_dict(FILTER_PARAMS_FORMATTERS) filter_result_formatter = apply_one_of_formatters(( (apply_formatter_to_array(log_entry_formatter), is_array_of_dicts), (apply_formatter_to_array(to_hexbytes(32)), is_array_of_strings), )) TRANSACTION_PARAM_FORMATTERS = { 'chainId': apply_formatter_if(is_integer, str), } transaction_param_formatter = compose( remove_key_if('to', lambda txn: txn['to'] in {'', b'', None}), apply_formatters_to_dict(TRANSACTION_PARAM_FORMATTERS), ) estimate_gas_without_block_id = apply_formatter_at_index(transaction_param_formatter, 0) estimate_gas_with_block_id = combine_argument_formatters( transaction_param_formatter, block_number_formatter, ) pythonic_middleware = construct_formatting_middleware( request_formatters={ # Eth 'eth_getBalance': apply_formatter_at_index(block_number_formatter, 1), 'eth_getBlockByNumber': apply_formatter_at_index(block_number_formatter, 0), 'eth_getBlockTransactionCountByNumber': apply_formatter_at_index( block_number_formatter, 0, ), 'eth_getCode': apply_formatter_at_index(block_number_formatter, 1), 'eth_getStorageAt': apply_formatter_at_index(block_number_formatter, 2), 'eth_getTransactionByBlockNumberAndIndex': compose( apply_formatter_at_index(block_number_formatter, 0), apply_formatter_at_index(integer_to_hex, 1), ), 'eth_getTransactionCount': apply_formatter_at_index(block_number_formatter, 1), 'eth_getUncleCountByBlockNumber': apply_formatter_at_index(block_number_formatter, 0), 'eth_getUncleByBlockNumberAndIndex': compose( apply_formatter_at_index(block_number_formatter, 0), apply_formatter_at_index(integer_to_hex, 1), ), 'eth_getUncleByBlockHashAndIndex': apply_formatter_at_index(integer_to_hex, 1), 'eth_newFilter': apply_formatter_at_index(filter_params_formatter, 0), 'eth_getLogs': apply_formatter_at_index(filter_params_formatter, 0), 'eth_call': combine_argument_formatters( transaction_param_formatter, block_number_formatter, ), 'eth_estimateGas': apply_one_of_formatters(( (estimate_gas_without_block_id, is_length(1)), (estimate_gas_with_block_id, is_length(2)), )), 'eth_sendTransaction': apply_formatter_at_index(transaction_param_formatter, 0), # personal 'personal_importRawKey': apply_formatter_at_index( compose(remove_0x_prefix, hexstr_if_str(to_hex)), 0, ), 'personal_sign': apply_formatter_at_index(text_if_str(to_hex), 0), 'personal_ecRecover': apply_formatter_at_index(text_if_str(to_hex), 0), 'personal_sendTransaction': apply_formatter_at_index(transaction_param_formatter, 0), # Snapshot and Revert 'evm_revert': apply_formatter_at_index(integer_to_hex, 0), 'trace_replayBlockTransactions': apply_formatter_at_index(block_number_formatter, 0), 'trace_block': apply_formatter_at_index(block_number_formatter, 0), 'trace_call': compose( apply_formatter_at_index(transaction_param_formatter, 0), apply_formatter_at_index(block_number_formatter, 2) ), }, result_formatters={ # Eth 'eth_accounts': apply_formatter_to_array(to_checksum_address), 'eth_blockNumber': to_integer_if_hex, 'eth_coinbase': to_checksum_address, 'eth_estimateGas': to_integer_if_hex, 'eth_gasPrice': to_integer_if_hex, 'eth_getBalance': to_integer_if_hex, 'eth_getBlockByHash': apply_formatter_if(is_not_null, block_formatter), 'eth_getBlockByNumber': apply_formatter_if(is_not_null, block_formatter), 'eth_getBlockTransactionCountByHash': to_integer_if_hex, 'eth_getBlockTransactionCountByNumber': to_integer_if_hex, 'eth_getCode': HexBytes, 'eth_getFilterChanges': filter_result_formatter, 'eth_getFilterLogs': filter_result_formatter, 'eth_getLogs': filter_result_formatter, 'eth_getStorageAt': HexBytes, 'eth_getTransactionByBlockHashAndIndex': apply_formatter_if( is_not_null, transaction_formatter, ), 'eth_getTransactionByBlockNumberAndIndex': apply_formatter_if( is_not_null, transaction_formatter, ), 'eth_getTransactionByHash': apply_formatter_if(is_not_null, transaction_formatter), 'eth_getTransactionCount': to_integer_if_hex, 'eth_getTransactionReceipt': apply_formatter_if( is_not_null, receipt_formatter, ), 'eth_getUncleCountByBlockHash': to_integer_if_hex, 'eth_getUncleCountByBlockNumber': to_integer_if_hex, 'eth_hashrate': to_integer_if_hex, 'eth_protocolVersion': compose( apply_formatter_if(is_integer, str), to_integer_if_hex, ), 'eth_sendRawTransaction': to_hexbytes(32), 'eth_sendTransaction': to_hexbytes(32), 'eth_sign': HexBytes, 'eth_syncing': apply_formatter_if(is_not_false, syncing_formatter), # personal 'personal_importRawKey': to_checksum_address, 'personal_listAccounts': apply_formatter_to_array(to_checksum_address), 'personal_newAccount': to_checksum_address, 'personal_sendTransaction': to_hexbytes(32), # SHH 'shh_getFilterMessages': apply_formatter_to_array(whisper_log_formatter), # Transaction Pool 'txpool_content': transaction_pool_content_formatter, 'txpool_inspect': transaction_pool_inspect_formatter, # Snapshot and Revert 'evm_snapshot': hex_to_integer, # Net 'net_peerCount': to_integer_if_hex, }, )
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/middleware/pythonic.py
pythonic.py
from web3._utils.toolz import ( assoc, dissoc, ) def normalize_errors_middleware(make_request, web3): def middleware(method, params): result = make_request(method, params) # As of v1.8, Geth returns errors when you request a # receipt for a transaction that is not in the chain. # It used to return a result of None, so we simulate the old behavior. if method == 'eth_getTransactionReceipt' and 'error' in result: is_geth = web3.version.node.startswith('Geth') if is_geth and result['error']['code'] == -32000: return assoc( dissoc(result, 'error'), 'result', None, ) else: return result else: return result return middleware
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/middleware/normalize_errors.py
normalize_errors.py
from web3._utils.normalizers import ( abi_ens_resolver, ) from web3._utils.rpc_abi import ( RPC_ABIS, abi_request_formatters, ) from .formatting import ( construct_formatting_middleware, ) def name_to_address_middleware(w3): normalizers = [ abi_ens_resolver(w3), ] return construct_formatting_middleware( request_formatters=abi_request_formatters(normalizers, RPC_ABIS) )
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/middleware/names.py
names.py
import functools import threading import time import lru from web3._utils.caching import ( generate_cache_key, ) SIMPLE_CACHE_RPC_WHITELIST = { 'web3_clientVersion', 'web3_sha3', 'net_version', # 'net_peerCount', # 'net_listening', 'eth_protocolVersion', # 'eth_syncing', # 'eth_coinbase', # 'eth_mining', # 'eth_hashrate', # 'eth_gasPrice', # 'eth_accounts', # 'eth_blockNumber', # 'eth_getBalance', # 'eth_getStorageAt', # 'eth_getTransactionCount', 'eth_getBlockTransactionCountByHash', # 'eth_getBlockTransactionCountByNumber', 'eth_getUncleCountByBlockHash', # 'eth_getUncleCountByBlockNumber', # 'eth_getCode', # 'eth_sign', # 'eth_sendTransaction', # 'eth_sendRawTransaction', # 'eth_call', # 'eth_estimateGas', 'eth_getBlockByHash', # 'eth_getBlockByNumber', 'eth_getTransactionByHash', 'eth_getTransactionByBlockHashAndIndex', # 'eth_getTransactionByBlockNumberAndIndex', # 'eth_getTransactionReceipt', 'eth_getUncleByBlockHashAndIndex', # 'eth_getUncleByBlockNumberAndIndex', # 'eth_getCompilers', # 'eth_compileLLL', # 'eth_compileSolidity', # 'eth_compileSerpent', # 'eth_newFilter', # 'eth_newBlockFilter', # 'eth_newPendingTransactionFilter', # 'eth_uninstallFilter', # 'eth_getFilterChanges', # 'eth_getFilterLogs', # 'eth_getLogs', # 'eth_getWork', # 'eth_submitWork', # 'eth_submitHashrate', } def _should_cache(method, params, response): if 'error' in response: return False elif 'result' not in response: return False if response['result'] is None: return False return True def construct_simple_cache_middleware( cache_class, rpc_whitelist=SIMPLE_CACHE_RPC_WHITELIST, should_cache_fn=_should_cache): """ Constructs a middleware which caches responses based on the request ``method`` and ``params`` :param cache: Any dictionary-like object :param rpc_whitelist: A set of RPC methods which may have their responses cached. :param should_cache_fn: A callable which accepts ``method`` ``params`` and ``response`` and returns a boolean as to whether the response should be cached. """ def simple_cache_middleware(make_request, web3): cache = cache_class() lock = threading.Lock() def middleware(method, params): lock_acquired = lock.acquire(blocking=False) try: if lock_acquired and method in rpc_whitelist: cache_key = generate_cache_key((method, params)) if cache_key not in cache: response = make_request(method, params) if should_cache_fn(method, params, response): cache[cache_key] = response return response return cache[cache_key] else: return make_request(method, params) finally: if lock_acquired: lock.release() return middleware return simple_cache_middleware _simple_cache_middleware = construct_simple_cache_middleware( cache_class=functools.partial(lru.LRU, 256), ) TIME_BASED_CACHE_RPC_WHITELIST = { # 'web3_clientVersion', # 'web3_sha3', # 'net_version', # 'net_peerCount', # 'net_listening', # 'eth_protocolVersion', # 'eth_syncing', 'eth_coinbase', # 'eth_mining', # 'eth_hashrate', # 'eth_gasPrice', 'eth_accounts', # 'eth_blockNumber', # 'eth_getBalance', # 'eth_getStorageAt', # 'eth_getTransactionCount', # 'eth_getBlockTransactionCountByHash', # 'eth_getBlockTransactionCountByNumber', # 'eth_getUncleCountByBlockHash', # 'eth_getUncleCountByBlockNumber', # 'eth_getCode', # 'eth_sign', # 'eth_sendTransaction', # 'eth_sendRawTransaction', # 'eth_call', # 'eth_estimateGas', # 'eth_getBlockByHash', # 'eth_getBlockByNumber', # 'eth_getTransactionByHash', # 'eth_getTransactionByBlockHashAndIndex', # 'eth_getTransactionByBlockNumberAndIndex', # 'eth_getTransactionReceipt', # 'eth_getUncleByBlockHashAndIndex', # 'eth_getUncleByBlockNumberAndIndex', # 'eth_getCompilers', # 'eth_compileLLL', # 'eth_compileSolidity', # 'eth_compileSerpent', # 'eth_newFilter', # 'eth_newBlockFilter', # 'eth_newPendingTransactionFilter', # 'eth_uninstallFilter', # 'eth_getFilterChanges', # 'eth_getFilterLogs', # 'eth_getLogs', # 'eth_getWork', # 'eth_submitWork', # 'eth_submitHashrate', } def construct_time_based_cache_middleware( cache_class, cache_expire_seconds=15, rpc_whitelist=TIME_BASED_CACHE_RPC_WHITELIST, should_cache_fn=_should_cache): """ Constructs a middleware which caches responses based on the request ``method`` and ``params`` for a maximum amount of time as specified :param cache: Any dictionary-like object :param cache_expire_seconds: The number of seconds an item may be cached before it should expire. :param rpc_whitelist: A set of RPC methods which may have their responses cached. :param should_cache_fn: A callable which accepts ``method`` ``params`` and ``response`` and returns a boolean as to whether the response should be cached. """ def time_based_cache_middleware(make_request, web3): cache = cache_class() lock = threading.Lock() def middleware(method, params): lock_acquired = lock.acquire(blocking=False) try: if lock_acquired and method in rpc_whitelist: cache_key = generate_cache_key((method, params)) if cache_key in cache: # check that the cached response is not expired. cached_at, cached_response = cache[cache_key] cached_for = time.time() - cached_at if cached_for <= cache_expire_seconds: return cached_response else: del cache[cache_key] # cache either missed or expired so make the request. response = make_request(method, params) if should_cache_fn(method, params, response): cache[cache_key] = (time.time(), response) return response else: return make_request(method, params) finally: if lock_acquired: lock.release() return middleware return time_based_cache_middleware _time_based_cache_middleware = construct_time_based_cache_middleware( cache_class=functools.partial(lru.LRU, 256), ) BLOCK_NUMBER_RPC_WHITELIST = { # 'web3_clientVersion', # 'web3_sha3', # 'net_version', # 'net_peerCount', # 'net_listening', # 'eth_protocolVersion', # 'eth_syncing', # 'eth_coinbase', # 'eth_mining', # 'eth_hashrate', 'eth_gasPrice', # 'eth_accounts', 'eth_blockNumber', 'eth_getBalance', 'eth_getStorageAt', 'eth_getTransactionCount', # 'eth_getBlockTransactionCountByHash', 'eth_getBlockTransactionCountByNumber', # 'eth_getUncleCountByBlockHash', 'eth_getUncleCountByBlockNumber', 'eth_getCode', # 'eth_sign', # 'eth_sendTransaction', # 'eth_sendRawTransaction', 'eth_call', 'eth_estimateGas', # 'eth_getBlockByHash', 'eth_getBlockByNumber', # 'eth_getTransactionByHash', # 'eth_getTransactionByBlockHashAndIndex', 'eth_getTransactionByBlockNumberAndIndex', 'eth_getTransactionReceipt', # 'eth_getUncleByBlockHashAndIndex', 'eth_getUncleByBlockNumberAndIndex', # 'eth_getCompilers', # 'eth_compileLLL', # 'eth_compileSolidity', # 'eth_compileSerpent', # 'eth_newFilter', # 'eth_newBlockFilter', # 'eth_newPendingTransactionFilter', # 'eth_uninstallFilter', # 'eth_getFilterChanges', # 'eth_getFilterLogs', 'eth_getLogs', # 'eth_getWork', # 'eth_submitWork', # 'eth_submitHashrate', } AVG_BLOCK_TIME_KEY = 'avg_block_time' AVG_BLOCK_SAMPLE_SIZE_KEY = 'avg_block_sample_size' AVG_BLOCK_TIME_UPDATED_AT_KEY = 'avg_block_time_updated_at' def _is_latest_block_number_request(method, params): if method != 'eth_getBlockByNumber': return False elif params[:1] == ['latest']: return True return False def construct_latest_block_based_cache_middleware( cache_class, rpc_whitelist=BLOCK_NUMBER_RPC_WHITELIST, average_block_time_sample_size=240, default_average_block_time=15, should_cache_fn=_should_cache): """ Constructs a middleware which caches responses based on the request ``method``, ``params``, and the current latest block hash. :param cache: Any dictionary-like object :param cache_expire_seconds: The number of seconds an item may be cached before it should expire. :param rpc_whitelist: A set of RPC methods which may have their responses cached. :param should_cache_fn: A callable which accepts ``method`` ``params`` and ``response`` and returns a boolean as to whether the response should be cached. .. note:: This middleware avoids re-fetching the current latest block for each request by tracking the current average block time and only requesting a new block when the last seen latest block is older than the average block time. """ def latest_block_based_cache_middleware(make_request, web3): cache = cache_class() block_info = {} def _update_block_info_cache(): avg_block_time = block_info.get(AVG_BLOCK_TIME_KEY, default_average_block_time) avg_block_sample_size = block_info.get(AVG_BLOCK_SAMPLE_SIZE_KEY, 0) avg_block_time_updated_at = block_info.get(AVG_BLOCK_TIME_UPDATED_AT_KEY, 0) # compute age as counted by number of blocks since the avg_block_time if avg_block_time == 0: avg_block_time_age_in_blocks = avg_block_sample_size else: avg_block_time_age_in_blocks = ( (time.time() - avg_block_time_updated_at) / avg_block_time ) if avg_block_time_age_in_blocks >= avg_block_sample_size: # If the length of time since the average block time as # measured by blocks is greater than or equal to the number of # blocks sampled then we need to recompute the average block # time. latest_block = web3.eth.getBlock('latest') ancestor_block_number = max( 0, latest_block['number'] - average_block_time_sample_size, ) ancestor_block = web3.eth.getBlock(ancestor_block_number) sample_size = latest_block['number'] - ancestor_block_number block_info[AVG_BLOCK_SAMPLE_SIZE_KEY] = sample_size if sample_size != 0: block_info[AVG_BLOCK_TIME_KEY] = ( (latest_block['timestamp'] - ancestor_block['timestamp']) / sample_size ) else: block_info[AVG_BLOCK_TIME_KEY] = avg_block_time block_info[AVG_BLOCK_TIME_UPDATED_AT_KEY] = time.time() if 'latest_block' in block_info: latest_block = block_info['latest_block'] time_since_latest_block = time.time() - latest_block['timestamp'] # latest block is too old so update cache if time_since_latest_block > avg_block_time: block_info['latest_block'] = web3.eth.getBlock('latest') else: # latest block has not been fetched so we fetch it. block_info['latest_block'] = web3.eth.getBlock('latest') lock = threading.Lock() def middleware(method, params): lock_acquired = lock.acquire(blocking=False) try: should_try_cache = ( lock_acquired and method in rpc_whitelist and not _is_latest_block_number_request(method, params) ) if should_try_cache: _update_block_info_cache() latest_block_hash = block_info['latest_block']['hash'] cache_key = generate_cache_key((latest_block_hash, method, params)) if cache_key in cache: return cache[cache_key] response = make_request(method, params) if should_cache_fn(method, params, response): cache[cache_key] = response return response else: return make_request(method, params) finally: if lock_acquired: lock.release() return middleware return latest_block_based_cache_middleware _latest_block_based_cache_middleware = construct_latest_block_based_cache_middleware( cache_class=functools.partial(lru.LRU, 256), rpc_whitelist=BLOCK_NUMBER_RPC_WHITELIST, )
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/middleware/cache.py
cache.py
from web3._utils.toolz import ( excepts, ) def construct_exception_handler_middleware(method_handlers=None): if method_handlers is None: method_handlers = {} def exception_handler_middleware(make_request, web3): def middleware(method, params): if method in method_handlers: exc_type, handler = method_handlers[method] return excepts( exc_type, make_request, handler, )(method, params) else: return make_request(method, params) return middleware return exception_handler_middleware
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/middleware/exception_handling.py
exception_handling.py
from web3._utils.toolz import ( assoc, curry, merge, ) def construct_formatting_middleware( request_formatters=None, result_formatters=None, error_formatters=None): def ignore_web3_in_standard_formatters(w3): return dict( request_formatters=request_formatters or {}, result_formatters=result_formatters or {}, error_formatters=error_formatters or {}, ) return construct_web3_formatting_middleware(ignore_web3_in_standard_formatters) def construct_web3_formatting_middleware(web3_formatters_builder): def formatter_middleware(make_request, w3): formatters = merge( { 'request_formatters': {}, 'result_formatters': {}, 'error_formatters': {}, }, web3_formatters_builder(w3), ) return apply_formatters(make_request=make_request, **formatters) return formatter_middleware @curry def apply_formatters( method, params, make_request, request_formatters, result_formatters, error_formatters): if method in request_formatters: formatter = request_formatters[method] formatted_params = formatter(params) response = make_request(method, formatted_params) else: response = make_request(method, params) if 'result' in response and method in result_formatters: formatter = result_formatters[method] formatted_response = assoc( response, 'result', formatter(response['result']), ) return formatted_response elif 'error' in response and method in error_formatters: formatter = error_formatters[method] formatted_response = assoc( response, 'error', formatter(response['error']), ) return formatted_response else: return response
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/middleware/formatting.py
formatting.py
from eth_utils.curried import ( apply_formatter_at_index, apply_formatter_if, apply_formatters_to_dict, is_null, ) from hexbytes import ( HexBytes, ) from web3._utils.toolz import ( complement, compose, curry, dissoc, ) from web3.exceptions import ( ValidationError, ) from web3.middleware.formatting import ( construct_web3_formatting_middleware, ) MAX_EXTRADATA_LENGTH = 32 is_not_null = complement(is_null) @curry def validate_chain_id(web3, chain_id): if chain_id == web3.net.chainId: return chain_id else: raise ValidationError( "The transaction declared chain ID %r, " "but the connected node is on %r" % ( chain_id, "UNKNOWN", ) ) def check_extradata_length(val): if not isinstance(val, (str, int, bytes)): return val result = HexBytes(val) if len(result) > MAX_EXTRADATA_LENGTH: raise ValidationError( "The field extraData is %d bytes, but should be %d. " "It is quite likely that you are connected to a POA chain. " "Refer " "http://web3py.readthedocs.io/en/stable/middleware.html#geth-style-proof-of-authority " "for more details. The full extraData is: %r" % ( len(result), MAX_EXTRADATA_LENGTH, result ) ) return val def transaction_normalizer(transaction): return dissoc(transaction, 'chainId') def transaction_param_validator(web3): transactions_params_validators = { 'chainId': apply_formatter_if( # Bypass `validate_chain_id` if chainId can't be determined lambda _: is_not_null(web3.net.chainId), validate_chain_id(web3) ), } return apply_formatter_at_index( apply_formatters_to_dict(transactions_params_validators), 0 ) BLOCK_VALIDATORS = { 'extraData': check_extradata_length, } block_validator = apply_formatter_if( is_not_null, apply_formatters_to_dict(BLOCK_VALIDATORS) ) @curry def chain_id_validator(web3): return compose( apply_formatter_at_index(transaction_normalizer, 0), transaction_param_validator(web3) ) def build_validators_with_web3(w3): return dict( request_formatters={ 'eth_sendTransaction': chain_id_validator(w3), 'eth_estimateGas': chain_id_validator(w3), 'eth_call': chain_id_validator(w3), }, result_formatters={ 'eth_getBlockByHash': block_validator, 'eth_getBlockByNumber': block_validator, }, ) validation_middleware = construct_web3_formatting_middleware(build_validators_with_web3)
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/middleware/validation.py
validation.py
import time from web3.exceptions import ( StaleBlockchain, ) SKIP_STALECHECK_FOR_METHODS = set([ 'eth_getBlockByNumber', ]) def _isfresh(block, allowable_delay): return block and time.time() - block['timestamp'] <= allowable_delay def make_stalecheck_middleware( allowable_delay, skip_stalecheck_for_methods=SKIP_STALECHECK_FOR_METHODS): """ Use to require that a function will run only of the blockchain is recently updated. This middleware takes an argument, so unlike other middleware, you must make the middleware with a method call. For example: `make_stalecheck_middleware(60*5)` If the latest block in the chain is older than 5 minutes in this example, then the middleware will raise a StaleBlockchain exception. """ if allowable_delay <= 0: raise ValueError("You must set a positive allowable_delay in seconds for this middleware") def stalecheck_middleware(make_request, web3): cache = {'latest': None} def middleware(method, params): if method not in skip_stalecheck_for_methods: if _isfresh(cache['latest'], allowable_delay): pass else: latest = web3.eth.getBlock('latest') if _isfresh(latest, allowable_delay): cache['latest'] = latest else: raise StaleBlockchain(latest, allowable_delay) return make_request(method, params) return middleware return stalecheck_middleware
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/middleware/stalecheck.py
stalecheck.py
import itertools import os from eth_utils import ( apply_key_map, to_hex, to_list, ) from web3._utils.toolz import ( concat, valfilter, ) if 'WEB3_MAX_BLOCK_REQUEST' in os.environ: MAX_BLOCK_REQUEST = os.environ['WEB3_MAX_BLOCK_REQUEST'] else: MAX_BLOCK_REQUEST = 50 def segment_count(start, stop, step=5): """Creates a segment counting generator The generator returns tuple pairs of integers that correspond to segments in the provided range. :param start: The initial value of the counting range :param stop: The last value in the counting range :param step: Optional, the segment length. Default is 5. :type start: int :type stop: int :return: returns a generator object Example: >>> segment_counter = segment_count(start=0, stop=10, step=3) >>> next(segment_counter) (0, 3) >>> next(segment_counter) (3, 6) >>> next(segment_counter) (6, 9) >>> next(segment_counter) # Remainder is also returned (9, 10) """ return gen_bounded_segments(start, stop, step) def gen_bounded_segments(start, stop, step): # If the initial range is less than the step # just return (start, stop) if start + step >= stop: yield (start, stop) return for segment in zip( range(start, stop - step + 1, step), range(start + step, stop + 1, step)): yield segment remainder = (stop - start) % step # Handle the remainder if remainder: yield (stop - remainder, stop) def block_ranges(start_block, last_block, step=5): """Returns 2-tuple ranges describing ranges of block from start_block to last_block Ranges do not overlap to facilitate use as ``toBlock``, ``fromBlock`` json-rpc arguments, which are both inclusive. """ if last_block is not None and start_block > last_block: raise TypeError( "Incompatible start and stop arguments.", "Start must be less than or equal to stop.") return ( (from_block, to_block - 1) for from_block, to_block in segment_count(start_block, last_block + 1, step) ) def iter_latest_block(w3, to_block=None): """Returns a generator that dispenses the latest block, if any new blocks have been mined since last iteration. If there are no new blocks None is returned. If ``to_block`` is defined, ``StopIteration`` is raised after to_block is reached. >>> mined_blocks = dispense_mined_blocks(w3, 0, 10) >>> next(new_blocks) # Latest block = 0 0 >>> next(new_blocks) # No new blocks >>> next(new_blocks) # Latest block = 1 1 >>> next(new_blocks) # Latest block = 10 10 >>> next(new_blocks) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>> """ _last = None is_bounded_range = ( to_block is not None and to_block is not 'latest' ) while True: latest_block = w3.eth.blockNumber if is_bounded_range and latest_block > to_block: return # No new blocks since last iteration. if _last is not None and _last == latest_block: yield None else: yield latest_block _last = latest_block def iter_latest_block_ranges(w3, from_block, to_block=None): """Returns an iterator unloading ranges of available blocks starting from `fromBlock` to the latest mined block, until reaching toBlock. e.g.: >>> blocks_to_filter = iter_latest_block_ranges(w3, 0, 50) >>> next(blocks_to_filter) # latest block number = 11 (0, 11) >>> next(blocks_to_filter) # latest block number = 45 (12, 45) >>> next(blocks_to_filter) # latest block number = 50 (46, 50) """ for latest_block in iter_latest_block(w3, to_block): if latest_block is None: yield (None, None) elif from_block > latest_block: yield (None, None) else: yield (from_block, latest_block) from_block = latest_block + 1 def drop_items_with_none_value(params): return valfilter(lambda x: x is not None, params) def get_logs_multipart( w3, startBlock, stopBlock, address, topics, max_blocks): """Used to break up requests to ``eth_getLogs`` The getLog request is partitioned into multiple calls of the max number of blocks ``max_blocks``. """ _block_ranges = block_ranges(startBlock, stopBlock, max_blocks) for from_block, to_block in _block_ranges: params = { 'fromBlock': from_block, 'toBlock': to_block, 'address': address, 'topics': topics } yield w3.eth.getLogs( drop_items_with_none_value(params)) class RequestLogs: def __init__( self, w3, from_block=None, to_block=None, address=None, topics=None): self.address = address self.topics = topics self.w3 = w3 if from_block is None or from_block == 'latest': self._from_block = w3.eth.blockNumber + 1 else: self._from_block = from_block self._to_block = to_block self.filter_changes = self._get_filter_changes() @property def from_block(self): return self._from_block @property def to_block(self): if self._to_block is None: to_block = self.w3.eth.blockNumber elif self._to_block == 'latest': to_block = self.w3.eth.blockNumber else: to_block = self._to_block return to_block def _get_filter_changes(self): for start, stop in iter_latest_block_ranges(self.w3, self.from_block, self.to_block): if None in (start, stop): yield [] yield list( concat( get_logs_multipart( self.w3, start, stop, self.address, self.topics, max_blocks=MAX_BLOCK_REQUEST))) def get_logs(self): return list( concat( get_logs_multipart( self.w3, self.from_block, self.to_block, self.address, self.topics, max_blocks=MAX_BLOCK_REQUEST))) FILTER_PARAMS_KEY_MAP = { 'toBlock': 'to_block', 'fromBlock': 'from_block' } NEW_FILTER_METHODS = set([ 'eth_newBlockFilter', 'eth_newFilter']) FILTER_CHANGES_METHODS = set([ 'eth_getFilterChanges', 'eth_getFilterLogs']) class RequestBlocks: def __init__(self, w3): self.w3 = w3 self.start_block = w3.eth.blockNumber + 1 @property def filter_changes(self): return self.get_filter_changes() def get_filter_changes(self): block_range_iter = iter_latest_block_ranges( self.w3, self.start_block, None) for block_range in block_range_iter: yield(block_hashes_in_range(self.w3, block_range)) @to_list def block_hashes_in_range(w3, block_range): from_block, to_block = block_range for block_number in range(from_block, to_block + 1): yield getattr(w3.eth.getBlock(block_number), 'hash', None) def local_filter_middleware(make_request, w3): filters = {} filter_id_counter = map(to_hex, itertools.count()) def middleware(method, params): if method in NEW_FILTER_METHODS: filter_id = next(filter_id_counter) if method == 'eth_newFilter': _filter = RequestLogs(w3, **apply_key_map(FILTER_PARAMS_KEY_MAP, params[0])) elif method == 'eth_newBlockFilter': _filter = RequestBlocks(w3) else: raise NotImplementedError(method) filters[filter_id] = _filter return {'result': filter_id} elif method in FILTER_CHANGES_METHODS: filter_id = params[0] # Pass through to filters not created by middleware if filter_id not in filters: return make_request(method, params) _filter = filters[filter_id] if method == 'eth_getFilterChanges': return {'result': next(_filter.filter_changes)} elif method == 'eth_getFilterLogs': return {'result': _filter.get_logs()} else: raise NotImplementedError(method) else: return make_request(method, params) return middleware
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/middleware/filter.py
filter.py
import collections import itertools counter = itertools.count() INVOCATIONS_BEFORE_RESULT = 5 def unmined_receipt_simulator_middleware(make_request, web3): receipt_counters = collections.defaultdict(itertools.count) def middleware(method, params): if method == 'eth_getTransactionReceipt': txn_hash = params[0] if next(receipt_counters[txn_hash]) < INVOCATIONS_BEFORE_RESULT: return {'result': None} else: return make_request(method, params) else: return make_request(method, params) return middleware
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/middleware/simulate_unmined_transaction.py
simulate_unmined_transaction.py
from eth_utils.curried import ( apply_formatters_to_dict, apply_key_map, ) from hexbytes import ( HexBytes, ) from web3._utils.toolz import ( compose, ) from web3.middleware.formatting import ( construct_formatting_middleware, ) remap_geth_poa_fields = apply_key_map({ 'extraData': 'proofOfAuthorityData', }) pythonic_geth_poa = apply_formatters_to_dict({ 'proofOfAuthorityData': HexBytes, }) geth_poa_cleanup = compose(pythonic_geth_poa, remap_geth_poa_fields) geth_poa_middleware = construct_formatting_middleware( result_formatters={ 'eth_getBlockByHash': geth_poa_cleanup, 'eth_getBlockByNumber': geth_poa_cleanup, }, )
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/middleware/geth_poa.py
geth_poa.py
from eth_utils import ( is_dict, ) from web3._utils.toolz import ( assoc, ) from web3.datastructures import ( AttributeDict, ) def attrdict_middleware(make_request, web3): """ Converts any result which is a dictionary into an a """ def middleware(method, params): response = make_request(method, params) if 'result' in response: result = response['result'] if is_dict(result) and not isinstance(result, AttributeDict): return assoc(response, 'result', AttributeDict.recursive(result)) else: return response else: return response return middleware
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/middleware/attrdict.py
attrdict.py
from web3._utils.normalizers import ( abi_address_to_hex, abi_bytes_to_hex, abi_int_to_hex, abi_string_to_hex, ) from web3._utils.rpc_abi import ( RPC_ABIS, abi_request_formatters, ) from .formatting import ( construct_formatting_middleware, ) STANDARD_NORMALIZERS = [ abi_bytes_to_hex, abi_int_to_hex, abi_string_to_hex, abi_address_to_hex, ] abi_middleware = construct_formatting_middleware( request_formatters=abi_request_formatters(STANDARD_NORMALIZERS, RPC_ABIS) )
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/middleware/abi.py
abi.py