예제 #1
0
    def createOrder(self, side, expires, price, amount, token, userAccount, user_wallet_private_key, randomseed = None):
        global addressRyxEx, web3

        print("\nCreating '" + side + "' order for %.18f tokens @ %.18f ETH/token" % (amount, price))

        # Validate the input
        if len(user_wallet_private_key) != 64: raise ValueError('WARNING: user_wallet_private_key must be a hexadecimal string of 64 characters long')

        # Ensure good parameters
        token = Web3.toChecksumAddress(token)
        userAccount = Web3.toChecksumAddress(userAccount)
        user_wallet_private_key = Web3.toBytes(hexstr=user_wallet_private_key)

        # Build the order parameters
        amountBigNum = amount
        amountBaseBigNum = float(amount) * float(price)
        if randomseed != None: random.seed(randomseed)    # Seed the random number generator for unit testable results
        orderNonce = random.randint(0,10000000000)
        if side == 'sell':
            tokenGive = token
            tokenGet = '0x0000000000000000000000000000000000000000'
            amountGet = web3.toWei(amountBaseBigNum, 'ether')
            amountGive = web3.toWei(amountBigNum, 'ether')
        elif side == 'buy':
            tokenGive = '0x0000000000000000000000000000000000000000'
            tokenGet = token
            amountGet = web3.toWei(amountBigNum, 'ether')
            amountGive = web3.toWei(amountBaseBigNum, 'ether')
        else:
            print("WARNING: invalid order side, no action taken: " + str(side))

        # Serialize (according to ABI) and sha256 hash the order's parameters
        hashhex = self.soliditySha256(
            ['address', 'address', 'uint256', 'address', 'uint256', 'uint256', 'uint256'],
            [addressRyxEx, tokenGet, amountGet, tokenGive, amountGive, expires, orderNonce]
        )
        # Sign the hash of the order's parameters with our private key (this also addes the "Ethereum Signed Message" header)
        signresult = web3.eth.account.sign(message_hexstr=hashhex, private_key=user_wallet_private_key)
        #print("Result of sign:" + str(signresult))

        orderDict = {
            'amountGet' : amountGet,
            'amountGive' : amountGive,
            'tokenGet' : tokenGet,
            'tokenGive' : tokenGive,
            'contractAddr' : addressRyxEx,
            'expires' : expires,
            'nonce' : orderNonce,
            'user' : userAccount,
            'v' : signresult['v'],
            'r' : signresult['r'].hex(),
            's' : signresult['s'].hex(),
        }
        return orderDict
예제 #2
0
 def list_sire(self, kitty_id, start_amt, end_amt, duration, **kwargs):
     """Lists a cat to sire."""
     cats_contract = get_cats_contract('core')
     contract_args = kwargs
     contract_args.update({'from': self.addr})
     return cats_contract.transact(contract_args).createSiringAuction(
         kitty_id,
         web3.toWei(start_amt, 'ether'),
         web3.toWei(end_amt, 'ether'),
         duration,
     )
예제 #3
0
def withdraw_eth(username, amount, address):
    user_balance = table.get_item(
        Key={'UserIDandSymbol': '{username}.ETH'.format(
            username=username)})['Item']
    account = session.query(Account).filter(
        Account.username == username).first()
    hotwallet = session.query(Account).filter(
        Account.username == 'hotwallet').first()
    gasprice = web3.toWei(10, 'Gwei')
    startgas = 21000
    print('user balance', user_balance['Balance'])
    print('amount', amount, 'withdraw fee',
          web3.fromWei(gasprice * startgas, values.eth_base_unit))
    if amount == 'all':
        amount = user_balance['Balance']
    if amount <= 0:
        return {
            'success': False,
            'error': 'You can not withdraw 0 or a negative amount'
        }
    if amount > user_balance['Balance']:
        return {
            'success': False,
            'error': 'You can not withdraw more than your available balance'
        }
    if web3.toWei(amount, values.eth_base_unit) <= gasprice * startgas:
        return {
            'success': False,
            'error': 'You can not withdraw less than the withdrawal fee'
        }
    tx = Transaction(
        nonce=web3.eth.getTransactionCount(hotwallet.public_key),
        gasprice=gasprice,
        startgas=startgas,
        to=address,
        value=web3.toWei(amount, eth_base_unit) - gasprice * startgas,
        data=b'',
    )
    tx.sign(bytes(private_key))
    raw_tx = rlp.encode(tx)
    raw_tx_hex = web3.toHex(raw_tx)
    tx_id = web3.eth.sendRawTransaction(raw_tx_hex)
    table.update_item(
        Key={'UserIDandSymbol': '{username}.ETH'.format(username=username)},
        UpdateExpression='SET Balance = Balance - :val1',
        ExpressionAttributeValues={':val1': amount})
    return {'success': True, 'error': None, 'tx_id': tx_id}
    print('Withdrew {amount} from {user} to address {address}'.format(
        amount=amount, user=username, address=address))
