Python eth_utils.to_checksum_address() Examples

The following are 30 code examples of eth_utils.to_checksum_address(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module eth_utils , or try the search function .
Example #1
Source File: zero_ex_custom_utils_v3.py    From hummingbot with Apache License 2.0 6 votes vote down vote up
def convert_order_to_tuple(order: Order) -> Tuple[str, any]:
    order_tuple = (to_checksum_address(order["makerAddress"]),
                   to_checksum_address(order["takerAddress"]),
                   to_checksum_address(order["feeRecipientAddress"]),
                   to_checksum_address(order["senderAddress"]),
                   int(order["makerAssetAmount"]),
                   int(order["takerAssetAmount"]),
                   int(order["makerFee"]),
                   int(order["takerFee"]),
                   int(order["expirationTimeSeconds"]),
                   int(order["salt"]),
                   order["makerAssetData"],
                   order["takerAssetData"],
                   order["makerFeeAssetData"],
                   order["takerFeeAssetData"])
    return order_tuple


# fix_signature extracts the logic used for formatting the signature required by the 0x protocol from 0x's custom
# sign_hash helper.
# https://github.com/0xProject/0x-monorepo/blob/development/python-packages/order_utils/src/zero_ex/order_utils/__init__.py#L462 
Example #2
Source File: mainnet_dao.py    From ether_sql with Apache License 2.0 6 votes vote down vote up
def add_dao_hardfork_state_diff():
    current_session = get_current_session()
    with current_session.db_session_scope():
        for dict_account in DAO_DRAIN_LIST:
            state_diff = StateDiff.add_state_diff(
                balance_diff=dict_account['balance_diff'],
                nonce_diff=None,
                code_from=None,
                code_to=None,
                address=to_checksum_address(dict_account['address']),
                transaction_hash=None,
                transaction_index=None,
                block_number=MAINNET_DAO_BLOCK,
                timestamp=MAINNET_DAO_TIMESTAMP,
                state_diff_type='dao-fork')
            current_session.db_session.add(state_diff) 
Example #3
Source File: uncles.py    From ether_sql with Apache License 2.0 6 votes vote down vote up
def add_uncle(cls, uncle_data, block_number, iso_timestamp):
        """
        Creates a new block object from data received from JSON-RPC call
        eth_getUncleByBlockNumberAndIndex.

        :param dict uncle_data: uncle data received from JSON RPC call
        :param int block_number: block number where this uncle was included
        :param datetime iso_timestamp: timestamp when the block was mined
        """
        logger.debug('{}'.format(uncle_data['gasUsed']))
        uncle = cls(uncle_hash=uncle_data['hash'],
                    uncle_blocknumber=hex_to_integer(uncle_data['number']),  # 'uncle_blocknumber'
                    parent_hash=uncle_data['parentHash'],  # parent_hash
                    difficulty=hex_to_integer(uncle_data['difficulty']),  # 'difficulty
                    current_blocknumber=block_number,  # current_blocknumber
                    gas_used=hex_to_integer(uncle_data['gasUsed']),  # gas_used
                    miner=to_checksum_address(uncle_data['miner']),  # miner
                    timestamp=iso_timestamp,
                    sha3uncles=uncle_data['sha3Uncles'],  # SHA3uncles
                    extra_data=uncle_data['extraData'],  # extra_data
                    gas_limit=hex_to_integer(uncle_data['gasLimit']))

        return uncle 
Example #4
Source File: utils.py    From ether_sql with Apache License 2.0 6 votes vote down vote up
def match_state_dump_to_state_table(block_number):
    current_session = get_current_session()
    with open('tests/fixtures/balance/balance_{}.json'.format(block_number)) as data_file:
        data = json.loads(data_file.read())
        state = data['state']
    with current_session.db_session_scope():
        for address in state:
            state_table_row = current_session.db_session.query(State).\
                filter_by(address=to_checksum_address(address)).first()
            assert state_table_row.balance == hex_to_integer(state[address]['balance'])
            assert state_table_row.nonce == hex_to_integer(state[address]['nonce'])
            if 'code' in state[address].keys():
                assert state_table_row.code == "0x"+state[address]['code']
                if state_table_row.storage is not None:
                    for storage in state_table_row.storage:
                        storage.storage = state[address]['storage'][storage.position] 
Example #5
Source File: blocks.py    From ether_sql with Apache License 2.0 6 votes vote down vote up
def add_block(cls, block_data, iso_timestamp):
        """
        Creates a new block object from data received from JSON-RPC call
        eth_getBlockByNumber.

        :param dict block_data: data received from the JSON RPC call
        :param datetime iso_timestamp: timestamp when the block was mined
        """
        block = cls(block_hash=to_hex(block_data['hash']),
                    parent_hash=to_hex(block_data['parentHash']),
                    difficulty=to_int(block_data['difficulty']),
                    block_number=to_int(block_data['number']),
                    gas_used=to_int(block_data['gasUsed']),
                    miner=to_checksum_address(block_data['miner']),
                    timestamp=iso_timestamp,
                    sha3uncles=to_hex(block_data['sha3Uncles']),
                    extra_data=to_hex(block_data['extraData']),
                    gas_limit=to_int(block_data['gasLimit']),
                    transaction_count=len(block_data['transactions']),
                    uncle_count=len(block_data['uncles']))

        return block 
Example #6
Source File: rpc_console.py    From python-sdk with MIT License 6 votes vote down vote up
def exec_cmd_with_hash_param(self, cmd, params):
        """
        execute cmd with one hash param
        """
        if cmd not in RPCConsole.functions["one_hash"]:
            return
        # check_param
        common.check_param_num(params, 1, False)
        # check contract address
        if cmd == "getCode":
            try:
                if len(params) > 1:
                    raise ArgumentsError("{} must provide one param".format(cmd))
                address = to_checksum_address(params[0])
                self.exec_command(cmd, [address])
            except Exception as e:
                raise ArgumentsError("invalid address: {}, info: {}"
                                     .format(params[0], e))
        else:
            if len(params) > 2:
                raise ArgumentsError("{} must provide no more than one param".format(cmd))
            # check hash
            common.check_hash(params[0])
            result = self.exec_command(cmd, [params[0]])
            self.parse_tx_and_receipt(result, cmd, params) 
Example #7
Source File: database.py    From raiden-services with MIT License 6 votes vote down vote up
def upsert_monitor_request(self, request: MonitorRequest) -> None:
        self.upsert(
            "monitor_request",
            dict(
                channel_identifier=hex256(request.channel_identifier),
                token_network_address=to_checksum_address(request.token_network_address),
                balance_hash=request.balance_hash,
                nonce=hex256(request.nonce),
                additional_hash=request.additional_hash,
                closing_signature=to_hex(request.closing_signature),
                non_closing_signature=to_hex(request.non_closing_signature),
                reward_amount=hex256(request.reward_amount),
                reward_proof_signature=to_hex(request.reward_proof_signature),
                non_closing_signer=to_checksum_address(request.non_closing_signer),
            ),
        ) 
Example #8
Source File: database.py    From raiden-services with MIT License 6 votes vote down vote up
def upsert_channel(self, channel: Channel) -> None:
        values = [
            to_checksum_address(channel.token_network_address),
            hex256(channel.identifier),
            to_checksum_address(channel.participant1),
            to_checksum_address(channel.participant2),
            hex256(channel.settle_timeout),
            channel.state,
            hex256(channel.closing_block) if channel.closing_block else None,
            channel.closing_participant,
            encode_hex(channel.monitor_tx_hash) if channel.monitor_tx_hash else None,
            encode_hex(channel.claim_tx_hash) if channel.claim_tx_hash else None,
        ]
        if channel.update_status:
            values += [
                to_checksum_address(channel.update_status.update_sender_address),
                hex256(channel.update_status.nonce),
            ]
        else:
            values += [None, None]

        upsert_sql = "INSERT OR REPLACE INTO channel VALUES ({})".format(
            ", ".join("?" * len(values))
        )
        self.conn.execute(upsert_sql, values) 
Example #9
Source File: api.py    From raiden-services with MIT License 6 votes vote down vote up
def get(self) -> Tuple[dict, int]:
        info = {
            "price_info": self.api.monitoring_service.context.min_reward,
            "network_info": {
                "chain_id": self.monitoring_service.chain_id,
                "token_network_registry_address": to_checksum_address(
                    self.monitoring_service.context.ms_state.blockchain_state.token_network_registry_address  # noqa
                ),
                "user_deposit_address": to_checksum_address(
                    self.monitoring_service.context.user_deposit_contract.address
                ),
                "service_token_address": to_checksum_address(self.service_token_address),
                "confirmed_block": {
                    "number": self.monitoring_service.context.ms_state.blockchain_state.latest_committed_block  # noqa
                },
            },
            "version": self.version,
            "contracts_version": self.contracts_version,
            "operator": self.api.operator,
            "message": self.api.info_message,
            "UTC": datetime.utcnow().isoformat(),
        }
        return info, 200 
Example #10
Source File: database.py    From raiden-services with MIT License 6 votes vote down vote up
def get_capacity_updates(
        self,
        updating_participant: Address,
        token_network_address: TokenNetworkAddress,
        channel_id: int,
    ) -> Tuple[TokenAmount, TokenAmount]:
        capacity_list = self.conn.execute(
            """
            SELECT updating_capacity, other_capacity
            FROM capacity_update WHERE updating_participant=?
            AND token_network_address=?
            AND channel_id=?
        """,
            [
                to_checksum_address(updating_participant),
                to_checksum_address(token_network_address),
                hex256(channel_id),
            ],
        )
        try:
            return next(capacity_list)
        except StopIteration:
            return TokenAmount(0), TokenAmount(0) 
Example #11
Source File: database.py    From raiden-services with MIT License 6 votes vote down vote up
def delete_channel(
        self, token_network_address: TokenNetworkAddress, channel_id: ChannelID
    ) -> bool:
        """ Tries to delete a channel from the database

        Args:
            token_network_address: The address of the token network of the channel
            channel_id: The id of the channel

        Returns: `True` if the channel was deleted, `False` if it did not exist
        """
        cursor = self.conn.execute(
            "DELETE FROM channel WHERE token_network_address = ? AND channel_id = ?",
            [to_checksum_address(token_network_address), hex256(channel_id)],
        )
        assert cursor.rowcount <= 1, "Did delete more than one channel"

        return cursor.rowcount == 1 
Example #12
Source File: database.py    From raiden-services with MIT License 6 votes vote down vote up
def update_feedback(self, token: FeedbackToken, route: List[Address], successful: bool) -> int:
        hexed_route = [to_checksum_address(e) for e in route]
        token_dict = dict(
            token_id=token.uuid.hex,
            token_network_address=to_checksum_address(token.token_network_address),
            route=json.dumps(hexed_route),
            successful=successful,
            feedback_time=datetime.utcnow(),
        )
        updated_rows = self.conn.execute(
            """
            UPDATE feedback
            SET
                successful = :successful,
                feedback_time = :feedback_time
            WHERE
                token_id = :token_id AND
                token_network_address = :token_network_address AND
                route = :route AND
                successful IS NULL;
        """,
            token_dict,
        ).rowcount

        return updated_rows 
Example #13
Source File: test_database.py    From raiden-services with MIT License 6 votes vote down vote up
def test_save_and_load_channel(ms_database: Database):
    ms_database.conn.execute(
        "INSERT INTO token_network (address) VALUES (?)",
        [to_checksum_address(DEFAULT_TOKEN_NETWORK_ADDRESS)],
    )
    for update_status in [
        None,
        OnChainUpdateStatus(
            update_sender_address=Address(bytes([1] * 20)), nonce=random.randint(0, UINT256_MAX)
        ),
    ]:
        channel = create_channel(update_status)
        ms_database.upsert_channel(channel)
        loaded_channel = ms_database.get_channel(
            token_network_address=channel.token_network_address, channel_id=channel.identifier
        )
        assert loaded_channel == channel 
Example #14
Source File: api.py    From raiden-services with MIT License 6 votes vote down vote up
def monitoring_service_mock() -> Generator[MonitoringService, None, None]:
    web3_mock = Web3Mock()

    mock_udc = Mock(address=bytes([8] * 20))
    mock_udc.functions.effectiveBalance.return_value.call.return_value = 10000
    mock_udc.functions.token.return_value.call.return_value = to_checksum_address(bytes([7] * 20))
    ms = MonitoringService(
        web3=web3_mock,
        private_key=PrivateKey(
            decode_hex("3a1076bf45ab87712ad64ccb3b10217737f7faacbf2872e88fdd9a537d8fe266")
        ),
        db_filename=":memory:",
        contracts={
            CONTRACT_TOKEN_NETWORK_REGISTRY: Mock(address=bytes([9] * 20)),
            CONTRACT_USER_DEPOSIT: mock_udc,
            CONTRACT_MONITORING_SERVICE: Mock(address=bytes([1] * 20)),
            CONTRACT_SERVICE_REGISTRY: Mock(address=bytes([2] * 20)),
        },
        sync_start_block=BlockNumber(0),
        required_confirmations=BlockTimeout(0),
        poll_interval=0,
    )

    yield ms 
Example #15
Source File: test_database.py    From raiden-services with MIT License 6 votes vote down vote up
def db_has_feedback_for(database: PFSDatabase, token: FeedbackToken, route: List[Address]) -> bool:
    hexed_route = [to_checksum_address(e) for e in route]
    feedback = database.conn.execute(
        """SELECT successful FROM feedback WHERE
            token_id = ? AND
            token_network_address = ? AND
            route = ?;
        """,
        [
            token.uuid.hex,
            to_checksum_address(token.token_network_address),
            json.dumps(hexed_route),
        ],
    ).fetchone()

    if feedback:
        return feedback["successful"] is not None

    return False 
Example #16
Source File: token_ops.py    From raiden-contracts with MIT License 6 votes vote down vote up
def get_weth(self, token_address: ChecksumAddress, amount: int) -> TxReceipt:
        token_address = to_checksum_address(token_address)
        assert (
            self.web3.eth.getBalance(self.owner) > amount
        ), "Not sufficient ether to make a deposit to WETH contract"
        assert self.is_valid_contract(
            token_address
        ), "The WETH token does not exist on this contract"
        result = requests.get(
            "http://api.etherscan.io/api?module=contract&action=getabi&"
            "address=0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
        )
        weth_abi = result.json()["result"]
        weth_proxy = self.web3.eth.contract(address=token_address, abi=weth_abi)
        assert weth_proxy.functions.symbol().call() == "WETH", "This contract is not a WETH token"
        txhash = weth_proxy.functions.deposit().transact(
            {"from": self.owner, "value": Wei(amount)}
        )
        receipt, _ = check_successful_tx(web3=self.web3, txid=txhash, timeout=self.wait)
        return receipt

    # Could be used for both custom token as well as WETH contracts 
Example #17
Source File: token_ops.py    From raiden-contracts with MIT License 6 votes vote down vote up
def transfer_tokens(self, token_address: ChecksumAddress, dest: str, amount: int) -> TxReceipt:
        token_address = to_checksum_address(token_address)
        dest = to_checksum_address(dest)
        assert self.is_valid_contract(
            token_address
        ), "The token contract does not seem to exist on this address"
        token_contract = ContractManager(contracts_precompiled_path()).get_contract(
            CONTRACT_CUSTOM_TOKEN
        )
        token_proxy = self.web3.eth.contract(address=token_address, abi=token_contract["abi"])
        assert (
            token_proxy.functions.balanceOf(self.owner).call() >= amount
        ), "Not enough token balances"
        txhash = token_proxy.functions.transfer(dest, amount).transact({"from": self.owner})
        receipt, _ = check_successful_tx(web3=self.web3, txid=txhash, timeout=self.wait)
        return receipt 
Example #18
Source File: database.py    From raiden-services with MIT License 6 votes vote down vote up
def get_feedback_token(
        self, token_id: UUID, token_network_address: TokenNetworkAddress, route: List[Address]
    ) -> Optional[FeedbackToken]:
        hexed_route = [to_checksum_address(e) for e in route]
        token = self.conn.execute(
            """SELECT * FROM feedback WHERE
                token_id = ? AND
                token_network_address = ? AND
                route = ?;
            """,
            [token_id.hex, to_checksum_address(token_network_address), json.dumps(hexed_route)],
        ).fetchone()

        if token:
            return FeedbackToken(
                token_network_address=TokenNetworkAddress(
                    to_canonical_address(token["token_network_address"])
                ),
                uuid=UUID(token["token_id"]),
                creation_time=token["creation_time"],
            )

        return None 
Example #19
Source File: logs.py    From raiden-contracts with MIT License 6 votes vote down vote up
def add(
        self,
        txn_hash: str,
        event_name: str,
        callback: Optional[Callable[..., Any]] = None,
        count: int = 1,
    ) -> None:
        caller = getframeinfo(stack()[1][0])
        message = "%s:%d" % (caller.filename, caller.lineno)

        if event_name not in self.event_waiting:
            self.event_waiting[event_name] = {}
            self.event_filters[event_name] = LogFilter(
                web3=self.web3,
                abi=self.abi,
                address=to_checksum_address(self.address),
                event_name=event_name,
                callback=self.handle_log,
            )

        self.event_waiting[event_name][txn_hash] = LogRecorded(
            message=message, callback=callback, count=count
        ) 
Example #20
Source File: database.py    From raiden-services with MIT License 6 votes vote down vote up
def pop_waiting_messages(
        self, token_network_address: TokenNetworkAddress, channel_id: ChannelID
    ) -> Iterator[DeferableMessage]:
        """Return all waiting messages for the given channel and delete them from the db"""
        # Return messages
        for row in self.conn.execute(
            """
            SELECT message FROM waiting_message
            WHERE token_network_address = ? AND channel_id = ?
            """,
            [to_checksum_address(token_network_address), hex256(channel_id)],
        ):
            yield JSONSerializer.deserialize(row["message"])

        # Delete returned messages
        self.conn.execute(
            "DELETE FROM waiting_message WHERE token_network_address = ? AND channel_id = ?",
            [to_checksum_address(token_network_address), hex256(channel_id)],
        ) 
Example #21
Source File: contract_deployer.py    From raiden-contracts with MIT License 6 votes vote down vote up
def deploy_token_contract(
        self,
        token_supply: int,
        token_decimals: int,
        token_name: str,
        token_symbol: str,
        token_type: str = "CustomToken",
    ) -> Dict[str, ChecksumAddress]:
        """Deploy a token contract."""
        receipt = self.deploy(
            contract_name=token_type, args=[token_supply, token_decimals, token_name, token_symbol]
        )
        token_address = receipt["contractAddress"]
        assert token_address and is_address(token_address)
        token_address = to_checksum_address(token_address)
        return {token_type: token_address} 
Example #22
Source File: contract_verifier.py    From raiden-contracts with MIT License 6 votes vote down vote up
def _verify_one_to_n_deployment(
    one_to_n: Contract,
    constructor_arguments: List,
    user_deposit_address: HexAddress,
    service_registry_address: HexAddress,
    chain_id: int,
) -> None:
    """ Check an onchain deployment of OneToN and constructor arguments """
    if to_checksum_address(one_to_n.functions.deposit_contract().call()) != user_deposit_address:
        raise RuntimeError("OneToN has a wrong UserDeposit address onchain.")
    if user_deposit_address != constructor_arguments[0]:
        raise RuntimeError("OneToN received a wrong UserDeposit address during construction.")
    if chain_id != constructor_arguments[1]:
        raise RuntimeError("OneToN received a wrong chain ID during construction.")
    if service_registry_address != constructor_arguments[2]:
        raise RuntimeError("OneToN received a wrong ServiceRegistry address during construction.")
    if len(constructor_arguments) != 3:
        raise RuntimeError("OneToN received a wrong number of constructor arguments.") 
Example #23
Source File: contract_verifier.py    From raiden-contracts with MIT License 6 votes vote down vote up
def _verify_service_registry_deployment(
    service_registry: Contract, constructor_arguments: List, token_address: HexAddress
) -> None:
    """ Check an onchain deployment of ServiceRegistry and constructor arguments """
    if len(constructor_arguments) != 8:
        raise RuntimeError(
            "ServiceRegistry was deployed with a wrong number of constructor arguments"
        )
    if to_checksum_address(service_registry.functions.token().call()) != token_address:
        raise RuntimeError("ServiceRegistry has a wrong token address")
    if token_address != constructor_arguments[0]:
        raise RuntimeError(
            f"expected token address {token_address} "
            f"but the constructor argument for {CONTRACT_SERVICE_REGISTRY} is "
            f"{constructor_arguments[0]}"
        )
    controller_onchain = to_checksum_address(service_registry.functions.controller().call())
    if controller_onchain != constructor_arguments[1]:
        raise RuntimeError(
            f"the deployment data contains the controller address {constructor_arguments[1]} "
            f"but the contract remembers {controller_onchain} onchain."
        )
    # All other parameters can change after the deployment, so the checks are omitted. 
Example #24
Source File: common.py    From python-sdk with MIT License 5 votes vote down vote up
def check_and_format_address(address):
    """
    check address
    """
    try:
        formatted_address = to_checksum_address(address)
        return formatted_address
    except Exception as e:
        raise ArgumentsError("invalid address {}, reason: {}"
                             .format(address, e)) 
Example #25
Source File: state.py    From ether_sql with Apache License 2.0 5 votes vote down vote up
def add_state(cls, address, balance, nonce, code):
        if nonce is None:
            _nonce = 0
        else:
            _nonce = nonce
        state = cls(
                    address=to_checksum_address(address),
                    balance=balance,
                    nonce=_nonce,
                    code=code)
        return state 
Example #26
Source File: test_graphs.py    From raiden-services with MIT License 5 votes vote down vote up
def test_routing_simple(
    token_network_model: TokenNetwork,
    reachability_state: SimpleReachabilityContainer,
    addresses: List[Address],
):
    hex_addrs = [to_checksum_address(addr) for addr in addresses]
    view01: ChannelView = token_network_model.G[addresses[0]][addresses[1]]["view"]
    view10: ChannelView = token_network_model.G[addresses[1]][addresses[0]]["view"]

    assert view01.fee_schedule_sender.flat == 0
    assert view01.capacity == 90
    assert view10.capacity == 60

    # 0->2->3 is the shortest path, but has no capacity, so 0->1->4->3 is used
    paths = token_network_model.get_paths(
        source=addresses[0],
        target=addresses[3],
        value=PaymentAmount(10),
        max_paths=1,
        reachability_state=reachability_state,
    )
    assert len(paths) == 1
    assert paths[0].to_dict() == {
        "path": [hex_addrs[0], hex_addrs[1], hex_addrs[4], hex_addrs[3]],
        "estimated_fee": 0,
    }

    # Not connected.
    no_paths = token_network_model.get_paths(
        source=addresses[0],
        target=addresses[5],
        value=PaymentAmount(10),
        max_paths=1,
        reachability_state=reachability_state,
    )
    assert [] == no_paths 
Example #27
Source File: iou.py    From raiden-services with MIT License 5 votes vote down vote up
def make_iou(one_to_n_contract: Contract):
    one_to_n_contract_address = to_canonical_address(one_to_n_contract.address)

    def f(
        sender_priv_key: PrivateKey,
        receiver: Address,
        amount=1,
        expiration_block=MIN_IOU_EXPIRY + 100,
        one_to_n_address: Address = one_to_n_contract_address,
        chain_id: ChainID = ChainID(61),
    ) -> IOU:
        receiver_hex: str = to_checksum_address(receiver)
        iou_dict = {
            "sender": to_checksum_address(private_key_to_address(sender_priv_key)),
            "receiver": receiver_hex,
            "amount": amount,
            "expiration_block": expiration_block,
            "one_to_n_address": to_checksum_address(one_to_n_address),
            "chain_id": chain_id,
        }
        iou_dict["signature"] = encode_hex(
            sign_one_to_n_iou(privatekey=sender_priv_key, **iou_dict)
        )
        iou = IOU.Schema().load(iou_dict)
        iou.claimed = False
        return iou

    return f 
Example #28
Source File: network_service.py    From raiden-services with MIT License 5 votes vote down vote up
def pathfinding_service_mock_empty() -> Generator[PathfindingService, None, None]:
    with patch("pathfinding_service.service.MatrixListener", new=Mock):
        web3_mock = Web3Mock()

        mock_udc = Mock(address=bytes([8] * 20))
        mock_udc.functions.effectiveBalance.return_value.call.return_value = 10000
        mock_udc.functions.token.return_value.call.return_value = to_checksum_address(
            bytes([7] * 20)
        )
        pathfinding_service = PathfindingService(
            web3=web3_mock,
            contracts={
                CONTRACT_TOKEN_NETWORK_REGISTRY: Mock(address=bytes([9] * 20)),
                CONTRACT_USER_DEPOSIT: mock_udc,
            },
            sync_start_block=BlockNumber(0),
            required_confirmations=BlockTimeout(0),
            poll_interval=0,
            private_key=PrivateKey(
                decode_hex("3a1076bf45ab87712ad64ccb3b10217737f7faacbf2872e88fdd9a537d8fe266")
            ),
            db_filename=":memory:",
        )

        yield pathfinding_service
        pathfinding_service.stop() 
Example #29
Source File: service_registry.py    From raiden-services with MIT License 5 votes vote down vote up
def checked_transact(
    web3: Web3, sender_address: Address, function_call: ContractFunction, task_name: str
) -> TxReceipt:
    log.info(f"Starting: {task_name}")
    transaction_hash = function_call.transact({"from": sender_address})

    click.secho(
        f"\nSending transaction: {task_name}"
        f"\n\tSee {etherscan_url_for_txhash(web3.eth.chainId, transaction_hash)}"
    )

    transaction_receipt = web3.eth.waitForTransactionReceipt(transaction_hash)
    was_successful = transaction_receipt["status"] == 1

    if not was_successful:
        log.error(
            f"Failed: {task_name}\nPlease check that the account "
            f"{to_checksum_address(sender_address)} has sufficient funds.",
            receipt=transaction_receipt,
        )
        sys.exit(1)

    log.info(
        f"Finished: {task_name}",
        successful=was_successful,
        transaction_hash=to_hex(transaction_hash),
    )

    return transaction_receipt 
Example #30
Source File: signature.py    From raiden-contracts with MIT License 5 votes vote down vote up
def public_key_to_address(public_key: Union[PublicKey, bytes]) -> ChecksumAddress:
    """ Converts a public key to an Ethereum address. """
    if isinstance(public_key, PublicKey):
        public_key = public_key.format(compressed=False)
    assert isinstance(public_key, bytes)
    return to_checksum_address(sha3(public_key[1:])[-20:])