def test_auto_gas_computation_when_transacting(web3,
                                               STRING_CONTRACT,
                                               skip_if_testrpc,
                                               wait_for_block,
                                               call,
                                               transact):
    skip_if_testrpc(web3)

    wait_for_block(web3)

    StringContract = web3.eth.contract(**STRING_CONTRACT)

    deploy_txn = StringContract.deploy(args=["Caqalai"])
    deploy_receipt = wait_for_transaction_receipt(web3, deploy_txn, 30)
    assert deploy_receipt is not None
    string_contract = StringContract(address=deploy_receipt['contractAddress'])

    gas_estimate = string_contract.functions.setValue(to_bytes(text="ÄLÄMÖLÖ")).estimateGas()

    # eth_abi will pass as raw bytes, no encoding
    # unless we encode ourselves
    txn_hash = transact(contract=string_contract,
                        contract_function="setValue",
                        func_args=[to_bytes(text="ÄLÄMÖLÖ")])
    txn_receipt = wait_for_transaction_receipt(web3, txn_hash, 30)
    assert txn_receipt is not None

    final_value = call(contract=string_contract,
                       contract_function='getValue')
    assert to_bytes(text=final_value) == to_bytes(text="ÄLÄMÖLÖ")

    txn = web3.eth.getTransaction(txn_hash)
    assert txn['gas'] == gas_estimate + 100000
def test_auto_gas_computation_when_transacting(web3, STRING_CONTRACT,
                                               skip_if_testrpc,
                                               wait_for_block):
    skip_if_testrpc(web3)

    wait_for_block(web3)

    StringContract = web3.eth.contract(**STRING_CONTRACT)

    deploy_txn = StringContract.deploy(args=["Caqalai"])
    deploy_receipt = wait_for_transaction_receipt(web3, deploy_txn, 30)
    assert deploy_receipt is not None
    string_contract = StringContract(address=deploy_receipt['contractAddress'])

    gas_estimate = string_contract.estimateGas().setValue(
        force_bytes("ÄLÄMÖLÖ"))

    # eth_abi will pass as raw bytes, no encoding
    # unless we encode ourselves
    txn_hash = string_contract.transact().setValue(force_bytes("ÄLÄMÖLÖ"))
    txn_receipt = wait_for_transaction_receipt(web3, txn_hash, 30)
    assert txn_receipt is not None

    final_value = string_contract.call().getValue()
    assert force_bytes(final_value) == force_bytes("ÄLÄMÖLÖ")

    txn = web3.eth.getTransaction(txn_hash)
    assert txn['gas'] == gas_estimate + 100000
Пример #3
0
def test_transacting_with_contract_respects_explicit_gas(
        web3, STRING_CONTRACT, skip_if_testrpc, wait_for_block, call,
        transact):
    skip_if_testrpc(web3)

    wait_for_block(web3)

    StringContract = web3.eth.contract(**STRING_CONTRACT)

    deploy_txn = StringContract.deploy(args=["Caqalai"])
    deploy_receipt = wait_for_transaction_receipt(web3, deploy_txn, 30)
    assert deploy_receipt is not None
    string_contract = StringContract(address=deploy_receipt['contractAddress'])

    # eth_abi will pass as raw bytes, no encoding
    # unless we encode ourselves
    txn_hash = transact(contract=string_contract,
                        contract_function='setValue',
                        func_args=[to_bytes(text="ÄLÄMÖLÖ")],
                        tx_kwargs={'gas': 200000})
    txn_receipt = wait_for_transaction_receipt(web3, txn_hash, 30)
    assert txn_receipt is not None

    final_value = call(contract=string_contract, contract_function='getValue')
    assert to_bytes(text=final_value) == to_bytes(text="ÄLÄMÖLÖ")

    txn = web3.eth.getTransaction(txn_hash)
    assert txn['gas'] == 200000
