def connect(network, account='user'):
    if network == 'local':
        from web3 import Web3

        w3 = Web3(Web3.HTTPProvider("http://127.0.0.1:8545"))
        try:
            w3.eth.defaultAccount = w3.eth.accounts[0]
            admin = w3.eth.accounts[0]
        except:
            raise Exception("Ensure ganache-cli is connected")
    elif network == 'bsc-testnet':
        config = read_config()
        os.environ[
            'WEB3_PROVIDER_URI'] = 'https://data-seed-prebsc-1-s1.binance.org:8545/'
        os.environ['WEB3_CHAIN_ID'] = '97'

        from web3.middleware import construct_sign_and_send_raw_middleware
        from web3.middleware import geth_poa_middleware
        from web3.auto import w3

        admin = w3.eth.account.from_key(config[account]['key'])
        w3.eth.defaultAccount = admin.address
        w3.middleware_onion.inject(geth_poa_middleware, layer=0)
        w3.middleware_onion.add(construct_sign_and_send_raw_middleware(admin))

    elif network == 'bsc-mainnet':
        config = read_config()
        os.environ['WEB3_PROVIDER_URI'] = 'https://bsc-dataseed.binance.org/'
        os.environ['WEB3_CHAIN_ID'] = '56'

        from web3.middleware import construct_sign_and_send_raw_middleware
        from web3.middleware import geth_poa_middleware
        from web3.auto import w3

        admin = w3.eth.account.from_key(config[account]['key'])
        w3.eth.defaultAccount = admin.address
        w3.middleware_onion.inject(geth_poa_middleware, layer=0)
        w3.middleware_onion.add(construct_sign_and_send_raw_middleware(admin))

    elif network == 'kovan':
        config = read_config()
        os.environ['WEB3_INFURA_PROJECT_ID'] = config['infura']['project_id']
        os.environ['WEB3_INFURA_API_SECRET'] = config['infura']['secret']

        from web3.middleware import construct_sign_and_send_raw_middleware
        from web3.auto.infura.kovan import w3

        admin = w3.eth.account.from_key(config[account]['key'])
        w3.eth.defaultAccount = admin.address
        w3.middleware_onion.add(construct_sign_and_send_raw_middleware(admin))
    else:
        raise ValueError(f'Unknown network {network}')

    assert w3.isConnected()
    return w3, admin
Пример #2
0
def test_sign_and_send_raw_middleware_with_byte_addresses(
        w3_dummy,
        from_converter,
        to_converter):
    private_key = PRIVATE_KEY_1
    from_ = from_converter(ADDRESS_1)
    to_ = to_converter(ADDRESS_2)

    w3_dummy.middleware_stack.add(
        construct_sign_and_send_raw_middleware(private_key))

    actual = w3_dummy.manager.request_blocking(
        'eth_sendTransaction',
        [{
            'to': to_,
            'from': from_,
            'gas': 21000,
            'gasPrice': 0,
            'value': 1,
            'nonce': 0
        }])
    raw_txn = actual[1][0]
    actual_method = actual[0]
    assert actual_method == 'eth_sendRawTransaction'
    assert isinstance(raw_txn, bytes)
    def __init__(
        self,
        web3: Web3,
        private_key: str,
        gas_limit: int,
        gas_price: int = 1,
        wait: int = 10,
        contracts_version: Optional[str] = None,
    ):
        # pylint: disable=E1101
        super(ContractDeployer, self).__init__(web3=web3, contracts_version=contracts_version)
        self.wait = wait
        self.owner = private_key_to_address(private_key)
        self.transaction = {"from": self.owner, "gas": gas_limit}
        if gas_price != 0:
            self.transaction["gasPrice"] = gas_price * int(units["gwei"])

        self.web3.middleware_stack.add(construct_sign_and_send_raw_middleware(private_key))

        # Check that the precompiled data matches the source code
        # Only for current version, because this is the only one with source code
        if self.contracts_version in [None, CONTRACTS_VERSION]:
            contract_manager_source = ContractSourceManager(contracts_source_path())
            contract_manager_source.checksum_contracts()
            contract_manager_source.verify_precompiled_checksums(self.precompiled_path)
        else:
            LOG.info("Skipped checks against the source code because it is not available.")
