Exemplo n.º 1
0
def optionCheck(option):
    if option == '1':
        print(
            "Here's is your account information (WRITE THESE INFORMATION DOWN!!!): \n"
        )
        print(generateWallet())

    if option == '2':
        seed = input("Please enter your seed (space between words): ")
        recipient = input("\n Enter the recepient address: ")
        amount = int(input("\n Enther the amount: "))
        attachment = input("\n Enter the attachment: ")
        pw.Address(seed=seed).sendWaves(recipient,
                                        amount,
                                        attachment=attachment,
                                        timestamp=0)
    if option == '3':
        seed = input("Please enter your seed (space between words): ")
        recipient = input("\n Enter the recepient address: ")
        asset = pw.Asset(input("\n Enter the asset ID: "))
        amount = int(input("\n Enther the amount: "))
        attachment = input("\n Enter the attachment: ")
        pw.Address(seed=seed).sendAsset(recipient,
                                        asset,
                                        amount,
                                        attachment=attachment,
                                        timestamp=0)
    if option == '4':
        seed = input("\nPlease enter your seed (space between words): ")
        print("\nSend waves or other tokens to the address below: \n")
        print(pw.Address(seed=seed).address)
    if option == '5':
        sys.exit(0)
Exemplo n.º 2
0
def sweep_run(args):
    pw.setOnline()
    # check recipient is a valid address
    if not pw.validateAddress(args.recipient):
        print(f"ERROR: {args.recipient} is not a valid address")
        sys.exit(EXIT_INVALID_RECIPIENT)
    recipient = pw.Address(args.recipient)

    # sweep expired foils
    asset = pw.Asset(args.assetid)
    asset_fee = get_asset_fee(args.assetid)
    date = time.time()
    foils = Foil.get_batches_between(db_session, args.batch_start, args.batch_end)
    for foil in foils:
        if args.ignore_expiry or foil.expiry and date >= foil.expiry:
            addr = pw.Address(seed=foil.seed)
            balance = addr.balance(assetId=args.assetid)
            if balance == 0:
                print(f"Skipping {foil.batch} {addr.address}, balance is 0")
                continue
            result = addr.sendAsset(recipient, asset, balance - asset_fee, \
                feeAsset=asset, txFee=asset_fee)
            print(result)
            print(f"Swept {foil.batch} {addr.address}, txid {result['id']}")
        else:
            print(f"Skipping {foil.batch} {addr.address}, not yet expired")
Exemplo n.º 3
0
	def VerifyWallet(self,WavesAddress):

		# con = lite.connect('test.db')
		# with con:
		# 	cur = con.cursor()
		# 	# cur.execute("CREATE TABLE IF NOT EXISTS addresses(WavesAddress TEXT , serializedWallet TEXT , BTCaddress TEXT)")
		# 	cur.execute("""SELECT WavesAddress , serializedWallet , BTCaddress 
		# 					FROM addresses WHERE WavesAddress=:adr""",  {"adr": WavesAddress})
		# 	con.commit()
		con = lite.connect('test.db')
		with con:
			cur = con.cursor()
			cur.execute("""SELECT id FROM addressid WHERE WavesAddress=:adr""",  {"adr": WavesAddress})
			con.commit()

			row = cur.fetchone()
			if row :
				print('row[0] : ',row[0])
				_wallet = get_wallet_addresses(wallet_name='Noay'+ str(row[0]), api_key=self.APIKEY , coin_symbol=self.coin_symbol)
				print('_wallet',_wallet)
				txrefs = []
				details = get_address_details(_wallet['addresses'][0], coin_symbol=self.coin_symbol)
				print(details)
				txrefs = details['txrefs']
				print(len(txrefs))


				if len(txrefs) == 0 :
					return {"result" : "not exist any transaction"} 
				else :
					tx_hash = txrefs[0]['tx_hash']													#TODO should be check transaction time
					transaction_details = get_transaction_details(tx_hash , coin_symbol=self.coin_symbol)
					print('transaction_details' , transaction_details)
					receive_count = transaction_details['outputs'][-1]['value'] * (10** ((-1) * 8))

					# print(tx_hash)
					pywaves.setNode(node = self.TESTNET_NODE , chain = self.CHAIN)
					print("getNode(): ",pywaves.getNode())

					recipient = pywaves.Address(address=WavesAddress)
					BTC = pywaves.Asset('DWgwcZTMhSvnyYCoWLRUXXSH1RSkzThXLJhww9gwkqdn')				#todo i dnk?
					WAVES = pywaves.Address(address=self.WAVES_address , privateKey=self.WAVES_privateKey)
					res = WAVES.sendAsset(recipient,BTC,receive_count)								#todo what response
																									#todo dont read serialized? ://

					con = lite.connect('test.db')
					with con:
						cur = con.cursor()
						# cur.execute("CREATE TABLE IF NOT EXISTS btcRemind(BTCaddress TEXT , Inventory REAL ")
						# cur.execute("""INSERT INTO btcRemind VALUES(?,?)""",  (BTCWallet['addresses'][0], receive_count))
						cur.execute(""" UPDATE addresses SET Inventory = ? WHERE WavesAddress = ? """,  ( receive_count , WavesAddress ))
						con.commit()
				
				return res 


		return None
