def __init__( self, exchange_address: str, maker_address: str, taker_address: str, maker_token: str, taker_token: str, fee_recipient: str, maker_token_amount: int, taker_token_amount: int, maker_fee: int, taker_fee: int, expiration_timestamp_in_sec: int, salt: int, ) -> None: super().__init__( exchange_address, maker_address, taker_address, maker_token, taker_token, fee_recipient, maker_token_amount, taker_token_amount, maker_fee, taker_fee, expiration_timestamp_in_sec, salt, v=0, r=hexbytes.HexBytes(b""), s=hexbytes.HexBytes(b""), )
def get(self, order_hash: str): abort_if_invalid_order_hash(order_hash) order = self.trustlines.orderbook.get_order_by_hash( hexbytes.HexBytes(order_hash)) if order is None: abort(404, message="Order does not exist") return order
def _deserialize(self, value, attr, data, **kwargs): try: hex_bytes = hexbytes.HexBytes(value) except ValueError: raise ValidationError("Could not parse Hex number") return hex_bytes
class MetaTransactionSchema(Schema): class Meta: strict = True def _validate(self, data): nonce = data["nonce"] fees = data["fees"] signature = data["signature"] if not 0 <= nonce < 2**256: raise ValidationError(f"nonce={nonce} is out of bounds") if not 0 <= fees < 2**64: raise ValidationError(f"delegationFees={fees} is out of bounds") if len(signature) != 65 and signature != hexbytes.HexBytes(""): raise ValidationError("signature must be 65 bytes") value = data["value"] if not 0 <= value < 2**256: raise ValidationError(f"value={value} is out of bounds") @post_load def make_meta_transaction(self, data, partial, many): self._validate(data) return identity.MetaTransaction(**data) from_ = Address(required=True, data_key="from") to = Address(required=True) value = BigInteger(required=True) data = HexEncodedBytes(required=True) delegationFees = BigInteger(missing=0, attribute="fees") currencyNetworkOfFees = Address(missing=to, attribute="currency_network_of_fees") nonce = BigInteger(required=True) extraData = HexEncodedBytes(required=True, attribute="extra_data") signature = HexEncodedBytes(missing=hexbytes.HexBytes(""))
def _field_to_hexbytes(field_value) -> hexbytes.HexBytes: # NOTE: Some fields are of type HexBytes since web3 v4. It can also be a hex string because # the indexer currently can not save bytes in the database. # See issue https://github.com/trustlines-protocol/py-eth-index/issues/16 if not isinstance(field_value, hexbytes.HexBytes): return hexbytes.HexBytes(field_value) else: return field_value
def extra_data(self): extra_data = self._web3_event.get("args").get("_extraData") # NOTE: The argument extraData can be a hex string because the indexer currently can # not save bytes in the database. See issue https://github.com/trustlines-protocol/py-eth-index/issues/16 if not isinstance(extra_data, hexbytes.HexBytes): return hexbytes.HexBytes(extra_data) else: return extra_data
def _get_abi_for_log(self, raw_event_log): topic = hexbytes.HexBytes(raw_event_log["topics"][0]) event_abi = self._topic2event_abi.get(topic) if event_abi is None: raise AbiNotFoundException( f"Could not find event abi for log {raw_event_log} on contract {self.address}. " f"{topic} not in {self._topic2event_abi.keys()}") return event_abi
def convert_event_data(cls, event_type, data): if event_type == 'NewListing': return int(data, 0) elif event_type == 'ListingPurchased': addr = decode_single('address', hexbytes.HexBytes(data)) return to_checksum_address(addr) elif event_type == 'PurchaseChange': return int(data, 0)
def decode_non_indexed_inputs(abi, log): """decode non-indexed inputs from a log entry This one decodes the values stored in the 'data' field.""" inputs = [input_ for input_ in abi["inputs"] if not input_["indexed"]] types = [input_["type"] for input_ in inputs] names = [input_["name"] for input_ in inputs] data = hexbytes.HexBytes(log["data"]) values = eth_abi.decode_abi(types, data) return zip(names, replace_with_checksum_address(values, types))
def __init__(self, web3, abi, address: str = None) -> None: self._web3 = web3 self._proxy = web3.eth.contract(abi=abi, address=address) self.address = address self._event2log_queue: Dict[str, Queue] = defaultdict(Queue) self._topic2event_abi = { hexbytes.HexBytes(eth_utils.event_abi_to_log_topic(event_abi)): event_abi for event_abi in self._proxy.events._events } self._log_listener: Optional[LogFilterListener] = None
def __init__(self, address2abi): """build a TopicIndex from an contract address to ABI dict""" self.addresses = list(address2abi.keys()) self.address2abi = address2abi self.address_topic2event_abi = {} for address, abi in self.address2abi.items(): for event_abi in get_event_abis(abi): self.address_topic2event_abi[( address, hexbytes.HexBytes( eth_utils.event_abi_to_log_topic(event_abi)), )] = event_abi
def _deserialize(self, value, attr, data, **kwargs): if not (isinstance(value, str) and value.startswith("0x")): raise ValidationError( f"Could not parse hex-encoded bytes objects of attribute {attr}: {value}" ) try: # Create bytes first, to not use weird conversion done by hexbytes constructor return hexbytes.HexBytes(bytes.fromhex(value[2:])) except ValueError: raise ValidationError( f"Could not parse hex-encoded bytes objects of attribute {attr}: {value}" )
def to_order(self) -> Order: return Order( exchange_address=self.exchange_address, maker_address=self.maker_address, taker_address=self.taker_address, maker_token=self.maker_token, taker_token=self.taker_token, fee_recipient=self.fee_recipient, maker_token_amount=self.maker_token_amount, taker_token_amount=self.taker_token_amount, filled_maker_token_amount=self.filled_maker_token_amount, filled_taker_token_amount=self.filled_taker_token_amount, cancelled_maker_token_amount=self.cancelled_maker_token_amount, cancelled_taker_token_amount=self.cancelled_taker_token_amount, maker_fee=self.maker_fee, taker_fee=self.taker_fee, expiration_timestamp_in_sec=self.expiration_timestamp_in_sec, salt=self.salt, v=self.v, r=hexbytes.HexBytes(self.r), s=hexbytes.HexBytes(self.s), )
def __init__(self, web3_event, current_blocknumber, timestamp, user=None): super().__init__(web3_event, current_blocknumber, timestamp, from_to_types, user) self.exchange_address = web3_event.get("address") # NOTE: The argument orderHash can be a hex string because the indexer currently can # not save bytes in the database. See issue https://github.com/trustlines-protocol/py-eth-index/issues/16 order_hash = web3_event.get("args").get("orderHash") if not isinstance(order_hash, hexbytes.HexBytes): self.order_hash = hexbytes.HexBytes(order_hash) else: self.order_hash = order_hash self.maker_token = web3_event.get("args").get("makerToken") self.taker_token = web3_event.get("args").get("takerToken")
def _validate(self, data): nonce = data["nonce"] fees = data["fees"] signature = data["signature"] if not 0 <= nonce < 2**256: raise ValidationError(f"nonce={nonce} is out of bounds") if not 0 <= fees < 2**64: raise ValidationError(f"delegationFees={fees} is out of bounds") if len(signature) != 65 and signature != hexbytes.HexBytes(""): raise ValidationError("signature must be 65 bytes") value = data["value"] if not 0 <= value < 2**256: raise ValidationError(f"value={value} is out of bounds")
def hash(self) -> hexbytes.HexBytes: return hexbytes.HexBytes( keccak256( self.exchange_address, self.maker_address, self.taker_address, self.maker_token, self.taker_token, self.fee_recipient, self.maker_token_amount, self.taker_token_amount, self.maker_fee, self.taker_fee, self.expiration_timestamp_in_sec, self.salt, ))
def __init__(self, web3_event, current_blocknumber: int, timestamp: int) -> None: super().__init__(timestamp) self._web3_event = web3_event self.blocknumber: Optional[int] = web3_event.get("blockNumber", None) self._current_blocknumber = current_blocknumber # NOTE: The field transactionHash is of type HexBytes sind web3 v4. It can also be a hex string because # the indexer currently can not save bytes in the database. # See issue https://github.com/trustlines-protocol/py-eth-index/issues/16 self.transaction_id: hexbytes.HexBytes transaction_id = web3_event.get("transactionHash") if not isinstance(transaction_id, hexbytes.HexBytes): self.transaction_id = hexbytes.HexBytes( web3_event.get("transactionHash")) else: self.transaction_id = transaction_id self.type = web3_event.get("event")
class MetaTransactionSchema(Schema): def _validate(self, data): value = data["value"] nonce = data["nonce"] base_fee = data["base_fee"] gas_price = data["gas_price"] gas_limit = data["gas_limit"] signature = data["signature"] if not 0 <= value < 2 ** 256: raise ValidationError(f"value={value} is out of bounds") if not 0 <= nonce < 2 ** 256: raise ValidationError(f"nonce={nonce} is out of bounds") if not 0 <= base_fee < 2 ** 256: raise ValidationError(f"baseFee={base_fee} is out of bounds") if not 0 <= gas_price < 2 ** 256: raise ValidationError(f"gas_price={gas_price} is out of bounds") if not 0 <= gas_limit < 2 ** 256: raise ValidationError(f"gas_limit={gas_limit} is out of bounds") if len(signature) != 65 and signature != hexbytes.HexBytes(""): raise ValidationError("signature must be 65 bytes") @post_load def make_meta_transaction(self, data, partial, many): self._validate(data) return identity.MetaTransaction(**data) chainId = fields.Integer(missing=0, attribute="chain_id") version = fields.Integer(missing=0, attribute="version") from_ = Address(required=True, data_key="from") to = Address(required=True) value = BigInteger(required=True) data = HexEncodedBytes(required=True) baseFee = BigInteger(missing=0, attribute="base_fee") gasPrice = BigInteger(missing=0, attribute="gas_price") gasLimit = BigInteger(missing=0, attribute="gas_limit") feeRecipient = Address(missing=ZERO_ADDRESS, attribute="fee_recipient") currencyNetworkOfFees = Address(missing=to, attribute="currency_network_of_fees") nonce = BigInteger(required=True) timeLimit = fields.Integer(missing=0, attribute="time_limit") operationType = OperationTypeField( missing=MetaTransaction.OperationType.CALL, attribute="operation_type" ) signature = HexEncodedBytes(missing=hexbytes.HexBytes(""))
def _validate(self, data): value = data["value"] nonce = data["nonce"] base_fee = data["base_fee"] gas_price = data["gas_price"] gas_limit = data["gas_limit"] signature = data["signature"] if not 0 <= value < 2 ** 256: raise ValidationError(f"value={value} is out of bounds") if not 0 <= nonce < 2 ** 256: raise ValidationError(f"nonce={nonce} is out of bounds") if not 0 <= base_fee < 2 ** 256: raise ValidationError(f"baseFee={base_fee} is out of bounds") if not 0 <= gas_price < 2 ** 256: raise ValidationError(f"gas_price={gas_price} is out of bounds") if not 0 <= gas_limit < 2 ** 256: raise ValidationError(f"gas_limit={gas_limit} is out of bounds") if len(signature) != 65 and signature != hexbytes.HexBytes(""): raise ValidationError("signature must be 65 bytes")
def postEth(self, hash, w3): """Post hash to blockchain.""" # web3 = getWeb3Instance() # contract = getWeb3Contract() nonce = w3.web3.eth.getTransactionCount(w3.account) tx = w3.contract.functions.save( hash, self.previousHash) tx_dict = tx.buildTransaction({ 'gas': 400000, # gas cost ~375k with encrypted IPFS hashes 'gasPrice': w3.web3.toWei(self.gasPrice, 'gwei'), 'nonce': nonce, }) signed_tx = w3.web3.eth.account.signTransaction( tx_dict, private_key=w3.privateKey) result = w3.web3.eth.sendRawTransaction(signed_tx.rawTransaction) tx_receipt = w3.web3.eth.waitForTransactionReceipt(result) import hexbytes # default output is HexBytes(address) which outputs bytes. if tx_receipt['status'] != 1: return 'failed transaction' else: return hexbytes.HexBytes(tx_receipt['transactionHash']).hex()
def test_extra_data(): return hexbytes.HexBytes("0x12345678123456781234567812345678")
def sign(self, key) -> None: v, r, s = eth_sign(self.hash(), key) self.v = v self.r = hexbytes.HexBytes(r) self.s = hexbytes.HexBytes(s)