def send_eth(wallet):
    # пополняем кошелек ефиром
    global out_nonce
    balance = w3.eth.getBalance(out_wallet)
    if balance < w3.toWei(ETH_FEE * 21000, 'gwei'):
        message = "Not enough Ether on hot wallet"
        logger.info(message)
        send_message(f'tokensend_bot seid: {message}')
        return False
    else:
        signed_txn = w3.eth.account.signTransaction(
            dict(
                nonce=out_nonce,
                gasPrice=w3.toWei(3, 'gwei'),
                gas=21000,
                to=w3.toChecksumAddress(wallet),
                value=w3.toWei(ETH_FEE * 100000, 'gwei'),
                data=b'',
            ),
            OUT_PRIVKEY,
        )
        txhash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
        logger.info(txhash.hex())
        out_nonce = out_nonce + 1
        return txhash
Esempio n. 2
0
 def player_roll_dice(self, bet_size_ether, chances, wallet_path,
                      wallet_password):
     """
     Work in progress:
     https://github.com/AndreMiras/EtherollApp/issues/1
     """
     roll_under = chances
     value_wei = w3.toWei(bet_size_ether, 'ether')
     gas = 310000
     gas_price = w3.toWei(4, 'gwei')
     # since Account.load is hanging while decrypting the password
     # we set password to None and use `w3.eth.account.decrypt` instead
     account = Account.load(wallet_path, password=None)
     from_address_normalized = checksum_encode(account.address)
     nonce = self.web3.eth.getTransactionCount(from_address_normalized)
     transaction = {
         # 'chainId': ChainID.ROPSTEN.value,
         'chainId': int(self.web3.net.version),
         'gas': gas,
         'gasPrice': gas_price,
         'nonce': nonce,
         'value': value_wei,
     }
     transaction = self.contract.functions.playerRollDice(
         roll_under).buildTransaction(transaction)
     encrypted_key = open(wallet_path).read()
     private_key = w3.eth.account.decrypt(encrypted_key, wallet_password)
     signed_tx = self.web3.eth.account.signTransaction(
         transaction, private_key)
     tx_hash = self.web3.eth.sendRawTransaction(signed_tx.rawTransaction)
     print("tx_hash:", tx_hash.hex())
     return tx_hash
Esempio n. 3
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
Esempio n. 4
0
def transfer():
    nonce = w3.eth.getTransactionCount(my_address)
    transaction = {
        'to': icoAddress,
        'value': w3.toWei(0.1, 'ether'),
        'gas': 500000,
        'gasPrice': w3.toWei(10, 'gwei'),
        'nonce': nonce
    }
    signed = w3.eth.account.signTransaction(transaction, private_key)
    w3.eth.sendRawTransaction(signed.rawTransaction)
    print("直接发送代币发送完毕")
Esempio n. 5
0
def test_withdraw_donation(Donation):
    donation = accounts[0].deploy(Donation)
    donatur_name = 'Rafa'
    donation.donate(donatur_name, {
        'from': accounts[1],
        'value': w3.toWei('1', 'ether')
    })

    initial_balance = w3.eth.getBalance(w3.eth.coinbase)
    donation.withdraw_donation()
    after_withdraw_balance = w3.eth.getBalance(w3.eth.coinbase)

    assert (abs(after_withdraw_balance - initial_balance) -
            w3.toWei('1', 'ether') < w3.toWei('1', 'gwei'))
Esempio n. 6
0
def fill_accounts():

    eth_accounts = w3.personal.listAccounts

    faucet_acc = eth_accounts[0]

    for i, acc in enumerate(eth_accounts[1:]):

        # Check balance and request funds from a faucet if below threshold
        balance = w3.eth.getBalance(acc)

        if balance < w3.toWei(0.005, 'ether'):
            logger.info("Account %s is below the threshold. Filling..." % acc)
            get_eth(faucet_acc, acc, w3.toWei(0.005, 'ether') - balance)
