本文整理汇总了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
示例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
示例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()
}
示例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
示例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
示例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__()
示例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
示例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
示例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]
示例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)
示例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
示例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
示例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
#
示例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
示例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]