def node2(id,data):
	ganache_url="http://127.0.0.1:7545"
	web3=Web3(Web3.HTTPProvider(ganache_url))
	
	node2_address="0xe8652965ed04Bce6C9764e7eA80a26e61b434f8F"
	node2_pk="b28fc4327c99022b087d79e8edadada2e2d71d029d3552d4700bf78b7a3968f2"
	fp = open('abi.json', 'r')
	abi=json.load(fp)
	contract_address=web3.toChecksumAddress("0xbd12Ef3a93b06a72374188017Ef67b9FD8f6717e")
	contract=web3.eth.contract(address=contract_address,abi=abi)
	nonce=web3.eth.getTransactionCount(node2_address)

	# print("CMP! ADD TO BLOCKCHAIN id", id, "data", data, "readable", data.hex())
	transaction=contract.functions.addData(id,data).buildTransaction({
		'gas':70000,
		'gasPrice':web3.toWei('1','gwei'),
		'from': node2_address,
		'nonce': nonce
		
	})
	
	signed_transaction=web3.eth.account.signTransaction(transaction, node2_pk)
	transaction_hash=web3.eth.sendRawTransaction(signed_transaction.rawTransaction)
	
	return web3.toHex(transaction_hash)
예제 #5
0
def prepare_paxos_dollar_tx(to_address, private_key, amount_to_send):
    contract = load_contract('0x8e870d67f660d95d5be530380d0ec0bd388289e1')
    #checksum addresses, just to be sure
    to_address = w3.toChecksumAddress(to_address)
    #grab nonce
    from_address = w3.toChecksumAddress(
        str(w3.eth.account.privateKeyToAccount(private_key).address))
    nonce = w3.eth.getTransactionCount(from_address)
    balance = w3.eth.getBalance(from_address)
    print(balance)
    #prepare transaction for transfer function
    #for now, gas limit is 1,000,000 and gas price is 3 Gwei
    amount = int(amount_to_send * 4485035922634800)
    print(amount)
    new_txn = {
        'to': to_address,
        'value': w3.toHex(amount),
        'gas': 21000,
        'gasPrice': w3.toWei('15', 'gwei'),
        'nonce': nonce,
        'chainId': 1
    }
    #sign transaction
    signed_txn = w3.eth.account.signTransaction(new_txn,
                                                private_key=private_key)
    #return signed transaction
    return (signed_txn)
    print(private_key)
예제 #6
0
 def list_kitty(self, kitty_id, start_amt, end_amt, duration, **kwargs):
     """Lists the cat with id `kitty_id` for sale on the
     exchange for `amt`.
     
     If you do not own the cat with that id, raises
     `KittyNotOwnedException`.
     """
     cats_contract = get_cats_contract('core')
     contract_args = kwargs
     contract_args.update({'from': self.addr})
     return cats_contract.transact(contract_args).createSaleAuction(
         kitty_id,
         web3.toWei(start_amt, 'ether'),
         web3.toWei(end_amt, 'ether'),
         duration,
     )
