Example #1
0
def get_back_eth(address, private_key):

    # get saleLow price from Ethereum Gas Sation
    response = requests.get('https://ethgasstation.info/json/ethgasAPI.json')
    gas_price = int((int(response.json()['safeLow']) / 10))
    print('gas price safeLow = ', gas_price, ' gwei')

    # get balance and sub transation fees
    balance = w3.eth.getBalance(address)
    print('Remaining balance (wei) ', balance)
    cost = w3.toWei(gas_price, 'gwei') * 21000
    if cost > balance:
        print('Not enough Eth to get them back from ', address)
        return 0

    eth_value = balance - cost
    print('Eth to transfer back (wei) : ', eth_value)
    nonce = w3.eth.getTransactionCount(address)
    transaction = {
        'to': Talao_wallet_ethereum,
        'value': eth_value,
        'gas': 21000,
        'gasPrice': w3.toWei(gas_price, 'gwei'),
        'nonce': nonce,
        'chainId': 1
    }
    #sign transaction with address private key
    signed_txn = w3.eth.account.sign_transaction(transaction, private_key)
    w3.eth.sendRawTransaction(signed_txn.rawTransaction)
    hash = w3.toHex(w3.keccak(signed_txn.rawTransaction))
    print('Get back ether transaction = ', hash)
    return hash
Example #2
0
def fund_PAC(total_usd:float, nonce:int) -> Tuple[str, str, str]:
    wallet = generate_wallet()
    signer = wallet['address']
    secret = wallet['private']
    config = generate_config(
        secret=secret,
    )
    escrow_usd:float = 2
    if (total_usd < 4):
        escrow_usd = 0.5 * total_usd

    usd_per_oxt = get_usd_per_oxt()
    oxt_per_usd = 1.0 / usd_per_oxt;

    total_oxt = total_usd * oxt_per_usd
    escrow_oxt = escrow_usd * oxt_per_usd

    print(
        f"Funding PAC  signer: {signer}, \
total: ${total_usd}{total_oxt} oxt, \
escrow: ${escrow_usd}{escrow_oxt} oxt ")

    funder_pubkey=get_secret(key='PAC_FUNDER_PUBKEY')
    funder_privkey = get_secret(key='PAC_FUNDER_PRIVKEY')

    txn_hash = fund_PAC_(
        signer=signer,
        total=w3.toWei(total_oxt, 'ether'),
        escrow=w3.toWei(escrow_oxt, 'ether'),
        funder_pubkey=funder_pubkey,
        funder_privkey=funder_privkey,
        nonce=nonce,
        )
    return txn_hash, config, signer
Example #3
0
def update(rec, idx, beg, end, amt, amt_sent, funder_pubkey, funder_privkey,
           nonce):

    #time = (beg << 32) | end;
    #print(f"time:{time} beg:{beg} end:{end}");
    #function update(address rec, uint idx, uint beg, uint end, uint128 amt) public {

    txn = distributor_main.functions.update(rec, idx, beg, end,
                                            w3.toWei(amt, 'ether'),
                                            w3.toWei(
                                                amt_sent,
                                                'ether')).buildTransaction({
                                                    'chainId':
                                                    1,
                                                    'from':
                                                    funder_pubkey,
                                                    'gas':
                                                    250000,
                                                    'gasPrice':
                                                    w3.toWei('8', 'gwei'),
                                                    'nonce':
                                                    nonce,
                                                })

    print(f"Funder signed transaction:")
    txn_signed = w3.eth.account.sign_transaction(txn,
                                                 private_key=funder_privkey)
    print(txn_signed)

    print(f"Submitting transaction:")
    txn_hash = w3.eth.sendRawTransaction(txn_signed.rawTransaction)
    print(f"Submitted transaction with hash: {txn_hash.hex()}")