Пример #4
0
    def make_web3_provider(self, account):
        w3 = Web3(HTTPProvider(self.url))
        w3.middleware_stack.add(
            construct_sign_and_send_raw_middleware(account.private_key))
        w3.middleware_stack.inject(geth_poa_middleware, layer=0)

        return w3
Пример #5
0
    def __init__(
        self,
        web3: Web3,
        private_key: str,
        gas_limit: int,
        gas_price: int=1,
        wait: int=10,
        contracts_version: Optional[str]=None,
    ):
        self.web3 = web3
        self.wait = wait
        self.owner = private_key_to_address(private_key)
        self.transaction = {'from': self.owner, 'gas': gas_limit}
        if gas_price != 0:
            self.transaction['gasPrice'] = gas_price * denoms.gwei

        self.contracts_version = contracts_version
        self.precompiled_path = contracts_precompiled_path(self.contracts_version)
        self.contract_manager = ContractManager(self.precompiled_path)
        self.web3.middleware_stack.add(
            construct_sign_and_send_raw_middleware(private_key),
        )

        # Check that the precompiled data matches the source code
        # Only for current version, because this is the only one with source code
        if self.contracts_version in [None, CONTRACTS_VERSION]:
            contract_manager_source = ContractManager(contracts_source_path())
            contract_manager_source.checksum_contracts()
            contract_manager_source.verify_precompiled_checksums(self.precompiled_path)
        else:
            log.info('Skipped checks against the source code because it is not available.')
Пример #6
0
def get_web3_client(network: str) -> Web3:
    """Returns instance of the Web3 client."""
    network_config = NETWORKS[network]
    endpoint = network_config["KEEPER_ETH1_ENDPOINT"]

    # Prefer WS over HTTP
    if endpoint.startswith("ws"):
        w3 = Web3(Web3.WebsocketProvider(endpoint, websocket_timeout=60))
        logger.warning(f"[{network}] Web3 websocket endpoint={endpoint}")
    elif endpoint.startswith("http"):
        w3 = Web3(Web3.HTTPProvider(endpoint))
        logger.warning(f"[{network}] Web3 HTTP endpoint={endpoint}")
    else:
        w3 = Web3(Web3.IPCProvider(endpoint))
        logger.warning(f"[{network}] Web3 HTTP endpoint={endpoint}")

    if network_config["IS_POA"]:
        w3.middleware_onion.inject(geth_poa_middleware, layer=0)
        logger.warning(f"[{network}] Injected POA middleware")

    account = w3.eth.account.from_key(network_config["ORACLE_PRIVATE_KEY"])
    w3.middleware_onion.add(construct_sign_and_send_raw_middleware(account))
    logger.warning(
        f"[{network}] Injected middleware for capturing transactions and sending as raw"
    )

    w3.eth.default_account = account.address
    logger.info(f"[{network}] Configured default account {w3.eth.default_account}")

    return w3
Пример #7
0
def test_sign_and_send_raw_middleware_with_byte_addresses(
        w3_dummy,
        from_converter,
        to_converter):
    private_key = PRIVATE_KEY_1
    from_ = from_converter(ADDRESS_1)
    to_ = to_converter(ADDRESS_2)

    w3_dummy.middleware_onion.add(
        construct_sign_and_send_raw_middleware(private_key))

    actual = w3_dummy.manager.request_blocking(
        'eth_sendTransaction',
        [{
            'to': to_,
            'from': from_,
            'gas': 21000,
            'gasPrice': 0,
            'value': 1,
            'nonce': 0
        }])
    raw_txn = actual[1][0]
    actual_method = actual[0]
    assert actual_method == 'eth_sendRawTransaction'
    assert isinstance(raw_txn, bytes)
Пример #8
0
def register_private_key(web3: Web3, private_key):
    assert (isinstance(web3, Web3))

    account = Account.privateKeyToAccount(private_key)

    _registered_accounts[(web3, Address(account.address))] = account
    web3.middleware_onion.add(construct_sign_and_send_raw_middleware(account))