def test_transacting_with_contract_respects_explicit_gas(web3,
                                                         STRING_CONTRACT,
                                                         skip_if_testrpc,
                                                         wait_for_block):
    skip_if_testrpc(web3)

    wait_for_block(web3)

    StringContract = web3.eth.contract(**STRING_CONTRACT)

    deploy_txn = StringContract.deploy(args=["Caqalai"])
    deploy_receipt = wait_for_transaction_receipt(web3, deploy_txn, 30)
    assert deploy_receipt is not None
    string_contract = StringContract(address=deploy_receipt['contractAddress'])

    # eth_abi will pass as raw bytes, no encoding
    # unless we encode ourselves
    txn_hash = string_contract.functions.setValue(force_bytes("ÄLÄMÖLÖ")).transact({'gas': 200000})
    txn_receipt = wait_for_transaction_receipt(web3, txn_hash, 30)
    assert txn_receipt is not None

    final_value = string_contract.functions.getValue().call()
    assert force_bytes(final_value) == force_bytes("ÄLÄMÖLÖ")

    txn = web3.eth.getTransaction(txn_hash)
    assert txn['gas'] == 200000
Пример #5
0
def test_auto_gas_computation_when_transacting(web3, STRING_CONTRACT,
                                               skip_if_testrpc, wait_for_block,
                                               call, transact):
    skip_if_testrpc(web3)

    wait_for_block(web3)

    StringContract = web3.eth.contract(**STRING_CONTRACT)

    deploy_txn = StringContract.deploy(args=["Caqalai"])
    deploy_receipt = wait_for_transaction_receipt(web3, deploy_txn, 30)
    assert deploy_receipt is not None
    string_contract = StringContract(address=deploy_receipt['contractAddress'])

    gas_estimate = string_contract.functions.setValue(
        to_bytes(text="ÄLÄMÖLÖ")).estimateGas()

    # eth_abi will pass as raw bytes, no encoding
    # unless we encode ourselves
    txn_hash = transact(contract=string_contract,
                        contract_function="setValue",
                        func_args=[to_bytes(text="ÄLÄMÖLÖ")])
    txn_receipt = wait_for_transaction_receipt(web3, txn_hash, 30)
    assert txn_receipt is not None

    final_value = call(contract=string_contract, contract_function='getValue')
    assert to_bytes(text=final_value) == to_bytes(text="ÄLÄMÖLÖ")

    txn = web3.eth.getTransaction(txn_hash)
    assert txn['gas'] == gas_estimate + 100000
def test_transacting_with_contract_respects_explicit_gas(web3,
                                                         STRING_CONTRACT,
                                                         skip_if_testrpc,
                                                         wait_for_block,
                                                         call,
                                                         transact):
    skip_if_testrpc(web3)

    wait_for_block(web3)

    StringContract = web3.eth.contract(**STRING_CONTRACT)

    deploy_txn = StringContract.deploy(args=["Caqalai"])
    deploy_receipt = wait_for_transaction_receipt(web3, deploy_txn, 30)
    assert deploy_receipt is not None
    string_contract = StringContract(address=deploy_receipt['contractAddress'])

    # eth_abi will pass as raw bytes, no encoding
    # unless we encode ourselves
    txn_hash = transact(contract=string_contract,
                        contract_function='setValue',
                        func_args=[to_bytes(text="ÄLÄMÖLÖ")],
                        tx_kwargs={'gas': 200000})
    txn_receipt = wait_for_transaction_receipt(web3, txn_hash, 30)
    assert txn_receipt is not None

    final_value = call(contract=string_contract,
                       contract_function='getValue')
    assert to_bytes(text=final_value) == to_bytes(text="ÄLÄMÖLÖ")

    txn = web3.eth.getTransaction(txn_hash)
    assert txn['gas'] == 200000
Пример #7
0
def connected_data(web3, data, constants, mp3, user0):
    _priv, owner = user0
    # Constants
    txhash = data.setConstantsAddress(constants.address,
                                      transact={'from': owner})
    receipt = wait_for_transaction_receipt(web3, txhash)
    assert receipt is not None
    assert data.constantsAddress() == constants.address
    # Mp3
    txhash = data.setMP3Address(mp3.address, transact={'from': owner})
    receipt = wait_for_transaction_receipt(web3, txhash)
    assert receipt is not None
    assert data.constantsAddress() == constants.address
    return data