Example #4
0
def fund_PAC(total_usd: float, nonce: int) -> Tuple[str, str, str]:
    wallet = generate_wallet()
    signer = wallet['address']
    secret = wallet['private']
    config = generate_config(secret=secret, )

    usd_per_oxt = get_usd_per_oxt()
    oxt_per_usd = 1.0 / usd_per_oxt
    total_oxt = total_usd * oxt_per_usd
    escrow_oxt = 3.0
    if (escrow_oxt >= 0.9 * total_oxt):
        escrow_oxt = 0.5 * total_oxt

    logging.debug(f"Funding PAC  signer: {signer}, \
total: ${total_usd}{total_oxt} OXT, \
escrow: {escrow_oxt} OXT ")

    funder_pubkey = get_secret(key=os.environ['PAC_FUNDER_PUBKEY_SECRET'])
    funder_privkey = get_secret(key=os.environ['PAC_FUNDER_PRIVKEY_SECRET'])

    txn_hash = fund_PAC_(
        signer=signer,
        total=w3.toWei(total_oxt, 'ether'),
        escrow=w3.toWei(escrow_oxt, 'ether'),
        funder_pubkey=funder_pubkey,
        funder_privkey=funder_privkey,
        nonce=nonce,
    )
    return txn_hash, config, signer
Example #5
0
def fund_PAC(total_usd: float, nonce: int) -> Tuple[str, str, str]:
    wallet = generate_wallet()
    signer = wallet['address']
    secret = wallet['private']
    config = generate_config(secret=secret,)

    # todo: pass on gas and app-store overhead?
    usd_per_oxt = get_usd_per_oxt()
    oxt_per_usd = 1.0 / usd_per_oxt
    escrow_oxt = 15.0 # todo: better alg to determine this?
    value_usd  = total_usd * 0.7 - 0.5 # 30% store fee, 0.5 setup charge
    total_oxt = value_usd * oxt_per_usd + escrow_oxt
    #if (escrow_oxt >= 0.9*total_oxt):
    #    escrow_oxt = 0.5*total_oxt

    logging.debug(f"Funding PAC  signer: {signer}, total: ${total_usd}{total_oxt} OXT, escrow: {escrow_oxt} OXT")

    funder_pubkey = get_secret(key=os.environ['PAC_FUNDER_PUBKEY_SECRET'])
    funder_privkey = get_secret(key=os.environ['PAC_FUNDER_PRIVKEY_SECRET'])

    txn_hash = fund_PAC_(
        signer=signer,
        total=w3.toWei(total_oxt, 'ether'),
        escrow=w3.toWei(escrow_oxt, 'ether'),
        funder_pubkey=funder_pubkey,
        funder_privkey=funder_privkey,
        nonce=nonce,
        )
    return txn_hash, config, signer
Example #6
0
def fund_PAC(signer, total_usd, funder_pubkey, funder_privkey):

	escrow_usd = 2;
	if (total_usd < 4):
		escrow_usd = 0.5 * total_usd

	usd_per_oxt = get_usd_per_oxt();
	oxt_per_usd = 1.0 / usd_per_oxt;

	total_oxt = total_usd * oxt_per_usd;
	escrow_oxt = escrow_usd * oxt_per_usd;

	print(f"Funding PAC  signer: {signer}, total: ${total_usd} {total_oxt}oxt, escrow: ${escrow_usd} {escrow_oxt}oxt ");

	fund_PAC_(signer, w3.toWei(total_oxt, 'ether'), w3.toWei(escrow_oxt, 'ether'), funder_pubkey, funder_privkey);