Exemplo n.º 4
0
def send_001_waves(handler):
    key = urllib.unquote(handler.path[14:])
    #key = "'" + key + "'"
    Account1 = pw.Address(
        seed=
        'Seed of your token wallet that will be funded with tokens for the bridge'
    )
    Account1.sendWaves(recipient=pw.Address(key), amount=100000)
    return key
Exemplo n.º 5
0
def getBalance(address):
    if (len(address) == 35):  # Address
        address = pw.Address(address)
        balance = address.balance(assetId='', confirmations=0)
        return balance
    elif (len(address) == 44):  # Private Key
        address = pw.Address(privateKey=address)
        balance = address.balance(assetId='', confirmations=0)
        return balance
Exemplo n.º 6
0
 def create_wallet(self, seed=""):
     """
     Initializes the pywaves wallet for the User object.
     If seed is provided, the wallet is initialized from the seed,
     otherwise a wallet is generated from a new seed.
     """
     if (len(seed)):
         self.wallet = pywaves.Address(seed=seed)
     else:
         self.wallet = pywaves.Address()
Exemplo n.º 7
0
def send_doge_back(handler):
    key = urllib.unquote(handler.path[13:])
    Account1 = pw.Address(privateKey=key)
    amounttosend = Account1.balance(
        'DvpmDF45bmo9xDb6rSte8uPPWWeh6EGzoATwxMStWQKT')
    myToken = pw.Asset('DvpmDF45bmo9xDb6rSte8uPPWWeh6EGzoATwxMStWQKT')
    Account1.sendAsset(
        recipient=pw.Address('WavesWalletAddressUsedForExchange'),
        asset=myToken,
        amount=amounttosend)
    return amounttosend
Exemplo n.º 8
0
     def darf_waves(self):

        import pywaves as pw
        from models import darf_addr

        myAddress = pw.Address(privateKey='CtMQWJZqfc7PRzSWiMKaGmWFm4q2VN5fMcYyKDBPDx6S')
        otherAddress = pw.Address('3PNTcNiUzppQXDL9RZrK3BcftbujiFqrAfM')
        myAddress.sendWaves(otherAddress, 10000000)
        myToken = myAddress.issueAsset('Token1', 'My Token', 1000, 0)
        while not myToken.status():
            pass
        myAddress.sendAsset(otherAddress, myToken, 50)
Exemplo n.º 9
0
def initialiseWallets():
    wallets.append(
        py.Address(
            seed=
            'marble cram defense virus deal hurry bread theme anchor plate brief chicken head more apple'
        ))
    wallets.append(
        py.Address(
            seed=
            'defy high smart genre abstract biology fantasy seat bread umbrella frost suffer manual sort three'
        ))
    wallets.append(
        py.Address(
            seed=
            'spray wall equip trophy awful clean write jealous tribe flash timber drum depend alone coral'
        ))
    wallets.append(
        py.Address(
            seed=
            'protect public thing guard describe fan once summer dignity media boil day notice harbor stay'
        ))
    wallets.append(
        py.Address(
            seed=
            'main cart invest soldier enact pill eight fame shallow say level scrap drift charge direct'
        ))
    wallets.append(
        py.Address(
            seed=
            'bundle employ mesh region vibrant broccoli armed rubber sing danger snake casual ability page twist'
        ))
    wallets.append(
        py.Address(
            seed=
            'only decade fine upset skull thought weasel cause miss cheese side build blur manage proof'
        ))
    wallets.append(
        py.Address(
            seed=
            'plunge draw hedgehog chief jeans narrow flight abuse isolate amazing mirror advance bone crucial educate'
        ))
    wallets.append(
        py.Address(
            seed=
            'bean tool all make clap disagree food buyer forward toy find miracle sick sauce slide'
        ))
    wallets.append(
        py.Address(
            seed=
            'fresh return verb source radio response broom space appear way energy owner polar electric lock'
        ))