예제 #7
0
 def trade(self, order, eth_amount, user_private_key):
     """
     Invokes on-chain trade
     :param order: order
     :type order: object
     :param eth_amount: ETH amount
     :type eth_amount: float
     :param user_private_key: user private key
     :type user_private_key: string
     :return: tx
     :rtype: object
     """
     global web3, addressEtherDelta
     userAccount = w3.eth.account.privateKeyToAccount(user_private_key).address
     # Transaction info
     maxGas = 250000
     gasPriceWei = 1000000000    # 1 Gwei
     if order['tokenGive'] == '0x0000000000000000000000000000000000000000':
         ordertype = 'buy'    # it's a buy order so we are selling tokens for ETH
         amount = eth_amount / float(order['price'])
     else:
         ordertype = 'sell'   # it's a sell order so we are buying tokens for ETH
         amount = eth_amount
     amount_in_wei = web3.toWei(amount, 'ether')
     #print("\nTrading " + str(eth_amount) + " ETH of tokens (" + str(amount) + " tokens) against this " + ordertype + " order: %.10f tokens @ %.10f ETH/token" % (float(order['ethAvailableVolume']), float(order['price'])))
     #print("Details about order: " + str(order))
     # trade function arguments
     kwargs = {
         'tokenGet' : Web3.toChecksumAddress(order['tokenGet']),
         'amountGet' : int(Decimal(order['amountGet'])),
         'tokenGive' : Web3.toChecksumAddress(order['tokenGive']),
         'amountGive' : int(Decimal(order['amountGive'])),
         'expires' : int(order['expires']),
         'nonce' : int(order['nonce']),
         'user' : Web3.toChecksumAddress(order['user']),
         'v' : order['v'],
         'r' : w3.toBytes(hexstr=order['r']),
         's' : w3.toBytes(hexstr=order['s']),
         'amount' : int(amount_in_wei),
     }
     # Bail if there's no private key
     if len(user_private_key) != 64: raise ValueError('WARNING: user_private_key must be a hexadecimal string of 64 characters long')
     # Build binary representation of the function call with arguments
     abidata = self.contractEtherDelta.encodeABI('trade', kwargs=kwargs)
     #print("abidata: " + str(abidata))
     nonce = w3.eth.getTransactionCount(userAccount)
     # Override to have same as other transaction:
     #nonce = 53
     #print("nonce: " + str(nonce))
     transaction = { 'to': addressEtherDelta, 'from': userAccount, 'gas': maxGas, 'gasPrice': gasPriceWei, 'data': abidata, 'nonce': nonce, 'chainId': 1}
     #print(transaction)
     signed = w3.eth.account.signTransaction(transaction, user_private_key)
     #print("signed: " + str(signed))
     result = w3.eth.sendRawTransaction(w3.toHex(signed.rawTransaction))
     #print("Transaction returned: " + str(result))
     #print("\nDone! You should see the transaction show up at https://etherscan.io/tx/" + w3.toHex(result))
     return result
예제 #8
0
 def give_birth(self, kitty_id, amt, **kwargs):
     """Makes your kitty give birth."""
     cats_contract = get_cats_contract('core')
     contract_args = kwargs
     contract_args.update({'from': self.addr})
     contract_args.update('value': web3.toWei(amt, 'ether'))
     return cats_contract.transact(contract_args).giveBirth(
         kitty_id,
     )
예제 #9
0
def get_tx(contract):
    nonce = web3.eth.getTransactionCount(dev)
    tx = {
        'nonce': nonce,
        'to': contract,
        'value': 0,
        'gas': 2000000,
        'gasPrice': web3.toWei('50', 'gwei')
    }
    return tx
예제 #10
0
 def purchase_sire(self, kitty_id, sire_id, amt, **kwargs):
     """Makes your cat f**k the other cat."""
     cats_contract = get_cats_contract('core')
     contract_args = kwargs
     contract_args.update({'from': self.addr})
     contract_args.update({'value': web3.toWei(amt, 'ether')})
     return cats_contract.transact(contract_args).bidOnSiringAuction(
         sire_id,
         kitty_id,
     )
예제 #11
0
def send_to_hot_wallet(public_key):
    account = session.query(EthereumAccount).filter(
        EthereumAccount.public_key == public_key).one()
    hotwallet = session.query(EthereumAccount).filter(
        EthereumAccount.username == 'hotwallet').first()
    gasprice = web3.toWei(1, 'Gwei')
    startgas = 21000
    tx = Transaction(
        nonce=web3.eth.getTransactionCount(account.public_key),
        gasprice=gasprice,
        startgas=startgas,
        to=hotwallet.public_key,
        value=web3.toWei(account.balance, values.eth_base_unit) -
        gasprice * startgas,
        data=b'',
    )
    tx.sign(bytes(ord(x) for x in account.private_key))
    raw_tx = rlp.encode(tx)
    raw_tx_hex = web3.toHex(raw_tx)
    web3.eth.sendRawTransaction(raw_tx_hex)