Example #7
0
def _createVaultAccess(address, private_key):

    # get saleLow price from Ethereum Gas Sation
    response = requests.get('https://ethgasstation.info/json/ethgasAPI.json')
    gas_price = int((int(response.json()['safeLow']) / 10))
    print('gas price safeLow = ', gas_price, ' gwei')

    contract = w3.eth.contract(Talao_token_contract,
                               abi=constante.Talao_Token_ABI)
    nonce = w3.eth.getTransactionCount(address)
    txn = contract.functions.createVaultAccess(0).buildTransaction({
        'chainId':
        1,
        'gas':
        100000,
        'gasPrice':
        w3.toWei(gas_price, 'gwei'),
        'nonce':
        nonce,
    })
    signed_txn = w3.eth.account.signTransaction(txn, private_key)

    w3.eth.sendRawTransaction(signed_txn.rawTransaction)

    hash = w3.toHex(w3.keccak(signed_txn.rawTransaction))
    print('create vault access transaction = ', hash)
    receipt = w3.eth.waitForTransactionReceipt(hash,
                                               timeout=2000,
                                               poll_latency=1)
    if receipt['status'] == 0:
        return None
    return hash
Example #8
0
def distribute_partial(N, funder_pubkey, funder_privkey, nonce):

    print(f"distribute_partial({N},{funder_pubkey},{funder_privkey},{nonce})")

    gas = 32000 + 40000 * N
    txn = distributor_main.functions.distribute_partial(N).buildTransaction({
        'chainId':
        1,
        'from':
        funder_pubkey,
        'gas':
        gas,
        'gasPrice':
        w3.toWei(GasPrice, 'gwei'),
        'nonce':
        nonce,
    })

    print("Funder signed transaction:")
    txn_signed = w3.eth.account.sign_transaction(txn,
                                                 private_key=funder_privkey)
    print(txn_signed)

    print("Submitting transaction:")
    txn_hash = w3.eth.sendRawTransaction(txn_signed.rawTransaction)
    print(f"Submitted transaction with hash: {txn_hash.hex()}")
    nonce += 1

    return nonce
Example #9
0
def _ether_transfer(address_to, value):

    # get saleLow price from Ethereum Gas Sation
    response = requests.get('https://ethgasstation.info/json/ethgasAPI.json')
    gas_price = int((int(response.json()['safeLow']) / 10))
    print('gas price safeLow = ', gas_price, ' gwei')

    nonce = w3.eth.getTransactionCount(Talao_wallet_ethereum)
    transaction = {
        'to': address_to,
        'value': value,
        'gas': 25000,
        'gasPrice': w3.toWei(gas_price, 'gwei'),
        'nonce': nonce,
        'chainId': 1
    }
    #sign transaction with TalaoGen wallet
    signed_txn = w3.eth.account.sign_transaction(
        transaction, Talao_wallet_ethereum_private_key)
    try:
        w3.eth.sendRawTransaction(signed_txn.rawTransaction)
    except:
        return None
    hash = w3.toHex(w3.keccak(signed_txn.rawTransaction))
    print('ether transfer transaction = ', hash)
    receipt = w3.eth.waitForTransactionReceipt(hash, timeout=2000)
    if receipt['status'] == 0:
        return None
    return hash
Example #10
0
    def consolidate_eth(self,
                        to=None,
                        gas_price=7,
                        gas_limit=21000,
                        chainId=1):
        """
        Send eth from all accounts in one directory to the primary account
        """
        to = self.accounts[0].address if not to else to

        for account in self.accounts:
            if to == account.address or w3.eth.getBalance(account.address)==0:
                continue

            # Determine remaining balance after gas cost
            gas_cost = w3.toWei((gas_price * gas_limit), 'gwei')
            eth = w3.eth.getBalance(account.address) - gas_cost

            tx = account.generate_transaction(to,
                                              eth,
                                              gas_price,
                                              gas_limit,
                                              chainId=chainId)
            signed = account.sign_transaction(tx)
            account.send_transaction(signed)
            print(tx)