Пример #8
0
def check_succesful_tx(web3: Web3, txid: str, timeout=600) -> dict:
    """See if transaction went through (Solidity code did not throw).

    :return: Transaction receipt
    """

    # http://ethereum.stackexchange.com/q/6007/620
    receipt = wait_for_transaction_receipt(web3, txid, timeout=timeout)
    txinfo = web3.eth.getTransaction(txid)
    if not txinfo:
        # This is some sort of geth flakiness issue, not sure what
        # Try to mitigate it with timeout
        time.sleep(1.0)
        txinfo = web3.eth.getTransaction(txid)

    if receipt is None:
        raise RuntimeError("Did not get receipt for {}".format(txid))

    if txinfo is None:
        raise RuntimeError("Did not get txinfo for {}".format(txid))

    # EVM has only one error mode and it's consume all gas
    if txinfo["gas"] == receipt["gasUsed"]:
        raise TransactionFailure("Transaction failed: {}".format(txid))
    return receipt
Пример #9
0
def confirm_transaction(web3: Web3, txid: str, timeout=60) -> dict:
    """Make sure a transaction was correctly performed.

    Confirm that

    * The transaction has been mined in blockchain

    * The transaction did not throw an error (used up all its gas)

    http://ethereum.stackexchange.com/q/6007/620

    :raise TransactionConfirmationError: If we did not get it confirmed in time
    :return: Transaction receipt
    """

    try:
        receipt = wait_for_transaction_receipt(web3, txid, timeout)
    except gevent.Timeout as e:
        raise TransactionConfirmationError("Could not confirm tx {} within timeout {}".format(txid, timeout)) from e

    tx = web3.eth.getTransaction(txid)

    if tx["gas"] == receipt["gasUsed"]:
        raise TransactionConfirmationError("Transaction failed (out of gas, thrown): {} - given gas {}".format(txid, tx["gas"]))

    return receipt
Пример #10
0
def confirm_transaction(web3: Web3, txid: str, timeout=60) -> dict:
    """Make sure a transaction was correctly performed.

    Confirm that

    * The transaction has been mined in blockchain

    * The transaction did not throw an error (used up all its gas)

    http://ethereum.stackexchange.com/q/6007/620

    :raise TransactionConfirmationError: If we did not get it confirmed in time
    :return: Transaction receipt
    """

    try:
        receipt = wait_for_transaction_receipt(web3, txid, timeout)
    except Timeout as e:
        raise TransactionConfirmationError(
            "Could not confirm tx {} within timeout {}".format(txid,
                                                               timeout)) from e

    tx = web3.eth.getTransaction(txid)

    if tx["gas"] == receipt["gasUsed"]:
        raise TransactionConfirmationError(
            "Transaction failed (out of gas, thrown): {} - given gas {}".
            format(txid, tx["gas"]))

    return receipt
Пример #11
0
def register_service(
        web3: Web3,
        contract_manager: ContractManager,
        msc_contract_address: str,
        private_key: str,
        deposit: int = 10,  # any amount works now
):
    """Register service with a Monitor service contract"""
    service_address = private_key_to_address(private_key)
    assert is_checksum_address(msc_contract_address)
    assert is_checksum_address(service_address)
    monitor_contract_abi = contract_manager.get_contract_abi(
        CONTRACT_MONITORING_SERVICE)
    monitor_contract = PrivateContract(
        web3.eth.contract(
            abi=monitor_contract_abi,
            address=msc_contract_address,
        ))
    bundle_contract_abi = contract_manager.get_contract_abi(
        CONTRACT_RAIDEN_SERVICE_BUNDLE)
    raiden_service_bundle_address = to_checksum_address(
        monitor_contract.functions.rsb().call())
    bundle_contract = PrivateContract(
        web3.eth.contract(
            abi=bundle_contract_abi,
            address=raiden_service_bundle_address,
        ))

    # approve funds for MSC
    token_address = to_checksum_address(
        monitor_contract.functions.token().call())
    token_abi = contract_manager.get_contract_abi('Token')
    token_contract = web3.eth.contract(abi=token_abi, address=token_address)
    token_contract = PrivateContract(token_contract)
    tx = token_contract.functions.approve(raiden_service_bundle_address,
                                          deposit).transact(
                                              private_key=private_key, )
    wait_for_transaction_receipt(web3, tx)

    # register MS
    tx = bundle_contract.functions.deposit(deposit).transact(
        private_key=private_key, )
    # check if MS is really registered
    wait_for_transaction_receipt(web3, tx)
    return bundle_contract.functions.deposits(service_address).call() > 0