Пример #9
0
def make_web3_provider(url: str, account: Account) -> Web3:
    w3 = Web3(HTTPProvider(url))
    w3.middleware_onion.add(simple_cache_middleware)
    if is_infura(w3):
        # Infura sometimes erroneously returns `null` for existing (but very recent) blocks.
        # Work around this by retrying those requests.
        # See docstring for details.
        Eth.getBlock = make_patched_web3_get_block(Eth.getBlock)  # type: ignore

    def gas_price_strategy_eth_gas_station_or_with_margin(web3: Web3, transaction_params):
        # FIXME: This is a temporary fix to speed up gas price generation
        # by fetching from eth_gas_station if possible.
        # Once we have a reliable gas price calculation this can be removed
        try:
            response = requests.get(ETH_GAS_STATION_API)
            if response and response.status_code == 200:
                data = response.json()
                log.debug(f"fetched gas price: {Wei(int(data['fast'] * 10e7 * 1.1))} Wei")
                return Wei(int(data["fast"] * 10e7 * 1.1))
        except (TimeoutError, ConnectionError, KeyError):
            log.debug("Could not fetch from ethgasstation. Falling back to web3 gas estimation.")

        gas_price_strategy = construct_time_based_gas_price_strategy(
            max_wait_seconds=15, sample_size=25
        )
        gas_price = Wei(int(gas_price_strategy(web3, transaction_params) * GAS_PRICE_MARGIN))
        return gas_price

    w3.eth.setGasPriceStrategy(gas_price_strategy_eth_gas_station_or_with_margin)

    if account.passphrase is not None:
        w3.middleware_onion.add(construct_sign_and_send_raw_middleware(account.private_key))
    w3.middleware_onion.inject(make_sane_poa_middleware, layer=0)

    return w3
Пример #10
0
def connect(contract_names=None, get_related=True):
    config, contract_details = read_config(contracts=contract_names,
                                           get_related=get_related)
    os.environ['WEB3_INFURA_PROJECT_ID'] = config['infura']['project_id']
    os.environ['WEB3_INFURA_API_SECRET'] = config['infura']['secret']

    if config['infura']['network'] == 'kovan':
        from web3.auto.infura.kovan import w3
    else:
        from web3.auto.infura import w3

    assert w3.isConnected()

    market_maker = w3.eth.account.from_key(config['maker']['key'])

    w3.middleware_onion.add(
        construct_sign_and_send_raw_middleware(market_maker))
    w3.eth.defaultAccount = market_maker.address

    contracts = {
        name: w3.eth.contract(address=contract_details[name]['address'],
                              abi=contract_details[name]['abi'])
        for name in contract_details
    }
    return w3, contracts
Пример #11
0
def test_sign_and_send_raw_middleware(w3_dummy, w3, method, from_, expected,
                                      key_object):
    w3_dummy.middleware_onion.add(
        construct_sign_and_send_raw_middleware(key_object))

    if isinstance(expected, type) and issubclass(expected, Exception):
        with pytest.raises(expected):
            w3_dummy.manager.request_blocking(method, [{
                'to': '0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf',
                'from': from_,
                'gas': 21000,
                'gasPrice': 0,
                'value': 1,
                'nonce': 0
            }])
    else:
        actual = w3_dummy.manager.request_blocking(method, [{
            'to': '0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf',
            'from': from_,
            'gas': 21000,
            'gasPrice': 0,
            'value': 1,
            'nonce': 0
        }])
        raw_txn = actual[1][0]
        actual_method = actual[0]
        assert actual_method == expected
        assert isinstance(raw_txn, bytes)
def connect():
    from web3.auto import w3
    from web3.middleware import construct_sign_and_send_raw_middleware

    admin = w3.eth.account.from_key('')
    w3.middleware_onion.add(construct_sign_and_send_raw_middleware(admin))
    w3.eth.defaultAccount = admin.address
    return w3, admin
Пример #13
0
def make_web3_provider(url: str, account: Account) -> Web3:
    w3 = Web3(HTTPProvider(url))
    w3.eth.setGasPriceStrategy(fast_gas_price_strategy)
    w3.middleware_onion.add(
        construct_sign_and_send_raw_middleware(account.private_key))
    w3.middleware_onion.inject(geth_poa_middleware, layer=0)

    return w3
def login_and_mint(private_key, filename):
    account = Account.from_key(private_key)
    w3 = Web3(Web3.WebsocketProvider(os.getenv("INFURA_URL")))
    w3.middleware_onion.inject(geth_poa_middleware, layer=0)
    w3.middleware_onion.add(construct_sign_and_send_raw_middleware(account))
    w3.eth.default_account = account.address
    contract = w3.eth.contract(address=os.getenv("ZORA_CONTRACT_ADDRESS"),
                               abi=get_abi())
    mint('pokemon-gpt-2-output' + '/' + filename, contract, w3)