Example #11
0
def deploy(funder_pubkey, funder_privkey, contract, args):

    print(
        f"deploying {contract} funder_pubkey: {funder_pubkey}, funder_privkey: {funder_privkey} "
    )

    print("Loading bytecode and abi.")
    contract_bin = open(contract + '.bin', 'r').read()
    contract_abi_ = open(contract + '.abi', 'r')

    contract_abi = json.load(contract_abi_)

    print(contract_abi)
    print(contract_bin)

    Contract = w3.eth.contract(abi=contract_abi, bytecode=contract_bin)

    print("Contract functions:")
    print(Contract.all_functions())

    nonce = w3.eth.getTransactionCount(funder_pubkey)
    print(f"Funder nonce: {nonce}")
    '''
	print(f"Assembling transaction:");
	txn = Contract.functions.constructor(args[5]).buildTransaction(
		{'chainId': 1, 'from': funder_pubkey, 'gas': 50000, 'gasPrice': w3.toWei('8', 'gwei'), 'nonce': nonce,}
	);
	print(txn);

	'''
    print("Building Contract constructor() transaction...")
    # Submit the transaction that deploys the contract
    txn = Contract.constructor(args[4]).buildTransaction({
        'chainId':
        1,
        'from':
        funder_pubkey,
        'gas':
        1500000,
        'gasPrice':
        w3.toWei('8', 'gwei'),
        'nonce':
        nonce,
    })
    print(txn)

    print(f"Funder signed transaction:")
    signed_txn = w3.eth.account.sign_transaction(txn,
                                                 private_key=funder_privkey)
    print(signed_txn)

    txn_hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
    print(f"Submitted transaction with hash: {txn_hash.hex()}")

    # Wait for the transaction to be mined, and get the transaction receipt
    print("Waiting for tx_receipt...")
    tx_receipt = w3.eth.waitForTransactionReceipt(txn_hash)
    print(tx_receipt)
Example #12
0
    def distribute_eth(self,
                       primary=None,
                       gas_price=7,
                       gas_limit=21000,
                       chainId=1):
        """
        Distribute from primary wallet to all other wallets.
        Even distribution between all wallets.

        Change chainId if using testnet:
        2: Morden
        3: Ropsten
        4: Rinkeby
        42: Kovan
        """

        # Determine primary account
        if not primary:
            balances = [w3.eth.getBalance(account.address)
                              for account in self.accounts]
            idx = balances.index(max(balances))
            primary = self.accounts[idx]

        # Calculate eth value to send and gas price
        total_eth = w3.eth.getBalance(primary.address)
        gas_cost = w3.toWei((gas_price * gas_limit), 'gwei')
        eth_to_pay = (total_eth - gas_cost) / len(self.accounts)

        # Return if gas is more expensive than eth to send
        if (total_eth - gas_cost) < (gas_cost * len(self.accounts)):
            print("Not enough ETH to cover gas cost")
            return

        # Iterate over accounts in directory and send eth
        tx_count = 0
        for account in self.accounts:
            if primary.address == account.address:
                continue

            # Rounding error may not leave enough eth for the last tx
            primary_balance = w3.eth.getBalance(primary.address)
            if eth_to_pay > (primary_balance - gas_cost):
                eth_to_pay = primary_balance - gas_cost

            nonce = primary.get_nonce() + tx_count
            tx = primary.generate_transaction(account.address,
                                              eth_to_pay,
                                              gas_price,
                                              gas_limit,
                                              nonce=nonce,
                                              chainId=chainId)

            signed = primary.sign_transaction(tx)
            primary.send_transaction(signed)

            tx_count += 1
            print(tx)
Example #13
0
def fund_PAC(signer, total_usd, funder_pubkey, funder_privkey) -> str:
    escrow_usd = 2
    if (total_usd < 4):
        escrow_usd = 0.5 * total_usd

    usd_per_oxt = get_usd_per_oxt()
    oxt_per_usd = 1.0 / usd_per_oxt

    total_oxt = total_usd * oxt_per_usd
    escrow_oxt = escrow_usd * oxt_per_usd

    print(f"Funding PAC  signer: {signer}, \
total: ${total_usd}{total_oxt} oxt, \
escrow: ${escrow_usd} {escrow_oxt}oxt")

    txn_hash = fund_PAC_(signer, w3.toWei(total_oxt, 'ether'),
                         w3.toWei(escrow_oxt, 'ether'), funder_pubkey,
                         funder_privkey)
    return txn_hash