Пример #12
0
def data(web3, Data, constants, user0):
    _priv, owner = user0
    deploy_txn = Data.deploy()
    deploy_receipt = wait_for_transaction_receipt(web3, deploy_txn)
    assert deploy_receipt is not None
    _contract = Data(address=deploy_receipt['contractAddress'])
    concise_contract = ConciseContract(_contract)
    assert owner == concise_contract.owner()
    return concise_contract
Пример #13
0
def mp3(web3, Mp3, user0):
    _priv, owner = user0
    deploy_txn = Mp3.deploy()
    deploy_receipt = wait_for_transaction_receipt(web3, deploy_txn)
    assert deploy_receipt is not None
    _contract = Mp3(address=deploy_receipt['contractAddress'])
    concise_contract = ConciseContract(_contract)
    assert owner == concise_contract.owner()
    return concise_contract
Пример #14
0
def upload_metadata(web3, data, addr, trackhash, key, value):
    txhash = data.uploadMetadata(
        trackhash,
        key,
        value,
        addr,
        transact={'from': addr},
    )
    txn_receipt = wait_for_transaction_receipt(web3, txhash)
    assert txn_receipt is not None
Пример #15
0
def crowdsale(web3, Crowdsale, user0, user2):
    _priv, owner = user0
    _priv, crowdsale_wallet = user2
    deploy_txn = Crowdsale.deploy(args=[crowdsale_wallet])
    deploy_receipt = wait_for_transaction_receipt(web3, deploy_txn)
    assert deploy_receipt is not None
    _contract = Crowdsale(address=deploy_receipt['contractAddress'])
    concise_contract = ConciseContract(_contract)
    assert owner == concise_contract.owner()
    return concise_contract
Пример #16
0
def upload_track(web3, data, addr, hash_function, size, trackhash, artist,
                 title):
    txhash = data.uploadTrack(
        hash_function,
        size,
        trackhash,
        artist,
        title,
        transact={'from': addr},
    )
    txn_receipt = wait_for_transaction_receipt(web3, txhash)
    assert txn_receipt is not None
Пример #17
0
def transfer(w3, privkey, to, value, data):
    address = w3.eth.account.privateKeyToAccount(privkey).address

    tx_dict = {
        'nonce': w3.eth.getTransactionCount(address),
        'to': to,
        'value': value,
        'data': data,
        'gas': 100000,
        'gasPrice': int(w3.eth.gasPrice),
        'chainId': int(w3.admin.nodeInfo.protocols.eth.config.chainId)
    }

    raw_tx = w3.eth.account.signTransaction(tx_dict, privkey)['rawTransaction']

    tx_hash = w3.eth.sendRawTransaction(raw_tx)
    tx_hash = Web3.toHex(tx_hash)

    wait_for_transaction_receipt(w3, tx_hash)

    return tx_hash
Пример #18
0
def check_succesful_tx(web3: Web3, txid: str, timeout=180) -> dict:
    """See if transaction went through (Solidity code did not throw).

    :return: Transaction receipt
    """

    # http://ethereum.stackexchange.com/q/6007/620
    receipt = wait_for_transaction_receipt(web3, txid, timeout=timeout)
    txinfo = web3.eth.getTransaction(txid)

    # EVM has only one error mode and it's consume all gas
    assert txinfo["gas"] != receipt["gasUsed"]
    return receipt
Пример #19
0
def deploy_contract(w3, contract_name, account, args=None):
    contract_compiled = compile_files([
        CONTRACT_DIR + contract_name + '.sol'
    ])[CONTRACT_DIR + contract_name + '.sol:' + contract_name]
    contract = w3.eth.contract(abi=contract_compiled['abi'],
                               bytecode=contract_compiled['bin'])

    tx_hash = contract.deploy(args=args, transaction={'from': account})
    tx_receipt = wait_for_transaction_receipt(w3, tx_hash)

    contract_address = tx_receipt['contractAddress']

    return contract_address