Esempio n. 7
0
 def __init__(self, parent):
     self.polyswarm = parent.polyswarm
     self.min_side = web3.toWei(100000000, "ether")
     self.refill_amount = web3.toWei(100000000, "ether")
     self.max_side = web3.toWei(250000000, "ether")
     # At least 5 minutes
     self.min_block_wait = 330
     self.cur_block = parent.initial_block
     self.wait_until_block = None
     # (side, home)
     self.eth_balance = (None, None)
     self.nct_balance = (None, None)
     self.changed = False
     log.info("Minimum balance: %s /  Maximum balance: %s", self.min_side,
              self.max_side)
Esempio n. 8
0
 def player_roll_dice(self,
                      bet_size_ether,
                      chances,
                      wallet_path,
                      wallet_password,
                      gas_price_gwei=DEFAULT_GAS_PRICE_GWEI):
     """
     Signs and broadcasts `playerRollDice` transaction.
     Returns transaction hash.
     """
     roll_under = chances
     # `w3.toWei` one has some issues on Android, see:
     # https://github.com/AndreMiras/EtherollApp/issues/77
     # value_wei = w3.toWei(bet_size_ether, 'ether')
     value_wei = int(bet_size_ether * 1e18)
     gas = 310000
     gas_price = w3.toWei(gas_price_gwei, 'gwei')
     wallet_encrypted = load_keyfile(wallet_path)
     address = wallet_encrypted['address']
     from_address_normalized = to_checksum_address(address)
     nonce = self.web3.eth.getTransactionCount(from_address_normalized)
     transaction = {
         'chainId': self.chain_id.value,
         'gas': gas,
         'gasPrice': gas_price,
         'nonce': nonce,
         'value': value_wei,
     }
     transaction = self.contract.functions.playerRollDice(
         roll_under).buildTransaction(transaction)
     private_key = Account.decrypt(wallet_encrypted, wallet_password)
     signed_tx = self.web3.eth.account.signTransaction(
         transaction, private_key)
     tx_hash = self.web3.eth.sendRawTransaction(signed_tx.rawTransaction)
     return tx_hash
Esempio n. 9
0
def send_ether(amount: float, destination: str):
    """Send Ether to an address"""
    return w3.eth.sendTransaction({
        "from": w3.eth.accounts[0],
        "value": w3.toWei(amount, "ether"),
        "to": w3.toChecksumAddress(destination)
    })
Esempio n. 10
0
    def deploy_contract(self):

        print("Constructing transaction")

        construct_txn = self.prepared_contract.constructor().buildTransaction({
            'from':
            self.system_account.address,
            'nonce':
            self.web3.eth.getTransactionCount(self.system_account.address),
            'gas':
            503116,
            'gasPrice':
            w3.toWei('100', 'gwei')
        })

        print("Signing transaction")

        signed = self.system_account.signTransaction(construct_txn)

        print("Sending transaction")

        print("System account ", self.system_account.address)

        transaction_id = self.web3.eth.sendRawTransaction(
            signed.rawTransaction)

        transaction_id = self.web3.eth.waitForTransactionReceipt(
            transaction_id, timeout=120)

        print("Contract ID ", str(transaction_id["contractAddress"]))

        return transaction_id["contractAddress"]
Esempio n. 11
0
    def add_spouse(self, contract_id, spouse_address):

        print("Adding ", spouse_address, "to countract ", contract_id)

        transaction = self.prepared_contract(contract_id).functions.addSpouse(
            spouse_address).buildTransaction({
                'from':
                self.system_account.address,
                'nonce':
                self.web3.eth.getTransactionCount(self.system_account.address),
                'gas':
                503116,
                'gasPrice':
                w3.toWei('100', 'gwei')
            })

        transaction = self.system_account.signTransaction(transaction)

        print("Sending transaction")

        transaction_id = self.web3.eth.sendRawTransaction(
            transaction.rawTransaction)

        transaction_id = self.web3.eth.waitForTransactionReceipt(
            transaction_id, timeout=120)

        return transaction_id["contractAddress"]