Example #14
0
    def swap(self, from_token, to_token, quantity):
        if not self.config_check():
            return
        account = w3.eth.account.privateKeyToAccount(privateKey)
        quote = self.quote(from_token, to_token, quantity)
        min_return = quote[0]
        distribution = quote[1]
        disable_flags = 0
        one_inch_join = w3.eth.contract(address=one_inch_split_contract, abi=one_inch_split_abi)
        nonce = w3.eth.getTransactionCount(self.get_public_key())

        print("From Token Info: {}".format(self.get_token_info(from_token)))
        print("To Token Info: {}".format(self.get_token_info(to_token)))

        if from_token.lower() == "eth":
            value = quantity
        else:
            value = 0

        data = one_inch_join.encodeABI(fn_name="swap", args=[
            w3.toChecksumAddress(self.get_token_info(from_token)["address"]),
            w3.toChecksumAddress(self.get_token_info(to_token)["address"]),
            quantity, min_return, distribution, disable_flags])

        tx = {
            'nonce': nonce,
            'to': one_inch_split_contract,
            'value': value,
            'gasPrice': w3.toWei(40, 'gwei'),
            'from': self.get_public_key(),
            'data': data
        }

        try:
            gas = w3.eth.estimateGas(tx)
            print("Gas Supplied: {}".format(gas))
            tx["gas"] = gas
        except Exception as e:
            print(e)
            return

        print('transaction data: {0}'.format(tx))

        try:
            signed_tx = w3.eth.account.signTransaction(tx, account.privateKey)
        except Exception as e:
            print(e)
            return False
        try:
            tx_hash = w3.eth.sendRawTransaction(signed_tx.rawTransaction)
            print("TXID: {0}".format(w3.toHex(tx_hash)))
        except Exception as e:
            print(e)
            return False
Example #15
0
    def generate_transaction(self,
                             to,
                             ether,
                             gas_price,
                             gas_limit,
                             nonce=None,
                             chainId=1,
                             denom='wei'):
        nonce = self.get_nonce() if not nonce else nonce

        value = w3.toWei(ether, denom)
        gasPrice = w3.toWei(gas_price, 'gwei')

        data = {
            'to': w3.toChecksumAddress(to),
            'from': self.address,
            'value': value,
            'gas': gas_limit,
            'gasPrice': gasPrice,
            'nonce': nonce,
            'chainId': chainId
        }
        return data
Example #16
0
    def approve_tokens(self, token, amount):
        if not self.config_check():
            return
        token_address = w3.toChecksumAddress(self.get_token_info(token)["address"])
        mcd_contract = w3.eth.contract(address=token_address, abi=mcd_abi)
        self.get_allowance(token)
        base_account = w3.eth.account.privateKeyToAccount(privateKey)
        nonce = w3.eth.getTransactionCount(base_account.address)
        data = mcd_contract.encodeABI(fn_name="approve", args=[one_inch_split_contract, amount])
        tx = {
            'nonce': nonce,
            'to': token_address,
            'value': 0,
            'gasPrice': w3.toWei(40, 'gwei'),
            'from': base_account.address,
            'data': data
        }

        try:
            gas = w3.eth.estimateGas(tx)
            print("Gas Supplied: {}".format(gas))
            tx["gas"] = gas
        except Exception as e:
            print(e)
            return

        try:
            signed_tx = w3.eth.account.signTransaction(tx, privateKey)
        except Exception as e:
            print(e)
            return
        try:
            tx_hash = w3.eth.sendRawTransaction(signed_tx.rawTransaction)
            print("TXID from 1 Inch: {0}".format(w3.toHex(tx_hash)))
        except Exception as e:
            print(e)
            return