Пример #20
0
def register_service(
    web3: Web3,
    msc_contract_address: str,
    private_key: str,
    deposit: int = 10  # any amount works now
):
    """Register service with a Monitor service contract"""
    service_address = private_key_to_address(private_key)
    assert is_checksum_address(msc_contract_address)
    assert is_checksum_address(service_address)
    monitor_contract_abi = CONTRACT_MANAGER.get_contract_abi('MonitoringService')
    monitor_contract = PrivateContract(web3.eth.contract(
        abi=monitor_contract_abi,
        address=msc_contract_address
    ))
    bundle_contract_abi = CONTRACT_MANAGER.get_contract_abi('RaidenServiceBundle')
    raiden_service_bundle_address = to_checksum_address(monitor_contract.functions.rsb().call())
    bundle_contract = PrivateContract(web3.eth.contract(
        abi=bundle_contract_abi,
        address=raiden_service_bundle_address
    ))

    # approve funds for MSC
    token_address = to_checksum_address(monitor_contract.functions.token().call())
    token_abi = CONTRACT_MANAGER.get_contract_abi('Token')
    token_contract = web3.eth.contract(abi=token_abi, address=token_address)
    token_contract = PrivateContract(token_contract)
    tx = token_contract.functions.approve(raiden_service_bundle_address, deposit).transact(
        private_key=private_key
    )
    wait_for_transaction_receipt(web3, tx)

    # register MS
    tx = bundle_contract.functions.deposit(deposit).transact(
        private_key=private_key
    )
    # check if MS is really registered
    wait_for_transaction_receipt(web3, tx)
    return bundle_contract.functions.deposits(service_address).call() > 0
Пример #21
0
def check_succesful_tx(web3: Web3, txid: str, timeout=180) -> dict:
    """See if transaction went through (Solidity code did not throw).

    :return: Transaction receipt
    """

    # http://ethereum.stackexchange.com/q/6007/620
    receipt = wait_for_transaction_receipt(web3, txid, timeout=timeout)
    txinfo = web3.eth.getTransaction(txid)

    # EVM has only one error mode and it's consume all gas
    if txinfo["gas"] == receipt["gasUsed"]:
        raise TransactionFailure("Transaction failed: {}".format(txid))
    return receipt
Пример #22
0
def check_succesful_tx(web3: Union[Web3, Contract],
                       txid: str,
                       timeout=180) -> bool:
    """See if transaction went through (Solidity code did not throw)"""

    if isinstance(web3, Contract):
        web3 = web3.web3

    # http://ethereum.stackexchange.com/q/6007/620
    receipt = wait_for_transaction_receipt(web3, txid, timeout=timeout)
    txinfo = web3.eth.getTransaction(txid)

    # EVM has only one error mode and it's consume all gas
    return txinfo["gas"] != receipt["gasUsed"]