Esempio n. 12
0
def withdraw():
    path = dirname(dirname(abspath(__file__))) + '/abi/Ico.json'
    contract_abi = loads(open(path).read())
    myContract = w3.eth.contract(address=icoAddress, abi=contract_abi)
    myDeposit = myContract.functions.depositBalanceOfUser(my_address).call()
    print("我的投资金额度为:", myDeposit)
    nonce = w3.eth.getTransactionCount(my_address)
    unicorn_txn = myContract.functions.safeWithdrawal().buildTransaction({
        'nonce':
        nonce,
        'gasPrice':
        w3.toWei(10, 'gwei'),
        'gas':
        400000
    })
    try:
        signed_txn = w3.eth.account.signTransaction(unicorn_txn,
                                                    private_key=private_key)
        hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
        print("提币交易已经发送,请耐心等待并查询,hash值为:", w3.toHex(hash))
        myDeposit = myContract.functions.depositBalanceOfUser(
            my_address).call()
        print("我的投资金额度为:", myDeposit)
    except Exception:
        print("交易失败")
Esempio n. 13
0
 def deposit(self, amount, depositor, currency):
     value = w3.toWei(amount,
                      'ether') if currency == '0x' + '00' * 20 else 0
     self.root_chain.functions.deposit(currency, amount).transact({
         'from':
         w3.toChecksumAddress(depositor),
         'value':
         value
     })
Esempio n. 14
0
def test_donate_1_eth(Donation):
    import time
    donation = accounts[0].deploy(Donation)

    donatur_name = 'Novak Djokovic'
    donation.donate(donatur_name, {
        'from': accounts[1],
        'value': w3.toWei('0.5', 'ether')
    })
    donatur = donation.donaturs(0)
    donation_sum = donation.donatur_details(donatur)['sum']
    donation_name = donation.donatur_details(donatur)['name']
    donation_time = donation.donatur_details(donatur)['time']

    assert (donatur == accounts[1])
    assert (donation_sum == w3.toWei('0.5', 'ether'))
    assert (donation_name == donatur_name)
    assert (int(time.time()) - donation_time < 600)
Esempio n. 15
0
def index():
    get_info = contract_instance.get_ballance_of_depo()
    print(get_info)

    balance = token_instance.functions.balanceOf(default_account).call()
    symbol = token_instance.functions.symbol().call()
    print(balance)
    print(web3.toWei('10000','ether'))
    print(symbol)
    nonce = eth_provider.getTransactionCount(default_account)
    print(nonce)
    print('Ether to wei:',w3.toWei('1','ether'))
    print('Balance of contract:',token_instance.functions.balanceOf(contract_address).call())
    contract_address_from = web3.toChecksumAddress(contract_address)
    own_address = web3.toChecksumAddress(default_account)
    # address to '0x4776e07A2A155410F601e3e0bfBbA7242a35493a' 0x3143ae291f6f04d22affc9f66578eff22f47aef3

    txn = token_instance.functions.transfer(contract_address_from,w3.toWei('598.999','ether')).buildTransaction(
                                                              {
                                                               'chainId': 5777,
                                                               'gas': 1000000,
                                                               'gasPrice': w3.toWei('43', 'wei'),
                                                               'nonce': nonce, })
    print(txn)

    if 'private_key' in dict_values.keys():
        privat_key = dict_values['private_key']
    else:
        try:
            private_key_file = open('./private_key','r')
            privat_key = private_key.read()
        except:
            pass

    signed_txn = w3.eth.account.signTransaction(txn, private_key=privat_key)
    print(signed_txn)

    result = eth_provider.sendRawTransaction(signed_txn.rawTransaction)
    print(result)
    result_txn = w3.toHex(w3.sha3(signed_txn.rawTransaction))
    print(result_txn)


    return render_template('index.html', owner=default_account,token = token_address,smartAddress = contract_address)
