Пример #1
0
def userA_has_some_amount_of_eth_in_root_chain(context, amount):
    userA_balance = w3.eth.getBalance(userA)
    assert_msg = 'userA balance in {} does not match expected amount: {} in eth'.format(
        w3.fromWei(userA_balance, 'ether'), amount)
    assert w3.toWei(amount, 'ether') == userA_balance, assert_msg

    userB_balance = w3.eth.getBalance(userB)
    assert_msg = 'userB balance in {} does not match expected amount: {} in eth'.format(
        w3.fromWei(userB_balance, 'ether'), amount)
    assert w3.toWei(amount, 'ether') == userB_balance, assert_msg
Пример #2
0
def show_balance(libra_client, lib_account1, lib_account2, eth_account1,
                 eth_account2):
    lib_state1 = libra_client.get_account_state(lib_account1.address)
    lib_state2 = libra_client.get_account_state(lib_account2.address)
    eth_balance1 = w3.fromWei(w3.eth.getBalance(eth_account1), 'ether')
    eth_balance2 = w3.fromWei(w3.eth.getBalance(eth_account2), 'ether')

    print(
        f"A's LIB address: {lib_account1.address} ({lib_state1.balance / LIB})"
    )
    print(
        f"B's LIB address: {lib_account2.address} ({lib_state2.balance / LIB})"
    )
    print(f"A's ETH balance: {eth_account1} ({eth_balance1})")
    print(f"B's ETH balance: {eth_account2} ({eth_balance2})\n")
Пример #3
0
def deploy_contract():
    account_address = web3login.web3_login()
    contract_interface = compile_contract()
    contract = w3.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin'])
    abs_cost = w3.eth.gasPrice * contract.constructor().estimateGas()
    log.out.debug("Absolute cost for this transaction: {} Ether".format(w3.fromWei(abs_cost, "ether")))
    deploy_txn = contract.constructor().transact(transaction={'from': w3.eth.accounts[0]})
    timer = 50
    tx_receipt = None
    log.out.info("Contract deployed, waiting for mining: max. {} seconds".format(timer))
    while (tx_receipt is None and timer > 0):
        tx_receipt = w3.eth.getTransactionReceipt(deploy_txn)
        time.sleep(1)
        timer -= 1
    if tx_receipt is None:
        log.out.warning("\033[91mCouldn't mine transaction. Check your node or increase timer (in deploy.py)\033[0m")
        web3login.web3_logout(account_address)
        exit()
    else:
        #log.out.debug("Transaction receipt: {}".format(tx_receipt))
        contract_address = tx_receipt['contractAddress']
        log.out.info("\033[92mContract with address {} deployed\033[0m".format(contract_address))
        store_contract_info(contract_address)
        web3login.web3_logout(account_address)
        return contract_address
Пример #4
0
def check_balance(private_key):
    address = b2h(ethereum.utils.privtoaddr(private_key))

    print("address: 0x%s" % address)

    checksum_address = w3.toChecksumAddress(address)
    balance = w3.fromWei(w3.eth.getBalance(checksum_address), 'ether')


    return balance
Пример #5
0
    def run_job():
        return
        we3 = GetWeb3()
        contract_instance = ConnectToContract(we3)
        owner_address = app.config['PUBLIC_ADDRESS']
        gasprice = GetMediumGasPrice(we3)
        i = 0

        while True:

            i += 1
            if i == 3600:
                i = 0
                gasprice = GetSlowGasPrice(we3)

            myBalance = GetMyBalance(contract_instance, owner_address)
            private_key = app.config['PRIVATE_KEY']
            signed_txn = we3.eth.account.signTransaction(
                txn, private_key=private_key)

            # Sending raw transaction to blockchain
            print('RawTransaction:')
            print(we3.toHex(signed_txn.rawTransaction))
            print("\t###    Gas:", gas)
            print("\t###    Gas price:", gasprice)
            tx = we3.eth.sendRawTransaction(
                we3.toHex(signed_txn.rawTransaction))
            txcost = w3.fromWei(gasprice * gas, "ether")
            print('Transaction Number:', we3.toHex(tx))

            # Updating database.
            claim.tx_number = we3.toHex(tx)
            claim.processed = True
            claim.processed_time = datetime.now()
            db.session.commit()

            print("\t###    ADDED NEW TRANSACTION")
            print("\t###    Cost:", txcost)
            print("\t###    TX Number:", tx)
            print("\t###    Address:", claim.claimed_address)
            print("\t###    Amount:", claim.amount)
            print("\t###    Nonce:", nonce)
            print("\t###    Gas:", gas)
            print("\t###    Gas price:", gasprice)

            time.sleep(1)