Пример #23
0
            # deploy ServiceProviderWallet
            spw_address = deploy_contract(w3, 'ServiceProviderWallet', actor)

            # deploy ManagementContract
            mgmt_address = deploy_contract(w3, 'ManagementContract', actor,
                                           [spw_address, service_fee])

            # deploy BatteryManagement
            bmgmt_address = deploy_contract(w3, 'BatteryManagement', actor,
                                            [mgmt_address, erc20_address])

            management_contract = w3.eth.contract(
                mgmt_address, abi=get_abi('ManagementContract'))
            tx_hash = management_contract.functions.setBatteryManagementContract(
                bmgmt_address).transact({'from': actor})
            wait_for_transaction_receipt(w3, tx_hash)

            with open('database.json', 'w') as database_file:
                json.dump({'mgmtContract': mgmt_address}, database_file)

            print('Management contract: ' + mgmt_address)
            print('Wallet contract: ' + spw_address)
            print('Currency contract: ' + erc20_address)

        elif args.setfee:
            new_fee = int(float(args.setfee) * (10**18))

            with open('database.json') as database_file:
                management_address = json.load(database_file)['mgmtContract']

            management_contract = w3.eth.contract(
Пример #24
0
 def waitForTransactionReceipt(self, transaction_hash, timeout=120):
     return wait_for_transaction_receipt(self.web3, transaction_hash,
                                         timeout)
Пример #25
0
tokenContractAddress = web3.toChecksumAddress(
    test_env['token_contract_address'])

#----------------------------------------------------------------------------
# Read ABI
#----------------------------------------------------------------------------
with open(_abiFile) as f:
    _contractABI = json.load(f)
f.close()
#print(_contractABI[0])

ContractFactory = web3.eth.contract(abi=_contractABI, )

# Assuminng that the account is unlocked and script is run on the same
# machine where validator is run.
#web3.personal.unlockAccount(actor, "11", 30)

BridgeContract = ContractFactory(bridgeContractAddress)

print("Set contract address...")

txHash = BridgeContract.functions.setTokenAddress(
    tokenContractAddress).transact(transaction=_txTempl)
wait_for_transaction_receipt(web3, txHash)

print("Check that new configuration reflected in the contract...")
print("ERC20 token used by bridge:",
      BridgeContract.functions.erc20token().call())

sys.exit(0)
Пример #26
0
def wait_tx(web3: Web3, txid: str):
    return wait_for_transaction_receipt(web3, txid, 60)
Пример #27
0
def wait_tx(web3: Web3, txid: str):
    return wait_for_transaction_receipt(web3, txid, 60)
Пример #28
0
def handle_transaction(txn_func, *args, **kwargs) -> AttributeDict:
    """Handles a transaction that updates the contract state by locally
    signing, building, sending the transaction and returning a transaction
    receipt.

    >>> credentials = {
    ... 	"gas_payer": "0x1413862C2B7054CDbfdc181B83962CB0FC11fD92",
    ... 	"gas_payer_priv": "28e516f1e2f99e96a48a23cea1f94ee5f073403a1c68e818263f0eb898f1c8e5"
    ... }
    >>> rep_oracle_pub_key = b"2dbc2c2c86052702e7c219339514b2e8bd4687ba1236c478ad41b43330b08488c12c8c1797aa181f3a4596a1bd8a0c18344ea44d6655f61fa73e56e743f79e0d"
    >>> job = Job(credentials=credentials, escrow_manifest=manifest)
    >>> job.launch(rep_oracle_pub_key)
    True

    >>> gas = 4712388
    >>> hmt_amount = int(job.amount * 10**18)
    >>> hmtoken_contract = get_hmtoken()
    >>> txn_func = hmtoken_contract.functions.transfer
    >>> func_args = [job.job_contract.address, hmt_amount]
    >>> txn_info = {
    ... "gas_payer": job.gas_payer,
    ... "gas_payer_priv": job.gas_payer_priv,
    ... "gas": gas
    ... }
    >>> txn_receipt = handle_transaction(txn_func, *func_args, **txn_info)
    >>> type(txn_receipt)
    <class 'web3.datastructures.AttributeDict'>

    Args:
        txn_func: the transaction function to be handled.

        \*args: all the arguments the function takes.

        \*\*kwargs: the transaction data used to complete the transaction.

    Returns:
        AttributeDict: returns the transaction receipt.

    Raises:
        TimeoutError: if waiting for the transaction receipt times out.
    """
    gas_payer = kwargs["gas_payer"]
    gas_payer_priv = kwargs["gas_payer_priv"]
    gas = kwargs["gas"]

    w3 = get_w3()
    nonce = w3.eth.getTransactionCount(gas_payer)

    txn_dict = txn_func(*args).buildTransaction({
        "from": gas_payer,
        "gas": gas,
        "nonce": nonce
    })

    signed_txn = w3.eth.account.signTransaction(txn_dict,
                                                private_key=gas_payer_priv)
    txn_hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)

    try:
        txn_receipt = wait_for_transaction_receipt(
            w3, txn_hash, timeout=WEB3_TIMEOUT, poll_latency=WEB3_POLL_LATENCY)
    except TimeoutError as e:
        raise e
    return txn_receipt