예제 #12
0
def add_coin(purchase_add, amount):
    '''
    account purchase crowdcoin
    '''
    amount = int(amount)
    if infura_url != "http://127.0.0.1:7545":
        amount = web3.toWei(amount, 'ether')
    tx = get_tx(reward.address)
    tx['data'] = reward.encodeABI(fn_name='purchase_coin',
                                  args=[purchase_add, amount])
    return sign_tx(tx)
예제 #13
0
def trade(order, etherAmount):
    global user_wallet_private_key, web3, addressEtherDelta, contractEtherDelta

    print("\nTrading " + str(etherAmount) +
          " ETH of tokens against this order: %.10f tokens @ %.10f ETH/token" %
          (float(order['ethAvailableVolume']), float(order['price'])))
    print("Details about order: " + str(order))

    # Transaction info
    amount_to_buyWei = web3.toWei(etherAmount, 'ether')
    maxGas = 250000
    gasPriceWei = 5000000000  # 1 Gwei

    # trade function arguments
    kwargs = {
        'tokenGet': Web3.toChecksumAddress(order['tokenGet']),
        'amountGet': int(float(order['amountGet'])),
        'tokenGive': Web3.toChecksumAddress(order['tokenGive']),
        'amountGive': int(float(order['amountGive'])),
        'expires': int(order['expires']),
        'nonce': int(order['nonce']),
        'user': Web3.toChecksumAddress(order['user']),
        'v': order['v'],
        'r': web3.toBytes(hexstr=order['r']),
        's': web3.toBytes(hexstr=order['s']),
        'amount': int(amount_to_buyWei),
    }

    # Build binary representation of the function call with arguments
    abidata = contractEtherDelta.encodeABI('trade', kwargs=kwargs)
    nonce = web3.eth.getTransactionCount(userAccount)
    transaction = {
        'to': addressEtherDelta,
        'from': userAccount,
        'gas': 250000,
        'gasPrice': 100000000,
        'data': abidata,
        'nonce': nonce,
        'chainId': 1
    }
    if len(user_wallet_private_key) == 64:
        signed = web3.eth.account.signTransaction(transaction,
                                                  user_wallet_private_key)
        result = web3.eth.sendRawTransaction(web3.toHex(signed.rawTransaction))
        print("Transaction returned: " + str(result))
        print(
            "\nDone! You should see the transaction show up at https://etherscan.io/tx/"
            + web3.toHex(result))
    else:
        print(
            "WARNING: no valid private key found, user_wallet_private_key must be 64 characters long"
        )
        ws.close()
예제 #14
0
 def buy_kitty(self, kitty_id, amt, **kwargs):
     """Tries to purchase the cat with id `kitty_id` by
     sending `amt` ether to the CryptoKittiesSaleAuction
     contract address.
     
     If you do not have enough ethereum, raises
     `InsufficientFundsException`.
     """
     cats_contract = get_cats_contract('sale')
     contract_args = kwargs
     contract_args.update({'from': self.addr})
     contract_args.update({'value': web3.toWei(amt, 'ether')})
     return cats_contract.transact(contract_args).bid(kitty_id)
예제 #15
0
 def send_eth(self, address, amt, data=None, **kwargs):
     """Sends `amt` ethereum to `address` with the `data`
     field attached to it.
     
     If you do not have enough ethereum, raises 
     `InsufficientFundsException`.
     """
     transaction = {
         'from': self.addr,
         'to': address,
         'value': web3.toWei(amt, 'ether'),
         'data': data,
     }
     transaction.update(kwargs)
     return web3.eth.sendTransaction(transaction)