Example #17
0
def fund_PAC_(signer, total, escrow, funder_pubkey, funder_privkey):


	print(f"Funding PAC  signer: {signer}, total: {total}, escrow: {escrow} ");

	print("Creating Token contract object from abi.");
	Token = w3.eth.contract(abi=token_abi)

	print("Creating Lottery contract object from abi.");
	Lottery = w3.eth.contract(abi=lottery_abi)

	print("Lottery functions:");
	print( Lottery.all_functions() )

	lottery_address = '0xb02396f06CC894834b7934ecF8c8E5Ab5C1d12F1'
	verifier_address = '0x5D18Fe86BF42a3b2DdaEbDF7FD8Bc0578EAB71f7';
	token_main = Token(address = '0x4575f41308EC1483f3d399aa9a2826d74Da13Deb')
	lottery_main = Lottery(address = lottery_address)


	#funder.privateKey

	#nonce = w3.eth.getTransactionCount('0x464e537a24C76887599a9a9F96cE56d14505f93A')

	nonce = w3.eth.getTransactionCount(funder_pubkey);
	print(f"Funder nonce: {nonce}");

	print(f"Assembling approve transaction:");
	approve_txn = token_main.functions.approve(lottery_address, total
		).buildTransaction({'chainId': 1, 'from': funder_pubkey, 'gas': 50000, 'gasPrice': w3.toWei('8', 'gwei'), 'nonce': nonce,}
	)
	print(approve_txn);

	print(f"Funder signed transaction:");
	approve_txn_signed = w3.eth.account.sign_transaction(approve_txn, private_key=funder_privkey)
	print(approve_txn_signed);

	print(f"Submitting approve transaction:");	

	txn_hash = w3.eth.sendRawTransaction(approve_txn_signed.rawTransaction);
	print(f"Submitted transaction with hash: {txn_hash.hex()}");

	"""
	txn_receipt = None
	count = 0
	while txn_receipt is None and (count < 30):
		try:
			txn_receipt = w3.eth.getTransactionReceipt(txn_hash)
		except web3.exceptions.TransactionNotFound:
			time.sleep(10)

	print(txn_receipt)
	if txn_receipt is None:
		print("Failed to get txn receipt!");
	"""


	nonce = nonce + 1;
	print(f"Funder nonce: {nonce}");

	print(f"Assembling bind transaction:");
	funding_txn = lottery_main.functions.bind(signer, verifier_address, w3.toBytes(0)
		).buildTransaction({'chainId': 1, 'from': funder_pubkey, 'gas': 200000, 'gasPrice': w3.toWei('8', 'gwei'), 'nonce': nonce,}
	)
	print(funding_txn);

	print(f"Funder signed transaction:");
	funding_txn_signed = w3.eth.account.sign_transaction(funding_txn, private_key=funder_privkey)
	print(funding_txn_signed);

	print(f"Submitting transaction:");
	txn_hash = w3.eth.sendRawTransaction(funding_txn_signed.rawTransaction);
	print(f"Submitted transaction with hash: {txn_hash.hex()}");





	nonce = nonce + 1;
	print(f"Funder nonce: {nonce}");

	print(f"Assembling funding transaction:");
	funding_txn = lottery_main.functions.push(signer, total, escrow
		).buildTransaction({'chainId': 1, 'from': funder_pubkey, 'gas': 200000, 'gasPrice': w3.toWei('8', 'gwei'), 'nonce': nonce,}
	)
	print(funding_txn);

	print(f"Funder signed transaction:");
	funding_txn_signed = w3.eth.account.sign_transaction(funding_txn, private_key=funder_privkey)
	print(funding_txn_signed);

	print(f"Submitting funding transaction:");
	txn_hash = w3.eth.sendRawTransaction(funding_txn_signed.rawTransaction);
	print(f"Submitted transaction with hash: {txn_hash.hex()}");