Пример #6
0
 def issue(self):
     while True:
         try:
             print("Fee is currently : ",
                   w3.fromWei(self.__pvaaGateway.getFee(), "ether"), "Eth")
             addressTo = input("Paste Ethereum Address of Receipient")
             self.viewMetadata()
             metadataURI = self.__pvaaGateway.getMetadataObjectList()[int(
                 input("Select Index of Metadata to use"))]["uri"]
             print(metadataURI)
             self.__pvaaGateway.issue(addressTo, metadataURI)
             break
         except Exception as e:
             #raise
             print(e)
             tryAgain = input("Something went wrong, try again (Y/N)")
             if tryAgain.lower() != 'y':
                 break
Пример #7
0
def searchTransactions(firstBlock, lastBlock, addresses, shortt, formatt, add):
    #firstBlock = 1240590
    g = Digraph('G', filename='transfer')
    if (lastBlock == 'latest'
        ):  #si viene latest, convierto lastBlock a el ultimo bloque en curso
        lastBlock = w3.eth.blockNumber
    booe = True
    direcc = addresses
    for i in range(int(firstBlock),
                   int(lastBlock)):  #Comienzo a recorrer los bloques elegidos
        tx = w3.eth.getBlock(i, booe)  #Recibo la informacion de cada bloque
        for diccionario in tx[
                'transactions']:  #Obtengo el campo de las transacciones del bloque anteriormente mencionado
            try:
                if (
                        diccionario['value'] > 0
                ):  #Verifico que se haya hecho alguna transaccion de mas de un wei
                    labe = str(w3.fromWei(
                        diccionario['value'], 'ether')) + ' ether  (' + str(
                            i) + ')'  #label que usaré en el graph
                    if not direcc:  #Si no elijo direcciones
                        # ~ if(add):
                        # ~ direcc.append(diccionario['from'])
                        # ~ direcc.append(diccionario['to'])
                        if (shortt):  #si lo necesito acortado
                            if (formatt == 'graphviz'):
                                g.node(diccionario['from'][2:10],
                                       diccionario['from'][2:10])
                                g.node(diccionario['to'][2:10],
                                       diccionario['to'][2:10])
                                g.edge(diccionario['from'][2:10],
                                       diccionario['to'][2:10],
                                       label=labe)
                            else:
                                print(diccionario['from'][2:10], " -> ",
                                      diccionario['to'][2:10], ": ",
                                      diccionario['value'], "wei   Block ->: ",
                                      i)
                        else:
                            if (formatt == 'graphviz'):
                                g.node(diccionario['from'],
                                       diccionario['from'])
                                g.node(diccionario['to'], diccionario['to'])
                                g.edge(diccionario['from'],
                                       diccionario['to'],
                                       label=labe)
                            else:
                                print(diccionario['from'], " -> ",
                                      diccionario['to'], ": ",
                                      diccionario['value'], "wei   Block ->: ",
                                      i)

                    else:
                        for adArray in direcc:  #si elijo direcciones a buscar
                            if (
                                    adArray == diccionario['from']
                                    or adArray == diccionario['to']
                            ):  #Verifico que pueda estár entre las direcciones que mandaron o recibieron transacciones
                                if (add):
                                    if (adArray != diccionario['from']):
                                        direcc.append(diccionario['from'])
                                    elif (adArray != diccionario['to']):
                                        direcc.append(diccionario['to'])
                                if (shortt):
                                    if (formatt == 'graphviz'):
                                        g.node(diccionario['from'][2:10],
                                               diccionario['from'][2:10])
                                        g.node(diccionario['to'][2:10],
                                               diccionario['to'][2:10])
                                        g.edge(diccionario['from'][2:10],
                                               diccionario['to'][2:10],
                                               label=labe)
                                    else:
                                        print(diccionario['from'][2:10],
                                              " -> ", diccionario['to'][2:10],
                                              ": ", diccionario['value'],
                                              "wei   Block ->: ", i)
                                else:
                                    if (formatt == 'graphviz'):
                                        g.node(diccionario['from'],
                                               diccionario['from'])
                                        g.node(diccionario['to'],
                                               diccionario['to'])
                                        g.edge(diccionario['from'],
                                               diccionario['to'],
                                               label=labe)
                                    else:
                                        print(diccionario['from'], " -> ",
                                              diccionario['to'], ": ",
                                              diccionario['value'],
                                              "wei   Block ->: ", i)
            except:
                raise Exception("no hay bloques que hayan hecho transacciones")
    if (formatt == 'graphviz'):
        print(g.source)
        g.view()
