當前位置: 首頁>>代碼示例>>Python>>正文


Python web3.Web3方法代碼示例

本文整理匯總了Python中web3.Web3方法的典型用法代碼示例。如果您正苦於以下問題:Python web3.Web3方法的具體用法?Python web3.Web3怎麽用?Python web3.Web3使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在web3的用法示例。


在下文中一共展示了web3.Web3方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_time_based_gas_price_strategy_zero_sample

# 需要導入模塊: import web3 [as 別名]
# 或者: from web3 import Web3 [as 別名]
def test_time_based_gas_price_strategy_zero_sample(strategy_params_zero,
                                                   expected_exception_message):
    with pytest.raises(ValidationError) as excinfo:
        fixture_middleware = construct_result_generator_middleware({
            'eth_getBlockByHash': _get_block_by_something,
            'eth_getBlockByNumber': _get_block_by_something,
        })

        w3 = Web3(
            provider=BaseProvider(),
            middlewares=[fixture_middleware],
        )
        time_based_gas_price_strategy_zero = construct_time_based_gas_price_strategy(
            **strategy_params_zero,
        )
        w3.eth.setGasPriceStrategy(time_based_gas_price_strategy_zero)
        w3.eth.generateGasPrice()
    assert str(excinfo.value) == expected_exception_message 
開發者ID:ethereum,項目名稱:web3.py,代碼行數:20,代碼來源:test_time_based_gas_price_strategy.py

示例2: __init__

# 需要導入模塊: import web3 [as 別名]
# 或者: from web3 import Web3 [as 別名]
def __init__(self):
		# Path setting
		self.Fpath = "/tmp"
		self.DbPath = "/tmp/.db"
		# Web3 setting
		self.web3 = Web3(HTTPProvider('http://localhost:8545'))
		# DB setting
		self.conn = sqlite3.connect(self.DbPath+"/FileSign.db")
		self.c = self.conn.cursor()
		self.c.execute("create table if not exists AccountEhash(account text, Ehash text, PRIMARY KEY(account))")
		self.conn.commit()
		self.c.execute("create table if not exists SendLog(account text, Thash text)")
		self.conn.commit()
		self.c.execute("create table if not exists SignFhash(SignHash text, Fhash text, PRIMARY KEY(SignHash))")
		self.conn.commit()
		try:
			self.c.execute("insert into AccountEhash values ('admin','"+str(self.web3.eth.coinbase)+"')")
			self.conn.commit()
		except:
			pass 
開發者ID:yenkuanlee,項目名稱:IPDC,代碼行數:22,代碼來源:control.py

示例3: find_transaction_details_in_redeem_event

# 需要導入模塊: import web3 [as 別名]
# 或者: from web3 import Web3 [as 別名]
def find_transaction_details_in_redeem_event(self, recipient_address: str, secret_hash: str, block_number: int):
        # web3.gastracker.io node does not support filtering
        # etc-geth.0xinfra.com not is not stable so it is used only for filtering
        filterable_web3 = Web3(HTTPProvider('https://etc-geth.0xinfra.com/'))

        event_signature_hash = self.web3.sha3(text="RedeemSwap(address,bytes20,bytes32)").hex()
        filter_options = {
            'fromBlock': block_number,
            'address': self.contract_address,
            'topics': [
                event_signature_hash,
                '0x' + encode_single('address', recipient_address).hex(),
                '0x' + encode_single('bytes20', bytes.fromhex(secret_hash)).hex()
            ]
        }

        event_filter = filterable_web3.eth.filter(filter_options)

        for _ in range(ETH_FILTER_MAX_ATTEMPTS):
            events = event_filter.get_all_entries()
            if events:
                return {
                    'secret': events[0]['data'][2:],
                    'transaction_hash': events[0]['transactionHash'].hex()
                } 
開發者ID:Lamden,項目名稱:clove,代碼行數:27,代碼來源:ethereum_classic.py

示例4: get_transaction_receipt

# 需要導入模塊: import web3 [as 別名]
# 或者: from web3 import Web3 [as 別名]
def get_transaction_receipt(self, transaction_hash):
        """
        :param transaction_hash:
        :raises Web3ConnectionException
        :raises UnknownTransaction
        :return:
        """
        try:
            receipt = self.web3.eth.getTransactionReceipt(transaction_hash)

            if not receipt:
                # Might be because a reorg
                raise UnknownTransaction
            return receipt
        except self.connection_exceptions as e:
            raise Web3ConnectionException('Web3 provider is not connected') from e
        except Exception as e:
            raise UnknownTransaction from e 
開發者ID:gnosis,項目名稱:django-eth-events,代碼行數:20,代碼來源:web3_service.py

示例5: get_block

# 需要導入模塊: import web3 [as 別名]
# 或者: from web3 import Web3 [as 別名]
def get_block(self, block_identifier, full_transactions=False):
        """
        :param block_identifier:
        :param full_transactions:
        :raises Web3ConnectionException
        :raises UnknownBlock
        :return:
        """
        try:
            block = self.web3.eth.getBlock(block_identifier, full_transactions)
            if not block:
                raise UnknownBlock
            return block
        except self.connection_exceptions:
            raise Web3ConnectionException('Web3 provider is not connected')
        except Exception as e:
            raise UnknownBlock from e 