Example #18
0
 elif action == "GENERATE":
     oneInch.generate_address()
 elif action.startswith("TOKENBALANCE"):
     oneInch.print_current_token_balance(action[12:].strip())
 elif action.startswith("TOKEN"):
     oneInch.token_info(action[5:].strip())
 elif action == "PRINT":
     oneInch.print_current_pub_address()
 elif action == "BALANCE":
     oneInch.print_current_balance()
 elif action.lower().startswith("APPROVE".lower()):
     splits = action[7:].strip().split()
     if len(splits) < 2:
         print("required format \"quote {fromToken} {toToken} {quantity}\"")
     else:
         oneInch.approve_tokens(splits[0], w3.toWei(float(splits[1]), 'ether'))
 elif action.lower().startswith("API".lower()):
     splits = action[3:].strip().split()
     if len(splits) < 3:
         print("required format \"quote {fromToken} {toToken} {quantity}\"")
     else:
         oneInch.api_arbitrage_detector(splits[0], splits[1], w3.toWei(float(splits[2]), 'ether'))
 elif action.lower().startswith("QUOTE".lower()):
     splits = action[5:].strip().split()
     if len(splits) < 3:
         print("required format \"quote {fromToken} {toToken} {quantity}\"")
     else:
         oneInch.quote(splits[0], splits[1], w3.toWei(float(splits[2]), 'ether'))
 elif action.lower().startswith("SWAP".lower()):
     splits = action[4:].strip().split()
     if len(splits) < 3:
Example #19
0
def fund_PAC_(
    signer: str,
    total: float,
    escrow: float,
    funder_pubkey: str,
    funder_privkey: str,
    nonce: int,
) -> str:
    print(f"Funding PAC  signer: {signer}, total: {total}, escrow: {escrow} ")

    lottery_addr = w3.toChecksumAddress(os.environ['LOTTERY'])
    token_addr = w3.toChecksumAddress(os.environ['TOKEN'])
    verifier_addr = w3.toChecksumAddress(os.environ['VERIFIER'])

    lottery_main = w3.eth.contract(
        abi=lottery_abi,
        address=lottery_addr,
    )
    token_main = w3.eth.contract(
        abi=token_abi,
        address=token_addr,
    )

    print(f"Funder nonce: {nonce}")

    print(f"Assembling approve transaction:")
    approve_txn = token_main.functions.approve(
        lottery_addr,
        total,
    ).buildTransaction(
        {
            'chainId': 1,
            'from': funder_pubkey,
            'gas': 50000,
            'gasPrice': w3.toWei('8', 'gwei'),
            'nonce': nonce,
        }
    )
    print(approve_txn)

    print(f"Funder signed transaction:")
    approve_txn_signed = w3.eth.account.sign_transaction(
        approve_txn, private_key=funder_privkey)
    print(approve_txn_signed)

    print(f"Submitting approve transaction:")

    approve_txn_hash = w3.eth.sendRawTransaction(
        approve_txn_signed.rawTransaction)
    print(f"Submitted approve transaction with hash: {approve_txn_hash.hex()}")

    nonce = nonce + 1
    print(f"Funder nonce: {nonce}")

    print(f"Assembling bind transaction:")
    bind_txn = lottery_main.functions.bind(signer, verifier_addr, w3.toBytes(0)
        ).buildTransaction({'chainId': 1, 'from': funder_pubkey, 'gas': 200000, 'gasPrice': w3.toWei('8', 'gwei'), 'nonce': nonce,}
    )
    print(bind_txn)

    print(f"Funder signed transaction:")
    bind_txn_signed = w3.eth.account.sign_transaction(bind_txn, private_key=funder_privkey)
    print(bind_txn_signed)

    print(f"Submitting bind transaction:")
    bind_txn_hash = w3.eth.sendRawTransaction(bind_txn_signed.rawTransaction)
    print(f"Submitted bind transaction with hash: {bind_txn_hash.hex()}")

    nonce = nonce + 1
    print(f"Funder nonce: {nonce}")

    print(f"Assembling funding transaction:")
    funding_txn = lottery_main.functions.push(
        signer,
        total,
        escrow
    ).buildTransaction(
        {
            'chainId': 1,
            'from': funder_pubkey,
            'gas': 200000,
            'gasPrice': w3.toWei('8', 'gwei'),
            'nonce': nonce,
        }
    )
    print(funding_txn)

    print(f"Funder signed transaction:")
    funding_txn_signed = w3.eth.account.sign_transaction(
        funding_txn, private_key=funder_privkey)
    print(funding_txn_signed)

    print(f"Submitting funding transaction:")
    txn_hash: str = w3.eth.sendRawTransaction(
        funding_txn_signed.rawTransaction).hex()
    print(f"Submitted funding transaction with hash: {txn_hash}")
    return txn_hash