Пример #8
0
def userA_has_around_some_amount_of_eth_in_root_chain(context, amount):
    balance = w3.eth.getBalance(userA)
    assert_msg = 'balance: {} is not in around: {}'.format(
        w3.fromWei(balance, 'ether'), amount)
    assert w3.toWei(amount - 0.01, 'ether') <= balance <= w3.toWei(
        amount, 'ether'), assert_msg
Пример #9
0
def userB_successfully_exit_from_root_chain_after_exit(context, amount):
    balance = w3.eth.getBalance(userB)
    assert_msg = 'balance: {} is not in around: {}'.format(
        w3.fromWei(balance, 'ether'), amount)
    assert w3.toWei(amount - 0.01, 'ether') <= balance <= w3.toWei(
        amount, 'ether'), assert_msg
Пример #10
0
 def getBalance(self):
     print("\tBalance : ",
           w3.fromWei(self.__pvaaGateway.getBalance(), "ether"), " Eth")
Пример #11
0
## Smart COntract Variables

#address
sc_address = Web3.toChecksumAddress(parameters["CONTRACT_ADDRESS"])
sc_abi = parameters["ABI"]

#Web 3 Set UP
w3 = Web3(HTTPProvider(parameters["INFURA_LINK"]))
w3.middleware_stack.inject(geth_poa_middleware, layer=0)

# Make default account
private_key = parameters["PRIVATE_KEY"]
w3.eth.defaultAccount = w3.eth.account.privateKeyToAccount(private_key)
balance = w3.eth.getBalance(w3.eth.defaultAccount.address)
balance = w3.fromWei(balance, 'ether')
print(w3.eth.defaultAccount.address, balance)
# Get Initial Nonce
nonce = int(w3.eth.getTransactionCount(w3.eth.defaultAccount.address))

#Location of QR Scanner
LOCATION = "Narnia"

#Make instance of Smart Contract
asset_contract = w3.eth.contract(address=sc_address, abi=sc_abi)


def check_in(id, nonce, location):
    """Short summary.

    Args:
Пример #12
0
 def from_wei(amount, unit='ether'):
     return w3.fromWei(amount, unit)
Пример #13
0
def voter_deposit(chief, address):
    '''Get MKR deposit of a user in the governance contract.'''
    return w3.fromWei(chief.functions.deposits(address).call(), 'ether')
Пример #14
0
def val_readable(wei, unit=None):
    if unit == "nct":
        # decimals = 18, so this works out
        pass
    v = web3.fromWei(wei, "ether")
    return str(v) + ((" " + unit) if unit else "")
Пример #15
0
#!/usr/bin/env python
from web3.auto import w3
print('all accounts:', w3.personal.listAccounts)
#print('first account:', w3.personal.listAccounts[0])
#print('balance of first account in wei:', w3.eth.getBalance(w3.personal.listAccounts[0]))
print('balance of first account in ether:',
      w3.fromWei(w3.eth.getBalance(w3.personal.listAccounts[0]), 'ether'))
print('balance of second account in ether:',
      w3.fromWei(w3.eth.getBalance(w3.personal.listAccounts[1]), 'ether'))
#!/usr/bin/env python
from web3.auto import w3
first = w3.personal.listAccounts[0]
second = w3.personal.listAccounts[1]
amount = w3.toWei('0.15', 'ether')
w3.eth.sendTransaction({'to': second, 'from': first, 'value': amount})
print('balance of first account in ether:', w3.fromWei(w3.eth.getBalance(first), 'ether'))
print('balance of second account in ether:', w3.fromWei(w3.eth.getBalance(second), 'ether'))