Esempio n. 16
0
def addTemplate():
    nonce = w3.eth.getTransactionCount(my_address)
    unicorn_txn = WalletTemplateInfos.functions.addTemplate(WalletTemplateOne.address).buildTransaction({
        'nonce': nonce,
        'gasPrice': w3.toWei(10, 'gwei'),
    })
    signed_txn = w3.eth.account.signTransaction(
        unicorn_txn, private_key=private_key)
    hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
    print("addTemplate交易已经发送")
Esempio n. 17
0
def donate(charity_event_id: int, amount: int, donor_name='Anonymous'):
    donate_tx_hash = charity_contract.functions.donate(
        charity_event_id, donor_name).transact({
            "value":
            w3.toWei(amount, 'ether'),
            "from":
            eth_address
        })
    receipt = w3.eth.waitForTransactionReceipt(donate_tx_hash)
    return receipt
Esempio n. 18
0
def test_wrong_account_withdraw_donation(Donation):
    donation = accounts[0].deploy(Donation)
    donatur_name = 'Novak Djokovic'
    donation.donate(donatur_name, {
        'from': accounts[1],
        'value': w3.toWei('1', 'ether')
    })

    with pytest.reverts('dev: wrong guy, budy'):
        donation.withdraw_donation({'from': accounts[1]})
Esempio n. 19
0
def addMethod():
    args = (DAPP_ID,Test.address,False,0,"registerName|User register his name|string|none",b'')
    nonce = w3.eth.getTransactionCount(my_address)
    unicorn_txn = DappMethodAdmin.functions.addMethod(*args).buildTransaction({
        'nonce': nonce,
        'gasPrice': w3.toWei(10, 'gwei'),
    })
    signed_txn = w3.eth.account.signTransaction(
        unicorn_txn, private_key=private_key)
    hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
    print("增加方法交易已经发送")
Esempio n. 20
0
 def deposit(self, amount, currency):
     value = w3.toWei(amount,
                      'ether') if currency == '0x' + '00' * 20 else 0
     tx = self.root_chain.functions.deposit(currency,
                                            amount).buildTransaction({
                                                'from':
                                                self.address,
                                                'value':
                                                value
                                            })
     self._sign_and_send_tx(tx)
Esempio n. 21
0
def setWalletAdminAddress():
    nonce = w3.eth.getTransactionCount(my_address)
    unicorn_txn = WalletHub.functions.setWalletAdminAddress(
        WalletAdmin.address).buildTransaction({
            'nonce': nonce,
            'gasPrice': w3.toWei(10, 'gwei'),
        })
    signed_txn = w3.eth.account.signTransaction(unicorn_txn,
                                                private_key=private_key)
    hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
    print("setWalletAdminAddress交易已经发送")
Esempio n. 22
0
def setRegisterFee():
    nonce = w3.eth.getTransactionCount(my_address)
    unicorn_txn = DappHub.functions.setRegisterFee(ONE_ETHER).buildTransaction(
        {
            'nonce': nonce,
            'gasPrice': w3.toWei(10, 'gwei'),
        })
    signed_txn = w3.eth.account.signTransaction(unicorn_txn,
                                                private_key=private_key)
    hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
    print("setRegisterFee交易已经发送")
Esempio n. 23
0
def deposit():
    path = dirname(dirname(abspath(__file__))) + '/abi/Ico.json'
    contract_abi = loads(open(path).read())
    contract_address = icoAddress
    myContract = w3.eth.contract(address=contract_address, abi=contract_abi)
    nonce = w3.eth.getTransactionCount(my_address)
    unicorn_txn = myContract.functions.deposit().buildTransaction({
        'nonce':
        nonce,
        'value':
        w3.toWei(1000, 'ether'),
        'gasPrice':
        w3.toWei(10, 'gwei'),
        'gas':
        500000
    })
    signed_txn = w3.eth.account.signTransaction(unicorn_txn,
                                                private_key=private_key)
    hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
    print("投资交易已经发送,请耐心等待并查询,hash值为:", w3.toHex(hash))