開發者ID:gnosis,項目名稱:django-eth-events,代碼行數:19,代碼來源:web3_service.py

示例6: __init__

# 需要導入模塊: import web3 [as 別名]
# 或者: from web3 import Web3 [as 別名]
def __init__(self, *args, **kwargs):
        """Initializes the `web3` object.

        Args:
            rpc_provider (HTTPProvider): Valid `web3` HTTPProvider instance (optional)
        """
        rpc_provider = kwargs.pop('rpc_provider', None)
        if not rpc_provider:
            timeout = getattr(settings, "ETHEREUM_NODE_TIMEOUT", 10)

            uri = settings.ETHEREUM_NODE_URI
            rpc_provider = HTTPProvider(
                endpoint_uri=uri,
                request_kwargs={
                    "timeout": timeout
                }
            )

        self.web3 = Web3(rpc_provider)

        # If running in a network with PoA consensus, inject the middleware
        if getattr(settings, "ETHEREUM_GETH_POA", False):
            self.web3.middleware_onion.inject(geth_poa_middleware, layer=0)

        super(Web3Service, self).__init__() 
開發者ID:artemistomaras,項目名稱:django-ethereum-events,代碼行數:27,代碼來源:web3_service.py

示例7: __init__

# 需要導入模塊: import web3 [as 別名]
# 或者: from web3 import Web3 [as 別名]
def __init__(self,host='localhost',port=5001,mainnet=False):
		self.last_contract_address = None
		self.last_hash_added = None
		#self.api = ipfsapi.connect(host='127.0.0.1',port=port)
		# self.web3 = Web3(HTTPProvider('http://localhost:8545'))
		if mainnet:
			ipc_path=os.path.dirname(os.path.realpath(__file__))+'/data_mainnet/geth.ipc'
		else:
			ipc_path = os.path.dirname(os.path.realpath(__file__))+'/data/geth.ipc'
		print("IPCProvider path: ",ipc_path)
		self.web3 = Web3(IPCProvider(ipc_path))
		self.blockNumber = self.web3.eth.blockNumber
		self.eth_accounts = self.web3.personal.listAccounts
		self.account_index = 0
		self.ethereum_acc_pass = None
		
		self.tx = {}

		print("Initializing a DDASH Interface object.")

		# log Ethereum accounts to ddash/nfo/
		self.write_ethereum_address(mainnet)

	# contract_name is without the sol extension 
開發者ID:osmode,項目名稱:ddash,代碼行數:26,代碼來源:bcinterface.py

示例8: has_matching_signatures

# 需要導入模塊: import web3 [as 別名]
# 或者: from web3 import Web3 [as 別名]
def has_matching_signatures(self) -> bool:
        """
        Check that the signatures match the terms of trade.

        :return: True if the transaction has been signed by both parties
        """
        w3 = Web3()
        singable_message = encode_defunct(primitive=self.sender_hash)
        result = (
            w3.eth.account.recover_message(  # pylint: disable=no-member
                signable_message=singable_message,
                signature=HexBytes(self.sender_signature),
            )
            == self.sender_addr
        )
        counterparty_signable_message = encode_defunct(primitive=self.counterparty_hash)
        result = (
            result
            and w3.eth.account.recover_message(  # pylint: disable=no-member
                signable_message=counterparty_signable_message,
                signature=HexBytes(self.counterparty_signature),
            )
            == self.counterparty_addr
        )
        return result 
開發者ID:fetchai,項目名稱:agents-aea,代碼行數:27,代碼來源:game.py

示例9: validate_single_matching_uri

# 需要導入模塊: import web3 [as 別名]
# 或者: from web3 import Web3 [as 別名]
def validate_single_matching_uri(all_blockchain_uris: List[str], w3: Web3) -> str:
    """
    Return a single block URI after validating that it is the *only* URI in
    all_blockchain_uris that matches the w3 instance.
    """
    from ethpm.uri import check_if_chain_matches_chain_uri

    matching_uris = [
        uri for uri in all_blockchain_uris if check_if_chain_matches_chain_uri(w3, uri)
    ]

    if not matching_uris:
        raise EthPMValidationError("Package has no matching URIs on chain.")
    elif len(matching_uris) != 1:
        raise EthPMValidationError(
            f"Package has too many ({len(matching_uris)}) matching URIs: {matching_uris}."
        )
    return matching_uris[0] 
開發者ID:ethereum,項目名稱:web3.py,代碼行數:20,代碼來源:uri.py

示例10: create_latest_block_uri