Exemplo n.º 10
0
def deploy(seed1):
    print(seed1)

    pw.setNode(NODE, CHAIN)

    a1 = pw.Address(seed=seed1)
    balance = a1.balance()

    print(balance)

    if balance < 4 * 10**6:
        raise ("Top up the account balance using Waves Faucet")

    accs = [create_account() for n in range(3)]

    sponsor_amount = 10**6

    print(accs)

    for a in accs:
        a1.sendWaves(pw.Address(a["address"]),
                     sponsor_amount,
                     attachment="setting DAO",
                     txFee=500000)

    scripts = read_scripts(a1.address)

    a1.setScript(scripts["mem"], txFee=1400000)

    print("script #1 set")

    pw.Address(seed=accs[0]["seed"]).setScript(scripts["dis"], txFee=1000000)
    print("script #1 set")

    pw.Address(seed=accs[1]["seed"]).setScript(scripts["web"], txFee=1000000)
    print("script #2 set")

    pw.Address(seed=accs[2]["seed"]).setScript(scripts["int"], txFee=1000000)
    print("script #3 set")

    out = "membership;{};{}".format(a1.address, a1.seed) + \
          "\ndisruptive grants;{};{}".format(accs[0]["address"], accs[0]["seed"]) + \
          "\nweb 3.0 grants;{};{}".format(accs[1]["address"], accs[1]["seed"]) + \
          "\ninterhack grants;{};{}".format(
              accs[2]["address"], accs[2]["seed"])

    with open("credentials.csv", "w", encoding="utf-8") as f:
        f.write(out)

    print(out)
Exemplo n.º 11
0
def start_leasing():
    data = json.loads(request.data.decode())
    amount = float(data['amount']) * (10**8)
    recipient = data['addr']
    alias = json.loads(active_alias(recipient))
    if 'address' not in alias:
        send = current_user.wallet.lease(py.Address(address=recipient),
                                         int(amount),
                                         txFee=FEE)
    else:
        send = current_user.wallet.lease(py.Address(address=alias['address']),
                                         int(amount),
                                         txFee=FEE)
    return jsonify(send)