def test_raw_transaction_address_as_string(greeter, web3, private_key_account,
                                           private_key_hex):
    # This works: Sending a transaction using the raw transaction middleware if 'from' is a hex string
    web3.middleware_stack.add(
        construct_sign_and_send_raw_middleware(private_key_hex))
    greeter.functions.payForNothing().transact({
        'value': 100,
        'from': private_key_account,
    })
Пример #16
0
 def __init__(
     self, rpc_url: URI, private_key: Path, password: Optional[Path] = None, wait: int = 10
 ):
     self.web3 = Web3(HTTPProvider(rpc_url))
     self.private_key = get_private_key(private_key, password)
     assert self.private_key is not None
     self.owner = private_key_to_address(self.private_key)
     self.wait = wait
     self.web3.middleware_onion.add(construct_sign_and_send_raw_middleware(self.private_key))
     self.web3.eth.defaultAccount = self.owner  # type: ignore
     self.web3.middleware_onion.inject(geth_poa_middleware, layer=0)
Пример #17
0
def main(
    private_key: str,
    state_db: str,  # pylint: disable=unused-argument
    web3: Web3,
    contracts: Dict[str, Contract],
    start_block: BlockNumber,  # pylint: disable=unused-argument
    service_url: str,
) -> None:
    """
    Registers the address of a service deployment with the `ServiceRegistry`.

    The address that is registered is derived from the supplied private key.
    It also sets or updates the URL of the services deployment.
    """
    # Add middleware to sign transactions by default
    web3.middleware_stack.add(construct_sign_and_send_raw_middleware(private_key))

    service_address = private_key_to_address(private_key)
    log.info("Running service registration script", account_address=service_address)

    service_registry_contract = contracts[CONTRACT_SERVICE_REGISTRY]

    # check if already registered
    currently_registered = service_registry_contract.functions.hasValidRegistration(
        service_address
    ).call()
    current_url = service_registry_contract.functions.urls(service_address).call()
    log.info(
        "Current ServiceRegistry information for service address",
        service_address=service_address,
        currently_registered=currently_registered,
        current_url=current_url,
    )

    # Register if not yet done
    if not currently_registered:
        deposit_to_registry(
            web3=web3,
            service_registry_contract=service_registry_contract,
            user_deposit_contract=contracts[CONTRACT_USER_DEPOSIT],
            service_address=service_address,
        )

    update_service_url(
        web3=web3,
        service_registry_contract=service_registry_contract,
        service_address=service_address,
        service_url=service_url,
        current_url=current_url,
    )

    current_url = service_registry_contract.functions.urls(service_address).call()

    log.info("Updated infos", current_url=current_url)
Пример #18
0
 def _check_account_from_key(self):
     try:
         account = Account()
         acct = account.from_key(config.PAYER_KEY)
         self._web3.middleware_onion.add(
             construct_sign_and_send_raw_middleware(acct))
         self._payer_account = Address(acct.address)
     except:
         self._logger.fatal(f"Account {config.PAYER_ADDRESS} register key error")
         return False
     return True
def test_raw_transaction_address_as_bytes(greeter, web3, private_key_account,
                                          private_key_hex):
    # This doesn't work: Sending a transaction using the raw transaction middleware if 'from' is bytes
    # (instead, with eth_tester it raises AccountLocked)
    web3.middleware_stack.add(
        construct_sign_and_send_raw_middleware(private_key_hex))
    private_key_account_as_bytes = to_bytes(hexstr=private_key_account)
    greeter.functions.payForNothing().transact({
        'value':
        100,
        'from':
        private_key_account_as_bytes,
    })
def test_raw_transaction_address_as_bytes_inject_layer_0(
        greeter, web3, private_key_account, private_key_hex):
    # This doesn't work: passing from as bytes address when injecting raw transaction middleware to layer 0
    # (different error than test_raw_transaction_address_as_bytes)
    web3.middleware_stack.inject(
        construct_sign_and_send_raw_middleware(private_key_hex), layer=0)
    private_key_account_as_bytes = to_bytes(hexstr=private_key_account)
    greeter.functions.payForNothing().transact({
        'value':
        100,
        'from':
        private_key_account_as_bytes,
    })