# 需要導入模塊: import web3 [as 別名]
# 或者: from web3 import Web3 [as 別名]
def create_latest_block_uri(w3: Web3, from_blocks_ago: int = 3) -> URI:
    """
    Creates a block uri for the given w3 instance.
    Defaults to 3 blocks prior to the "latest" block to accommodate for block reorgs.
    If using a testnet with less than 3 mined blocks, adjust :from_blocks_ago:.
    """
    chain_id = to_hex(get_genesis_block_hash(w3))
    latest_block_tx_receipt = w3.eth.getBlock("latest")
    target_block_number = BlockNumber(latest_block_tx_receipt["number"] - from_blocks_ago)
    if target_block_number < 0:
        raise Exception(
            f"Only {latest_block_tx_receipt['number']} blocks avaible on provided w3, "
            f"cannot create latest block uri for {from_blocks_ago} blocks ago."
        )
    recent_block = to_hex(w3.eth.getBlock(target_block_number)["hash"])
    return create_block_uri(chain_id, recent_block) 
開發者ID:ethereum,項目名稱:web3.py,代碼行數:18,代碼來源:uri.py

示例11: check_if_chain_matches_chain_uri

# 需要導入模塊: import web3 [as 別名]
# 或者: from web3 import Web3 [as 別名]
def check_if_chain_matches_chain_uri(web3: Web3, blockchain_uri: URI) -> bool:
    chain_id, resource_type, resource_hash = parse_BIP122_uri(blockchain_uri)
    genesis_block = web3.eth.getBlock("earliest")

    if encode_hex(genesis_block["hash"]) != chain_id:
        return False

    if resource_type == BLOCK:
        resource = web3.eth.getBlock(resource_hash)
    else:
        raise ValueError(f"Unsupported resource type: {resource_type}")

    if encode_hex(resource["hash"]) == resource_hash:
        return True
    else:
        return False 
開發者ID:ethereum,項目名稱:web3.py,代碼行數:18,代碼來源:uri.py

示例12: _get_weighted_avg_block_time

# 需要導入模塊: import web3 [as 別名]
# 或者: from web3 import Web3 [as 別名]
def _get_weighted_avg_block_time(w3: Web3, sample_size: int) -> float:
    latest_block_number = w3.eth.getBlock('latest')['number']
    constrained_sample_size = min(sample_size, latest_block_number)
    if constrained_sample_size == 0:
        raise ValidationError('Constrained sample size is 0')

    oldest_block = w3.eth.getBlock(BlockNumber(latest_block_number - constrained_sample_size))
    oldest_block_number = oldest_block['number']
    prev_timestamp = oldest_block['timestamp']
    weighted_sum = 0.0
    sum_of_weights = 0.0
    for i in range(oldest_block_number + 1, latest_block_number + 1):
        curr_timestamp = w3.eth.getBlock(BlockNumber(i))['timestamp']
        time = curr_timestamp - prev_timestamp
        weight = (i - oldest_block_number) / constrained_sample_size
        weighted_sum += (time * weight)
        sum_of_weights += weight
        prev_timestamp = curr_timestamp
    return weighted_sum / sum_of_weights 
開發者ID:ethereum,項目名稱:web3.py,代碼行數:21,代碼來源:time_based.py

示例13: __init__

# 需要導入模塊: import web3 [as 別名]
# 或者: from web3 import Web3 [as 別名]
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
    # 
開發者ID:ethereum,項目名稱:web3.py,代碼行數:18,代碼來源:pm.py

示例14: test_time_based_gas_price_strategy

# 需要導入模塊: import web3 [as 別名]
# 或者: from web3 import Web3 [as 別名]
def test_time_based_gas_price_strategy(strategy_params, expected):
    fixture_middleware = construct_result_generator_middleware({
        'eth_getBlockByHash': _get_block_by_something,
        'eth_getBlockByNumber': _get_block_by_something,
    })

    w3 = Web3(
        provider=BaseProvider(),
        middlewares=[fixture_middleware],
    )

    time_based_gas_price_strategy = construct_time_based_gas_price_strategy(
        **strategy_params,
    )
    w3.eth.setGasPriceStrategy(time_based_gas_price_strategy)
    actual = w3.eth.generateGasPrice()
    assert actual == expected 
開發者ID:ethereum,項目名稱:web3.py,代碼行數:19,代碼來源:test_time_based_gas_price_strategy.py

示例15: query_blockchain_events

# 需要導入模塊: import web3 [as 別名]
# 或者: from web3 import Web3 [as 別名]
def query_blockchain_events(
    web3: Web3, contract_addresses: List[Address], from_block: BlockNumber, to_block: BlockNumber
) -> List[Dict]:
    """Returns events emmitted by a contract for a given event name, within a certain range.

    Args:
        web3: A Web3 instance
        contract_addresses: The address(es) of the contract(s) to be filtered
        from_block: The block to start search events
        to_block: The block to stop searching for events

    Returns:
        All matching events
    """
    filter_params = FilterParams(
        {"fromBlock": from_block, "toBlock": to_block, "address": contract_addresses}
    )

    events = web3.eth.getLogs(filter_params)

    return [decode_event(web3.codec, log_entry) for log_entry in events] 
開發者ID:raiden-network,項目名稱:raiden-services,代碼行數:23,代碼來源:blockchain.py


注:本文中的web3.Web3方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。