Esempio n. 24
0
def setBeneficiary():
    nonce = w3.eth.getTransactionCount(my_address)
    unicorn_txn = DappHub.functions.setBeneficiary(
        ANOTHER_ADDRESS).buildTransaction({
            'nonce': nonce,
            'gasPrice': w3.toWei(10, 'gwei'),
        })
    signed_txn = w3.eth.account.signTransaction(unicorn_txn,
                                                private_key=private_key)
    hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
    print("setBeneficiary交易已经发送")
Esempio n. 25
0
def createAuction(name, desc, owner, amt):
    global BlindAuction, contract_interface
    try:
        minBid = w3.toWei(amt, 'ether')
        tx_hash = BlindAuction.constructor(name, desc, owner, minBid).transact(
            {'from': developer})
        tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)
        blindAuction = w3.eth.contract(address=tx_receipt.contractAddress,
                                       abi=contract_interface['abi'])
        return blindAuction
    except:
        return False
Esempio n. 26
0
def transfer():
    nonce = w3.eth.getTransactionCount(my_address)
    unicorn_txn = NFT_CONTRACT.functions.safeTransferFrom(my_address,receiver_address,1).buildTransaction({
        'nonce': nonce,
        # 'value': w3.toWei(1000, 'ether'),
        'gasPrice': w3.toWei(10, 'gwei'),
        # 'gas': 500000
    })
    signed_txn = w3.eth.account.signTransaction(
        unicorn_txn, private_key=private_key)
    hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
    print("安全交易已经发送,请耐心等待并查询,hash值为:", w3.toHex(hash))
Esempio n. 27
0
def pre_fund(pre_funded_accounts):
    alloc = {}

    for account in pre_funded_accounts:
        if w3.isAddress(account['address']) and int(account['balance']) > 0:
            address = account['address'][2:]

            balance_wei = w3.toWei(account['balance'], 'ether')
            alloc[address] = {
                "balance": w3.toHex(balance_wei)
            }

    return alloc
Esempio n. 28
0
def pet():
    nonce = web3.eth.get_transaction_count(ether_address)
    pet_tx = contract.functions.interact(summoned_gotchis).buildTransaction({
        "chainId":137,
        "gasPrice": w3.toWei("1", "gwei"),
        "nonce": nonce
    })

    signed_txn = web3.eth.account.sign_transaction(pet_tx, private_key=private_key)
    tx_hash = web3.eth.send_raw_transaction(signed_txn.rawTransaction).hex()

    print("interact() called. Transaction ID:")
    print(f"https://polygonscan.com/tx/{tx_hash}")
Esempio n. 29
0
 def sendEth(self):
     while True:
         try:
             addressTo = input("Paste Ethereum Address of Receipient")
             wei = w3.toWei(input("Enter amount in Eth to send"), 'ether')
             self.__pvaaGateway.sendEth(wei, addressTo)
             break
         except Exception as e:
             #raise
             print(e)
             tryAgain = input("Something went wrong, try again (Y/N)")
             if tryAgain.lower() != 'y':
                 break
Esempio n. 30
0
def buy():
    path = dirname(dirname(abspath(__file__))) + '/abi/Exchange.json'
    contract_abi = loads(open(path).read())
    myContract = w3.eth.contract(address=exchange_address, abi=contract_abi)
    nonce = w3.eth.getTransactionCount(my_address)
    deadline = math.floor(time.time()) + 10 * 60
    if isTransfer:
        unicorn_txn = myContract.functions.ethToTokenTransferOutput( 100 * 10**18, deadline,transfer_address).buildTransaction({
            'nonce': nonce,
            'value': w3.toWei(1, 'ether'),
            'gas': 400000
        })
    else:
        unicorn_txn = myContract.functions.ethToTokenSwapOutput( 100 * 10**18, deadline).buildTransaction({
            'nonce': nonce,
            'value': w3.toWei(1, 'ether'),
            'gas': 400000
        })
    signed_txn = w3.eth.account.signTransaction(
        unicorn_txn, private_key=private_key)
    hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
    print("稳定币购买代币交易已经发送,请耐心等待并查询,hash值为:", w3.toHex(hash))