Пример #21
0
def web3_foreign(node_foreign, accounts, account_keys):
    web3 = Web3(HTTPProvider(FOREIGN_RPC_URL))
    web3.middleware_onion.add(
        construct_sign_and_send_raw_middleware(account_keys))
    for account in accounts[1:]:
        wait_for_successful_transaction_receipt(
            web3,
            web3.eth.sendTransaction({
                "from": accounts[0],
                "to": account,
                "value": START_WEI_PER_ACCOUNT
            }),
        )
    return web3
Пример #22
0
    def __init__(  # pylint: disable=too-many-arguments
        self,
        web3: Web3,
        private_key: PrivateKey,
        db_filename: str,
        contracts: Dict[str, Contract],
        sync_start_block: BlockNumber,
        required_confirmations: BlockTimeout,
        poll_interval: float,
        min_reward: int = 0,
        get_timestamp_now: Callable = get_posix_utc_time_now,
    ):
        self.web3 = web3
        self.chain_id = ChainID(web3.eth.chain_id)
        self.private_key = private_key
        self.address = private_key_to_address(private_key)
        self.poll_interval = poll_interval
        self.service_registry = contracts[CONTRACT_SERVICE_REGISTRY]
        self.token_network_registry = contracts[
            CONTRACT_TOKEN_NETWORK_REGISTRY]
        self.get_timestamp_now = get_timestamp_now
        self.try_scheduled_events_after = get_timestamp_now()

        web3.middleware_onion.add(
            construct_sign_and_send_raw_middleware(private_key))

        monitoring_contract = contracts[CONTRACT_MONITORING_SERVICE]
        user_deposit_contract = contracts[CONTRACT_USER_DEPOSIT]

        self.database = Database(
            filename=db_filename,
            chain_id=self.chain_id,
            registry_address=to_canonical_address(
                self.token_network_registry.address),
            receiver=self.address,
            msc_address=MonitoringServiceAddress(
                to_canonical_address(monitoring_contract.address)),
            sync_start_block=sync_start_block,
        )
        ms_state = self.database.load_state()

        self.context = Context(
            ms_state=ms_state,
            database=self.database,
            web3=self.web3,
            monitoring_service_contract=monitoring_contract,
            user_deposit_contract=user_deposit_contract,
            min_reward=min_reward,
            required_confirmations=required_confirmations,
        )
Пример #23
0
def withdraw_cmd(
    private_key: str,
    state_db: str,  # pylint: disable=unused-argument
    web3: Web3,
    contracts: Dict[str, Contract],
    start_block: BlockNumber,
    to: Optional[Address],
) -> None:
    """
    Withdraw tokens deposited to the ServiceRegistry.
    """
    # Add middleware to sign transactions by default
    web3.middleware_onion.add(construct_sign_and_send_raw_middleware(private_key))

    withdraw(private_key, web3, contracts, start_block, to)
Пример #24
0
    def _check_keeper_account(self):
        with open(config.KEEPER_KEY_FILE) as f:
            read_key = f.read().replace("\n","")

        # check account with key
        try:
            account = Account()
            acct = account.from_key(read_key)
            self.web3.middleware_onion.add(construct_sign_and_send_raw_middleware(acct))
            self.keeper_account = Address(acct.address)
            self.keeper_account_key = read_key
        except Exception as e:
            self.logger.warning(f"check private key error: {e}")
            return False
            
        return True
Пример #25
0
def connect():
    credentials = json.loads(os.environ.get('CREDENTIALS'))
    os.environ['WEB3_INFURA_PROJECT_ID'] = credentials['infura']['project_id']
    os.environ['WEB3_INFURA_API_SECRET'] = credentials['infura']['secret']

    if credentials['infura']['network'] == 'kovan':
        from web3.auto.infura.kovan import w3
    else:
        from web3.auto.infura import w3

    assert w3.isConnected()

    acct = w3.eth.account.from_key(credentials['mainnet']['key'])
    w3.middleware_onion.add(construct_sign_and_send_raw_middleware(acct))
    w3.eth.defaultAccount = acct.address

    return w3