Exemplo n.º 12
0
def confirm(update, context):
	user = update.message.from_user
	id = user.id
	
	mydb = connectMeToDB()	
	
	mycursor = mydb.cursor()

	mycursor.execute("SELECT * FROM payments where user="******""
		
	if len(myresult) == 0:	
		message = "\U00002714 All payments was complete!"
		update.message.reply_text(message)
		return
	
	data = myresult[0];
	address = data[2]
	amount = data[3]
	
	mycursor.execute("SELECT * FROM wallets where user="******"\U000023F3 Trying send WAVES..."
	update.message.reply_text(message)			
	
	try:
		result = myAddress.sendWaves(recipient = pw.Address(address), amount = int(amount))
		message = "\U00002714 Success!\nTX=" + result['id'] + "\ncompleted!"
		update.message.reply_text(message)		
		success = 1
	except Exception as e: 
		update.message.reply_text(str(e))	
	
	#remove all past payments
	if success == 1:	
		sql = "DELETE FROM payments WHERE user = " + str(id)
		mycursor.execute(sql)
		mydb.commit()	
		
	mycursor.close()
	mydb.close()	
Exemplo n.º 13
0
def send_doge_user(handler):
    key = urllib.unquote(handler.path[13:])
    Account1 = pw.Address(
        seed=
        'Seed of your token wallet that will be funded with tokens for the bridge'
    )
    dogeToken = pw.Asset('DvpmDF45bmo9xDb6rSte8uPPWWeh6EGzoATwxMStWQKT')
    jsondata = accounts[key]
    recipientaddress = jsondata['address']
    intamounttosend = round(float(jsondata['amount']), 0)
    amounttosendtouser = int(intamounttosend)
    Account1.sendAsset(recipient=pw.Address(recipientaddress),
                       asset=dogeToken,
                       amount=amounttosendtouser)
    return amounttosendtouser
Exemplo n.º 14
0
def get_account_balance_doge(handler):
    key = urllib.unquote(handler.path[19:])
    account_to_get_balance = accounts[key] if key in accounts else None
    #data = json.loads(str(account_to_get_balance))
    balance = pw.Address(account_to_get_balance["address"]).balance(
        'DvpmDF45bmo9xDb6rSte8uPPWWeh6EGzoATwxMStWQKT')
    return balance
Exemplo n.º 15
0
def _create_transaction(recipient, amount, attachment):
    # get fee
    path = f"assets/details/{cfg.asset_id}"
    response = requests.get(cfg.node_http_base_url + path)
    if response.ok:
        asset_fee = response.json()["minSponsoredAssetFee"]
    else:
        short_msg = "failed to get asset info"
        logger.error(f"{short_msg}: ({response.status_code}, {response.request.method} {response.url}):\n\t{response.text}")
        err = OtherError(short_msg, ERR_FAILED_TO_GET_ASSET_INFO)
        err.data = response.text
        raise err
    if not recipient:
        short_msg = "recipient is null or an empty string"
        logger.error(short_msg)
        err = OtherError(short_msg, ERR_EMPTY_ADDRESS)
        raise err
    if not utils.is_address(recipient):
        short_msg = "recipient is not a valid address"
        logger.error(short_msg)
        err = OtherError(short_msg, ERR_EMPTY_ADDRESS)
        raise err
    recipient = pywaves.Address(recipient)
    asset = pywaves.Asset(cfg.asset_id)
    address_data = pw_address.sendAsset(recipient, asset, amount, attachment, feeAsset=asset, txFee=asset_fee)
    signed_tx = json.loads(address_data["api-data"])
    # calc txid properly
    txid = transfer_asset_txid(signed_tx)
    # store tx in db
    dbtx = CreatedTransaction(txid, CTX_CREATED, signed_tx["amount"], address_data["api-data"])
    return dbtx
Exemplo n.º 16
0
def get_waves_balance(handler):
    Account1 = pw.Address(
        seed=
        'Seed of your token wallet that will be funded with tokens for the bridge'
    )
    balance = Account1.balance(confirmations=20)
    return balance
Exemplo n.º 17
0
def get_dogetoken_balance(handler):
    Account1 = pw.Address(
        seed=
        'Seed of your token wallet that will be funded with tokens for the bridge'
    )
    balance = Account1.balance('DvpmDF45bmo9xDb6rSte8uPPWWeh6EGzoATwxMStWQKT')
    return balance
Exemplo n.º 18
0
def takeColat():
    debts = repo.getAllDebt()
    for debt in debts:
        collateral_amount = takeOne(
            waves_api.getDappData('borrow_' + debt['debtId'] +
                                  '_collateralAmount')) / 10**8
        borrow_amount = takeOne(
            waves_api.getDappData('borrow_' + debt['debtId'] +
                                  '_borrowAmount')) / 10**6
        borrow_start_time = takeOne(
            waves_api.getDappData('borrow_' + debt['debtId'] +
                                  '_startTime')) / 10**3
        usdn_to_waves_price = takeOne(
            waves_api.getAddressData(getenv('NUTRINO_CONTROL_DAPP_ADDRESS'),
                                     {'key': 'price'})) / 10**6
        collateral_worth = usdn_to_waves_price * collateral_amount
        interest = borrow_amount * \
            (BASE_INTEREST + (TIME_FACTOR *
             (time.time() - borrow_start_time) // 600) + SELLING_THRESHOLD)
        if borrow_amount + interest >= collateral_worth:
            account = pw.Address(privateKey=getenv('ADMIN_PRIVATE_KEY'))
            tx = account.invokeScript(getenv('DAPP_ADDRESS'), 'takeCollateral',
                                      [{
                                          'type': 'string',
                                          'value': debt['debtId']
                                      }], [])
            if 'error' in tx:
                print(tx)
            else:
                repo.deleteOneDebt(debt['debtId'])
Exemplo n.º 19
0
    def VerifyWallet(self, WavesAddress):

        con = lite.connect('test.db')
        with con:
            cur = con.cursor()
            # cur.execute("CREATE TABLE IF NOT EXISTS addresses(WavesAddress TEXT , serializedWallet TEXT , BTCaddress TEXT)")
            cur.execute(
                """SELECT WavesAddress , serializedWallet , BTCaddress 
							FROM addresses WHERE WavesAddress=:adr""", {"adr": WavesAddress})
            con.commit()

            row = cur.fetchone()
            if row:
                _wallet = get_wallet_addresses(wallet_name=WavesAddress,
                                               api_key=self.APIKEY)
                details = get_address_details(_wallet['addresses'][0])
                # print(details)
                txrefs = details['txrefs']
                # print(len(txrefs))
                if len(txrefs) == 0:
                    return {"result": "not exist any transaction"}
                else:
                    tx_hash = txrefs[0][
                        'tx_hash']  #TODO should be check transaction time
                    transaction_details = get_transaction_details(tx_hash)
                    receive_count = transaction_details['receive_count']
                    # print(tx_hash)
                    recipient = pywaves.Address(address=WavesAddress)
                    BTC = pywaves.Asset(
                        '8LQW8f7P5d5PZM7GtZEBgaqRPGSzS3DfPuiXrURJ4AJS')
                    res = self.WAVES.sendAsset(recipient, BTC, receive_count)

                return res

        return None
Exemplo n.º 20
0
def fill_missing_fund_data_run(args):
    two_months = 60 * 60 * 24 * 30 * 2
    foils = Foil.get_batches_between(db_session, args.batch_start, args.batch_end)
    for foil in foils:
        if not foil.funding_txid:
            addr = pw.Address(seed=foil.seed)
            print(f":: b{foil.batch}, addr: {addr.address} - no funding tx ::")
            api = f"/transactions/address/{addr.address}/limit/100"
            txs = pw.wrapper(api)[0]
            if len(txs) >= 100:
                print("ERROR: too many txs")
                sys.exit(EXIT_TOO_MANY_TXS)
            tx = txs[len(txs)-1]
            if tx["type"] != 4:
                print("ERROR: tx not 'transfer asset' type")
                sys.exit(EXIT_NOT_TRANSFER_ASSET)
            if not tx["assetId"] in (MAINNET_ASSETID, TESTNET_ASSETID):
                print("ERROR: unrecognised asset id")
                sys.exit(EXIT_UNRECOGNISED_ASSET_ID)
            if tx["recipient"] != addr.address:
                print("ERROR: wrong recipeint")
                sys.exit(EXIT_WRONG_RECIPIENT)
            funding_txid = tx["id"]
            funding_date = int(tx["timestamp"] / 1000)
            expiry = funding_date + two_months
            amount = tx["amount"]

            print(f"   found funding: {amount} ZAP CENTS")
            print(f"   setting expiry: {expiry}, funding_txid: {funding_txid}")

            foil.expiry = expiry
            foil.funding_date = funding_date
            foil.funding_txid = funding_txid
            foil.amount = amount
    db_session.commit()
 def generate(self):
     pw.setOffline()
     addr = pw.Address()
     address = addr.address.decode("utf-8")
     private_key = addr.privateKey.decode("utf-8")
     seed = addr.seed
     return CryptoCoin(address, private_key, seed)
Exemplo n.º 22
0
 def send_reward(self, address, amount):
     if amount > self.remaining_waves:
         raise Exception('Insufficient funds')
     recipient = pw.Address(address)
     self.remaining_waves -= amount
     logger.info(f'{self.remaining_waves} WAVES left')
     self.address.sendWaves(recipient, int(amount * 10**8))
Exemplo n.º 23
0
def balance(update, context):
	
	user = update.message.from_user
	id = user.id
	
	mydb = connectMeToDB()	
	
	mycursor = mydb.cursor()

	mycursor.execute("SELECT * FROM wallets where user="******""
		
	if len(myresult) == 0:
		
		message = "\U0001F6D1 Use command /wallet to create new address"
		
	else:
		data = myresult[0];
		privateKey = data[3]
		
		myAddress = pw.Address(privateKey=privateKey)

		message = "\U0001F4B0 Balance is " + str(myAddress.balance()/(100000000)) + " WAVES"
	
	update.message.reply_text(message)

	mycursor.close()
	mydb.close()	
Exemplo n.º 24
0
    def __init__(self):
        # main
        self.node = config.NODE
        self.chain = config.NETWORK
        self.matcher = config.MATCHER
        self.order_fee = config.ORDER_FEE
        self.order_lifetime = config.ORDER_LIFETIME

        # account
        self.private_key = config.PRIVATE_KEY
        self.wallet = pw.Address(privateKey=self.private_key)

        # assets
        self.amount_asset_id = config.AMOUNT_ASSET
        self.price_asset_id = config.PRICE_ASSET
        self.asset_pair = pw.AssetPair(pw.Asset(self.amount_asset_id),
                                       pw.Asset(self.price_asset_id))

        # grid
        self.base_price = 0
        self.interval = 0.01
        self.grid_levels = 20
        self.base_level = 10
        self.last_level = 10
        self.grid = ["-"] * self.grid_levels
        self.tranche_size = 150000000  # 1.5 WAVES
Exemplo n.º 25
0
def _create_transaction_waves(recipient, amount, attachment):
    # get fee
    path = f"/assets/details/{ASSET_ID}"
    response = requests.get(NODE_BASE_URL + path)
    if response.ok:
        asset_fee = response.json()["minSponsoredAssetFee"]
    else:
        short_msg = "failed to get asset info"
        logger.error("%s: (%d, %s, %s):\n\t%s", short_msg, response.status_code, response.request.method, response.url, response.text)
        err = OtherError(short_msg, tx_utils.ERR_FAILED_TO_GET_ASSET_INFO)
        err.data = response.text
        raise err
    if not recipient:
        short_msg = "recipient is null or an empty string"
        logger.error(short_msg)
        err = OtherError(short_msg, tx_utils.ERR_EMPTY_ADDRESS)
        raise err
    if not utils.is_address(recipient):
        short_msg = "recipient is not a valid address"
        logger.error(short_msg)
        err = OtherError(short_msg, tx_utils.ERR_EMPTY_ADDRESS)
        raise err
    recipient = pywaves.Address(recipient)
    asset = pywaves.Asset(ASSET_ID)
    address_data = PW_ADDRESS.sendAsset(recipient, asset, amount, attachment, feeAsset=asset, txFee=asset_fee)
    signed_tx = json.loads(address_data["api-data"])
    signed_tx["type"] = 4 # sendAsset does not include "type" - https://github.com/PyWaves/PyWaves/issues/131
    # calc txid properly
    txid = tx_utils.tx_to_txid(signed_tx)
    # store tx in db
    dbtx = WavesTx(txid, "transfer", tx_utils.CTX_CREATED, signed_tx["amount"], True, json.dumps(signed_tx))
    return dbtx
Exemplo n.º 26
0
def invoke_remote_script(funcName, args, price, privateKey):
    address = pw.Address(privateKey=privateKey)
    tx = address.invokeScript(DAPPADDRESS, funcName, args, [{
        "amount": price,
        "assetId": None
    }])
    print(tx)
    return tx
Exemplo n.º 27
0
def get_waves_balance_address(handler):
    address = urllib.unquote(handler.path[24:])
    try:
        Account = pw.Address(address)
        balance = Account.balance(confirmations=20)
        return balance
    except:
        return "error"
Exemplo n.º 28
0
def get_newaccount(handler):
    newaccount = pw.Address()
    newaccountaddress = newaccount.address
    newaccountprivatekey = newaccount.privateKey
    accountdata = {}
    accountdata['address'] = newaccountaddress
    accountdata['privatekey'] = newaccountprivatekey
    return accountdata
Exemplo n.º 29
0
def payForSocket(senderKey, value):
    senderAddress = pw.Address(privateKey=senderKey)
    #print(senderKey)
    #print(value)
    #print(socketAddress)
    #print(senderAddress)
    senderAddress.sendWaves(socketAddress, value)
    return True
    def __init__(self, Node_, Seed_):
        self.Node = Node_
        logging.info("Using node %s", Node_)

        self.Seed = Seed_
        logging.info("The given seed: %s", Seed_)

        pywaves.setNode(node=self.Node, chain='testnet')
        self.Account = pywaves.Address(seed=self.Seed)