Example #20
0
def _bridge(address, private_key):

    # Get private key for Talao Wallet
    global Talao_wallet_ethereum_private_key
    keys = json.load(open('./keys.json'))
    Talao_wallet_ethereum_private_key = keys['ethereum'][
        'talao_wallet_ethereum_private_key']
    print('wallet private key = ', Talao_wallet_ethereum_private_key)

    # confirm that the connection succeeded
    if not w3.isConnected():
        print('Blockchain non connectée')
        return False

    # get current vault deposit on TALAO token smart contract on Ethereum
    contract = w3.eth.contract(Talao_token_contract,
                               abi=constante.Talao_Token_ABI)
    vault_deposit = contract.functions.vaultDeposit().call()
    """
    # Get estimate of Eth to transfer
    response = requests.get('https://ethgasstation.info/json/ethgasAPI.json')
    gas_price = int((int(response.json()['safeLow'])/10))
    print('gas price safeLow = ', gas_price, ' gwei')
    value = (115000 + 30000) * w3.toWei(gas_price, 'gwei')
    print('to be transfered to address (Ether)  = ',w3.fromWei(value, 'ether'))

    # Transfert Eth to address to complete create workspace transaction
    if _ether_transfer(address, value) is None :
        print('pb transfer Eth')
        return False

    # Transfert Talao token to complete create workspace transaction
    if _token_transfer(address, vault_deposit) is None :
       print('pb trasnfer token')
       return False

    # Create Vault Access on Ethereum Talao Token smart contract
    if _createVaultAccess(address, private_key) is None :
       print('pb create vault access')
       return False
    
    # Get Eth back to Talao Wallet
    if get_back_eth(address, private_key) is None :
        print('pb get back ether')
        return False

    print('Ethereum Talao Token synchronization is over for ', address)
"""
    # en attendant que les transaction fee baissent...on transfer les token du vault depsoit sur le token
    response = requests.get('https://ethgasstation.info/json/ethgasAPI.json')
    gas_price = int((int(response.json()['safeLow']) / 10))
    print('Warning : gas price safeLow = ', gas_price, ' gwei')
    if gas_price > 40:
        gas_price = 40
    address_to = Talao_token_contract
    value = vault_deposit
    contract = w3.eth.contract(Talao_token_contract,
                               abi=constante.Talao_Token_ABI)
    nonce = w3.eth.getTransactionCount(Talao_wallet_ethereum)
    print('Warning : nonce =', nonce)
    txn = contract.functions.transfer(address_to, value).buildTransaction({
        'chainId':
        1,
        'gas':
        100000,
        'gasPrice':
        w3.toWei(gas_price, 'gwei'),
        'nonce':
        nonce,
    })
    signed_txn = w3.eth.account.signTransaction(
        txn, Talao_wallet_ethereum_private_key)
    try:
        w3.eth.sendRawTransaction(signed_txn.rawTransaction)
        hash = w3.toHex(w3.keccak(signed_txn.rawTransaction))
        print('Warning : token transfer transaction brdge_ethereum.py= ', hash)
        #receipt = w3.eth.waitForTransactionReceipt(
        #    hash, timeout=2000, poll_latency=1)
        #if receipt['status'] == 0:
        #    print('transaction failed')
        #    return None
        #print('Ethereum Talao Token synchronization is done for ', address)
        return hash
    except:
        print('transaction refused')
        return None