Пример #26
0
def get_votes_from_blochchain(spec_hash):
    w3 = Web3(Web3.HTTPProvider(PROVIDER_HTTP_ENDPOINT))
    acct = Account.from_key(PRIVATE_KEY)
    abi = json.load(open("voting.json"))

    VotingAlpha = w3.eth.contract(address=CONTRACT_ADDRESS, abi=abi)

    w3.middleware_onion.add(
        construct_sign_and_send_raw_middleware(acct.privateKey))
    print(spec_hash)
    p_id = VotingAlpha.functions.getProposalId(spec_hash.replace("0x0x",
                                                                 "0x")).call()
    proposalInfo = VotingAlpha.functions.getProposal(p_id).call()

    print("No votes:", proposalInfo[3])
    print("Yes votes:", proposalInfo[4])
    return (proposalInfo[4], proposalInfo[3])
Пример #27
0
def main(rpc_url: URI, private_key: Path, token_address: ChecksumAddress, amount: int) -> None:
    web3 = Web3(HTTPProvider(rpc_url))
    privkey = get_private_key(private_key)
    assert privkey is not None
    owner = private_key_to_address(privkey)
    web3.middleware_onion.add(construct_sign_and_send_raw_middleware(privkey))
    token_code = web3.eth.get_code(token_address, "latest")
    assert token_code != HexBytes("")
    token_contract = ContractManager(contracts_precompiled_path()).get_contract(
        CONTRACT_CUSTOM_TOKEN
    )
    token_proxy = web3.eth.contract(address=token_address, abi=token_contract["abi"])
    tx_hash = token_proxy.functions.mint(amount).transact({"from": owner})
    print(f"Minting tokens for address {owner}")
    print(f"Transaction hash {encode_hex(tx_hash)}")
    balance = token_proxy.functions.balanceOf(owner).call()
    print(f"Balance of {owner}: {balance}")
Пример #28
0
    def initialize(self, account, estimate_gas_only=False):

        # to make it easier to deploy and interact with the contract, tell Web3 to use a specific account
        #  when sending transactions
        if account:
            self.simple_web3.middleware_onion.add(
                construct_sign_and_send_raw_middleware(account))
            self.simple_web3.eth.default_account = account.address

        # load ABI from file if it was supplied
        if self.abi_filepath and os.path.exists(self.abi_filepath):
            print(f'Loading ABI from {self.abi_filepath}')
            with open(self.abi_filepath) as f:
                self.abi = json.load(f)

        # load bytecode from file if it was supplied
        if self.bytecode_filepath and os.path.exists(self.bytecode_filepath):
            print(f'Loading bytecode from {self.bytecode_filepath}')
            with open(self.bytecode_filepath) as f:
                self.bytecode = f.read()

        # if we couldn't load the ABI then we need to compile ourselves
        if not self.abi:
            self.compile()

        # if an address was supplied then use that to initialize the contract
        if self.address:
            print(f'Loading existing contract at address {self.address}')
            self.contract = self.simple_web3.eth.contract(address=self.address,
                                                          abi=self.abi)
            print(f'Existing contract with address {self.address} initialized')

        # otherwise we need to deploy a new contract
        else:
            print(f'Deploying new contract {self.name}')
            self.deploy(estimate_gas_only=estimate_gas_only)

            if not estimate_gas_only:
                # sometimes there is a delay after deploying a contract so we
                #  need to wait until its for sure available
                code = self.simple_web3.eth.getCode(self.address)
                while code in ['0x', '0x0']:
                    print('contract not found? waiting...')
                    time.sleep(1)

                print('New contract initialized')