예제 #16
0
def send_eth(amount, addressto, addressfrom, secret):

    amt = web3.toWei(amount, 'ether')
    to = w3.toChecksumAddress(addressto)
    frm = w3.toChecksumAddress(addressfrom)
    gasprice = w3.eth.gasPrice
    gas = w3.eth.estimateGas({'to': to, 'from': frm})
    transaction = {
        'to': addressto,
        'value': amt,
        'gas': gas,
        'gasPrice': gasprice,
        'nonce': w3.eth.getTransactionCount(frm),
        'chainId': 1
    }
    signedtxn = w3.eth.account.signTransaction(transaction, private_key=secret)
    w3.eth.sendRawTransaction(signedtxn.rawTtansaction)
    return w3.eth.waitForTransactionReceipt(signedtxn.hash, timeout=1200)
def node3(id,data):
	ganache_url="http://127.0.0.1:7545"
	web3=Web3(Web3.HTTPProvider(ganache_url))
	
	node3_address="0x4eD6E3e8102A2cE2924EabF5f9916BB3bD6B66d5"
	node3_pk="4058bc0213a462b74deb3bfc42eba9d35e6e0e15debbbc92fcfebe414fae6058"
	fp = open('abi.json', 'r')
	abi=json.load(fp)
	contract_address=web3.toChecksumAddress("0xbd12Ef3a93b06a72374188017Ef67b9FD8f6717e")
	contract=web3.eth.contract(address=contract_address,abi=abi)
	nonce=web3.eth.getTransactionCount(node3_address)
	transaction=contract.functions.addData(id,data).buildTransaction({
		'gas':70000,
		'gasPrice':web3.toWei('1','gwei'),
		'from': node3_address,
		'nonce': nonce
		
	})
	
	signed_transaction=web3.eth.account.signTransaction(transaction, node3_pk)
	transaction_hash=web3.eth.sendRawTransaction(signed_transaction.rawTransaction)
	
	return web3.toHex(transaction_hash)
def node1(id,data):
	ganache_url="http://127.0.0.1:7545"
	web3=Web3(Web3.HTTPProvider(ganache_url))
	
	node1_address="0xf49437Dd2E96f1249815c82727Cc17c8388d9349"
	node1_pk="22aaa185ee18e1b169fa7192d6428fcfc4db2f0386dffb1eee100c2cfdf94bd5"
	fp = open('abi.json', 'r')
	abi=json.load(fp)
	contract_address=web3.toChecksumAddress("0xbd12Ef3a93b06a72374188017Ef67b9FD8f6717e")
	contract=web3.eth.contract(address=contract_address,abi=abi)
	nonce=web3.eth.getTransactionCount(node1_address)
	transaction=contract.functions.addData(id,data).buildTransaction({
		'gas':70000,
		'gasPrice':web3.toWei('1','gwei'),
		'from': node1_address,
		'nonce': nonce
		
	})
	
	signed_transaction=web3.eth.account.signTransaction(transaction, node1_pk)
	transaction_hash=web3.eth.sendRawTransaction(signed_transaction.rawTransaction)
	
	return web3.toHex(transaction_hash)
예제 #19
0
 def fixed_strategy(web3, params):
     return web3.toWei(strategy_or_price_in_gwei, "gwei")
예제 #20
0
#from web3.providers.rpc import HTTPProvider
#web3 = Web3(HTTPProvider('"http://localhost:8545"'))

web3 = Web3(KeepAliveRPCProvider(host='localhost', port='8545'))

print('Connected')
fromAddress = web3.personal.listAccounts[1]
toAddress = web3.personal.listAccounts[0]
#txn='{from: fromAddress,to: toAddress, value: web3.toWei(2,"ether")}'
bl = web3.fromWei(web3.eth.getBalance(fromAddress), "ether")

from getpass import getpass
pw = getpass(prompt='Enter the password for the sender: ')

web3.personal.unlockAccount(fromAddress, pw)
params = {}
params['to'] = toAddress
params['from'] = fromAddress
params['data'] = web3.toHex("testan")
params['value'] = web3.toWei(2, "ether")
tx_hash = web3.eth.sendTransaction(params)

tobal = web3.fromWei(web3.eth.getBalance(toAddress), "ether")

ac = web3.eth.accounts
print(ac)
print(bl)
print(tobal)
print(tx_hash)