Пример #29
0
    def __init__(  # pylint: disable=too-many-arguments
        self,
        web3: Web3,
        private_key: str,
        db_filename: str,
        contracts: Dict[str, Contract],
        sync_start_block: BlockNumber = BlockNumber(0),
        required_confirmations: int = DEFAULT_NUMBER_OF_BLOCK_CONFIRMATIONS,
        poll_interval: float = 1,
        min_reward: int = 0,
    ):
        self.web3 = web3
        self.private_key = private_key
        self.address = private_key_to_address(private_key)
        self.required_confirmations = required_confirmations
        self.poll_interval = poll_interval
        self.service_registry = contracts[CONTRACT_SERVICE_REGISTRY]

        web3.middleware_stack.add(
            construct_sign_and_send_raw_middleware(private_key))

        monitoring_contract = contracts[CONTRACT_MONITORING_SERVICE]
        user_deposit_contract = contracts[CONTRACT_USER_DEPOSIT]

        chain_id = ChainID(int(web3.net.version))
        self.database = Database(
            filename=db_filename,
            chain_id=chain_id,
            registry_address=contracts[CONTRACT_TOKEN_NETWORK_REGISTRY].
            address,
            receiver=self.address,
            msc_address=monitoring_contract.address,
            sync_start_block=sync_start_block,
        )
        ms_state = self.database.load_state()

        self.context = Context(
            ms_state=ms_state,
            db=self.database,
            web3=self.web3,
            monitoring_service_contract=monitoring_contract,
            user_deposit_contract=user_deposit_contract,
            min_reward=min_reward,
            required_confirmations=required_confirmations,
        )
def test_raw_transaction_contract_address_as_bytes(greeter, web3,
                                                   private_key_account,
                                                   private_key_hex):
    # This doesn't work: passing contract address as bytes when USING raw transaction middleware
    web3.middleware_stack.add(
        construct_sign_and_send_raw_middleware(private_key_hex))
    greeter_address_bytes = to_bytes(hexstr=greeter.address)
    assert to_checksum_address(
        greeter_address_bytes) == greeter.address  # sanity check

    wrapped_greeter = web3.eth.contract(address=greeter_address_bytes,
                                        abi=greeter.abi)
    wrapped_greeter.functions.payForNothing().transact({
        'value':
        100,
        'from':
        private_key_account,
    })
Пример #31
0
def test_signed_transaction(w3, fund_account, transaction, expected,
                            key_object, from_):
    w3.middleware_onion.add(construct_sign_and_send_raw_middleware(key_object))

    # Drop any falsy addresses
    to_from = valfilter(bool, {'to': w3.eth.accounts[0], 'from': from_})

    _transaction = merge(transaction, to_from)

    if isinstance(expected, type) and issubclass(expected, Exception):
        with pytest.raises(expected):
            w3.eth.send_transaction(_transaction)
    else:
        start_balance = w3.eth.get_balance(
            _transaction.get('from', w3.eth.accounts[0]))
        w3.eth.send_transaction(_transaction)
        assert w3.eth.get_balance(
            _transaction.get('from')) <= start_balance + expected
Пример #32
0
def test_signed_transaction(
        w3,
        fund_account,
        transaction,
        expected,
        key_object,
        from_):
    w3.middleware_stack.add(construct_sign_and_send_raw_middleware(key_object))

    # Drop any falsy addresses
    to_from = valfilter(bool, {'to': w3.eth.accounts[0], 'from': from_})

    _transaction = merge(transaction, to_from)

    if isinstance(expected, type) and issubclass(expected, Exception):
        with pytest.raises(expected):
            start_balance = w3.eth.getBalance(_transaction.get('from', w3.eth.accounts[0]))
            w3.eth.sendTransaction(_transaction)
    else:
        start_balance = w3.eth.getBalance(_transaction.get('from', w3.eth.accounts[0]))
        w3.eth.sendTransaction(_transaction)
        assert w3.eth.getBalance(_transaction.get('from')) <= start_balance + expected
Пример #33
0
def test_sign_and_send_raw_middleware(
        w3_dummy,
        w3,
        method,
        from_,
        expected,
        key_object):
    w3_dummy.middleware_stack.add(
        construct_sign_and_send_raw_middleware(key_object))

    if isinstance(expected, type) and issubclass(expected, Exception):
        with pytest.raises(expected):
            w3_dummy.manager.request_blocking(
                method,
                [{
                    'to': '0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf',
                    'from': from_,
                    'gas': 21000,
                    'gasPrice': 0,
                    'value': 1,
                    'nonce': 0
                }])
    else:
        actual = w3_dummy.manager.request_blocking(
            method,
            [{
                'to': '0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf',
                'from': from_,
                'gas': 21000,
                'gasPrice': 0,
                'value': 1,
                'nonce': 0
            }])
        raw_txn = actual[1][0]
        actual_method = actual[0]
        assert actual_method == expected
        assert isinstance(raw_txn, bytes)