def balance(user_id): balance = Balance.query.filter_by(user_id=user_id).first() if request.method == "POST": value = request.json.get('value') if not balance: balance = Balance(user_id=user_id, value=value).create() else: balance.credit(value=value) return Response(json.dumps({ "balance": BalanceSchema().dump(balance) }), mimetype='application/json')
def create(): form = CreateForm() all_users = User.query.order_by(db.func.lower(User.username)) form.usernames.choices = [(u.username, u.username) for u in all_users] if form.validate_on_submit(): users = [ User.query.filter_by(username=username).first() for username in form.usernames.data ] pool = Pool() pool.new_from_cube() auction = Auction(starting_balance=form.starting_balance.data, time_limit=form.time_limit.data, default_lot=form.default_lot.data, pool=pool, users=users, creator=current_user) if form.first_nom.data: auction.add_lot(card=form.first_nom.data) else: auction.add_lot(size=form.default_lot.data) db.session.add(auction) db.session.flush() for user in users: new_balance = Balance(holder=user, auction=auction, amount=form.starting_balance.data) db.session.add(new_balance) db.session.commit() return redirect(url_for("auction", auction_id=auction.id)) return render_template("create.html", title="New Draft", form=form, cube_cards=cube_cards)
def register(): print('SESSION: ', session) if current_user.is_authenticated: return redirect(url_for('index')) form = RegistrationForm() if form.validate_on_submit(): address = get_from_bitcoind('getnewaddress', []) dumpPri = get_from_bitcoind('dumpprivkey', [address]) impoPri = get_from_bitcoind('importprivkey', [dumpPri]) user = User(first_name=form.first_name.data, last_name=form.last_name.data, username=form.username.data, address=address) user.set_password(form.password.data) db.session.add(user) db.session.commit() transfer = Transfer(tx_type='Deposit', amount=500000, currency='USD', confirmation_status=0, user_id=user.id) balances = Balance(confirmed_balance_btc=0, unconfirmed_balance_btc=0, balance_usd=500000, user_id=user.id) db.session.add_all([transfer, balances]) db.session.commit() flash('You have successfully registered - please log in') return redirect(url_for('login')) return render_template('register.html', title='Register', form=form)
def add_balance_to_udid(udid, credits=500, ip_addr=None, sec_code=None, app_name=None, icon_url=None, sec_check=False): user = User.objects.get(udid=udid) if not user: raise Exception if sec_check: should_give_credit = check_for_credits(udid, sec_code) if not should_give_credit: print 'Not the right security matching code' raise Exception added_history = add_app_history(user, app_name, icon_url, ip_addr) if not added_history: print 'already downlaoded app' raise Exception try: balance = Balance.objects.get(user_id=user.id) except Balance.DoesNotExist: balance = Balance() balance.user_id = user.id balance.balance = 0 balance.balance += credits balance.save() return balance
def trade(): user = current_user balances = Balance.query.filter_by(user_id=user.id).first() form = TradeForm() if form.validate_on_submit(): tx_type = form.option.data amount = form.btc_amount.data try: price = session['price'] total = price * amount # session.pop('price', None) except KeyError: price = 'N/A' total = 'N/A' print("Amount: ", amount) print("Price: ", price) print("Total: ", total) if all(isinstance(i, float) for i in [amount, price, total]): if (tx_type == 'Buy' and balances.balance_usd >= total) or \ (tx_type == 'Sell' and balances.balance_btc >= amount): if tx_type == 'Buy': new_balance_btc = balances.balance_btc + amount new_balance_usd = balances.balance_usd - total else: new_balance_btc = balances.balance_btc - amount new_balance_usd = balances.balance_usd + total db.session.delete(balances) db.session.commit() trade = Trade(tx_type=tx_type, amount=amount, price=price, total=total, user_id=user.id) new_balances = Balance(balance_btc=new_balance_btc, balance_usd=new_balance_usd, user_id=user.id) db.session.add_all([trade, new_balances]) db.session.commit() balances = Balance.query.filter_by(user_id=user.id).first() flash('Your {} trade was executed - {} BTC @ ${}'.format( tx_type.lower(), clean(amount), clean(price))) else: flash('Your {} trade failed - insufficient funds'.format( tx_type.lower())) else: return redirect(url_for('trade')) return render_template('trade.html', user=user, balances=balances, form=form)
def register(): if current_user.is_authenticated: return redirect(url_for('index')) form = RegistrationForm() if form.validate_on_submit(): user = User(first_name=form.first_name.data, last_name=form.last_name.data, username=form.username.data) user.set_password(form.password.data) db.session.add(user) db.session.commit() transfer = Transfer(tx_type='Deposit', amount=500000, currency='USD', user_id=user.id) balances = Balance(balance_btc=0, balance_usd=500000, user_id=user.id) db.session.add_all([transfer, balances]) db.session.commit() flash('You have successfully registered - please log in') return redirect(url_for('login')) return render_template('register.html', title='Register', form=form)
def get_deposit(): address = 'mqqHSBCp5873mK9WY3cR32KDx2pnEJBT2p' #address_balance_satoshis = blockcypher.get_total_balance(address, coin_symbol="btc-testnet", api_key="acb0b8a2fe3d479c8b05b415ded8021e") #address_balance = blockcypher.from_satoshis(address_balance_satoshis, 'btc') key = PrivateKeyTestnet('cPvDDZ8XREaxWnZNaZ2V8FeUrZYvwHk8kAMHVaFbFte1QZUuuTur') address_balance = float(key.get_balance('btc')) deposit = 'None' print("DEPOSIT ==> address_balance:", address_balance) print(" ==> session['address_balance']:", session['address_balance']) if address_balance > session['address_balance']: print(("\nNew address balance: {} Old address balance: {}\n").format(address_balance, session['address_balance'])) amount = address_balance - session['address_balance'] #address_txs = get_address_txs(address) address_txs = key.get_transactions() user = current_user balances = Balance.query.filter_by(user_id=user.id).first() latest_transfers = Transfer.query.filter_by(user_id=user.id).all() db_txs = [] for transfer in latest_transfers: db_txs.append(transfer.tx_id) new_balance_btc = balances.balance_btc + amount #tx = address_txs[0] #txid = tx[1] txid = address_txs[0] # if tx not in session['address_txs'] and txid not in db_txs: if txid not in db_txs: if all(isinstance(i, float) for i in [amount, new_balance_btc, balances.balance_usd]): # print(("\ntxid: {}\nPrevious txs: {}\n").format(txid, session['address_txs'])) db.session.delete(balances) db.session.commit() transfer = Transfer(tx_type='deposit', amount=amount, currency='BTC', tx_id=txid, user_id=user.id) new_balances = Balance(balance_btc=new_balance_btc, balance_usd=balances.balance_usd, user_id=user.id) db.session.add_all([transfer, new_balances]) db.session.commit() print(("\nTransfer: {}\nNew balances: {}\n").format(transfer, new_balances)) session['address_balance'] = address_balance # session['address_txs'] = address_txs deposit = txid return jsonify(result=deposit)
def check_withdrawal_confirmed(): withdrawal = 'None' user = current_user status = Transfer.query.filter_by(user_id=user.id).all() if status: confirmation_status = status[-1].confirmation_status tx_id = status[-1].tx_id tx_type = status[-1].tx_type transaction_info = get_from_bitcoind('gettransaction', [tx_id]) confirmations = transaction_info['confirmations'] balances = Balance.query.filter_by(user_id=user.id).first() balanceUsd = balances.balance_usd confirmedBalanceBTC = balances.confirmed_balance_btc unConfirmedBalanceBTC = balances.unconfirmed_balance_btc if confirmations >= 1 and confirmation_status == 0 and tx_type == 'withdrawal': confirmation_status = 1 db.session.delete(balances) db.session.commit() new_confirmed_balance_btc = unConfirmedBalanceBTC unConfirmedBalanceBTC = 0.00 new_balances = Balance(confirmed_balance_btc=new_confirmed_balance_btc, unconfirmed_balance_btc=unConfirmedBalanceBTC, balance_usd=balanceUsd, user_id=user.id) transfer = Transfer(tx_type='withdrawal', amount=new_confirmed_balance_btc, currency='BTC', tx_id=tx_id, confirmation_status=confirmation_status, user_id=user.id) db.session.add_all([transfer, new_balances]) db.session.commit() withdrawal = tx_id return jsonify(result=withdrawal)
def register(): """ Renders registration page. If form validates on submission and user email doesn't exist in the database, new user is created. """ form = RegisterForm(request.form) if request.method == 'POST': if form.validate_on_submit(): first_name = request.form.get('first_name') last_name = request.form.get('last_name') email = request.form.get('email').lower() passphrase = request.form.get('passphrase') existing_user = User.query.filter_by(email=email).first() if existing_user is None: new_user = User(first_name=first_name, last_name=last_name, email=email, passphrase=generate_password_hash( passphrase, method='sha256')) db.session.add(new_user) db.session.commit() new_user_id = new_user.get_user_id() new_balance = Balance(user_id=new_user_id, balance=format(5000.00, '.2f')) db.session.add(new_balance) db.session.commit() login_user(new_user) return redirect(url_for('main.portfolio')) else: flash('An account for this email address already exists.') return redirect(url_for('auth.register')) return render_template('register.html', form=form)
def get_withdrawal(): address = request.args.get('address', 0, type=str) amount = request.args.get('amount', 0, type=float) withdrawal = 'None' try: check = get_version(address) if check == 'test': if type(amount) is not float: withdrawal = 'error-amount' else: user = current_user balances = Balance.query.filter_by(user_id=user.id).first() latest_transfers = Transfer.query.filter_by(user_id=user.id).all() db_txs = [] for transfer in latest_transfers: db_txs.append(transfer.tx_id) new_balance_btc = balances.balance_btc - amount key = PrivateKeyTestnet('cPvDDZ8XREaxWnZNaZ2V8FeUrZYvwHk8kAMHVaFbFte1QZUuuTur') address_balance = key.get_balance() txid = key.send([(address, amount, 'btc')]) if txid not in db_txs: db.session.delete(balances) db.session.commit() transfer = Transfer(tx_type='withdrawal', amount=amount, currency='BTC', tx_id=txid, user_id=user.id) new_balances = Balance(balance_btc=new_balance_btc, balance_usd=balances.balance_usd, user_id=user.id) db.session.add_all([transfer, new_balances]) db.session.commit() print(("\nTransfer: {}\nNew balances: {}\n").format(transfer, new_balances)) withdrawal = txid else: withdrawal = 'error-main' except ValueError: withdrawal = 'error-address' if withdrawal in ['error-main', 'error-address']: if type(amount) is not float: withdrawal = 'error-both' return jsonify(result=withdrawal)
def executeTransaction(transaction): if transaction.sender == '0': balance = Balance.query.filter_by( user=transaction.receiver).first() if balance == None: balance = Balance(transaction.receiver) balance.deposit(transaction.amount) db.session.add(balance) else: balance.deposit(transaction.amount) db.session.commit() else: # need to be atomic sender = Balance.query.filter_by(user=transaction.sender).first() receiver = Balance.query.filter_by( user=transaction.receiver).first() if sender == None: print 'loaner ran away...' else: if sender.withdraw(transaction.amount): if receiver == None: receiver = Balance(transaction.receiver) receiver.deposit(transaction.amount) db.session.add(receiver) else: receiver.deposit(transaction.amount) db.session.commit() else: print 'loaner better ran away...'
def get_withdrawal(): address = request.args.get('address', 0, type=str) amount = request.args.get('amount', 0, type=float) withdrawal = 'None' try: if type(amount) is not float: withdrawal = 'error-amount' else: print("In else.........................") user = current_user balances = Balance.query.filter_by(user_id=user.id).first() print(balances) balanceUsd = balances.balance_usd confirmedBalanceBTC = balances.confirmed_balance_btc unConfirmedBalanceBTC = balances.unconfirmed_balance_btc addresses = [address] latest_transfers = Transfer.query.filter_by(user_id=user.id).all() db_txs = [] for transfer in latest_transfers: db_txs.append(transfer.tx_id) #tx_status[transfer.tx_id] = transfer.confirmation_status sendAmountTxID = get_from_bitcoind('sendtoaddress', [address, amount]) print("sendAmount...................", sendAmountTxID) transaction_info = get_from_bitcoind('gettransaction', [sendAmountTxID]) fees_BTC = float('%.07f' % transaction_info['fee']) print("fees.......................", fees_BTC) status = Transfer.query.filter_by(tx_id=sendAmountTxID).first() if status != None: confirmation_status = status.confirmation_status confirmations = transaction_info['confirmations'] if sendAmountTxID not in db_txs: confirmation_status = 0 db.session.delete(balances) db.session.commit() new_unconfirmed_balance_btc = '%.07f' % ( confirmedBalanceBTC - amount + fees_BTC ) #since fees coming - if unConfirmedBalanceBTC > 0: new_unconfirmed_balance_btc = '%.07f' % ( unConfirmedBalanceBTC + new_unconfirmed_balance_btc) new_balances = Balance( confirmed_balance_btc=confirmedBalanceBTC, unconfirmed_balance_btc=new_unconfirmed_balance_btc, balance_usd=balanceUsd, user_id=user.id) transfer = Transfer(tx_type='withdrawal', amount=amount, currency='BTC', tx_id=sendAmountTxID, confirmation_status=confirmation_status, user_id=user.id) db.session.add_all([transfer, new_balances]) db.session.commit() withdrawal = sendAmountTxID # if confirmations >= 1 and confirmation_status == 0: # confirmation_status = 1 # db.session.delete(balances) # db.session.commit() # new_confirmed_balance_btc = unConfirmedBalanceBTC # unConfirmedBalanceBTC = 0.00 # new_balances = Balance(confirmed_balance_btc=new_confirmed_balance_btc, unconfirmed_balance_btc=unConfirmedBalanceBTC , balance_usd=balanceUsd, user_id=user.id) # transfer = Transfer(tx_type='withdrawal', amount=amount, currency='BTC', tx_id=sendAmountTxID,confirmation_status=confirmation_status, user_id=user.id) # db.session.add_all([transfer, new_balances]) # db.session.commit() # withdrawal = sendAmountTxID except ValueError: withdrawal = 'error-address' if withdrawal in ['error-amount', 'error-address']: if type(amount) is not float: withdrawal = 'error-both' return jsonify(result=withdrawal)
def get_deposit(): user = current_user users = User.query.filter(User.username == user.username).first() balances = Balance.query.filter_by(user_id=user.id).first() confirmedBalanceBTC = balances.confirmed_balance_btc unConfirmedBalanceBTC = balances.unconfirmed_balance_btc deposit = 'None' balanceUsd = balances.balance_usd addresses = [users.address] unspentlist = get_from_bitcoind('listunspent', [0, 100, addresses]) #need to clear latest_transfers = Transfer.query.filter_by(user_id=user.id).all() db_txs = [] for transfer in latest_transfers: db_txs.append(transfer.tx_id) for unspent in unspentlist: txid = unspent['txid'] amount = unspent['amount'] confirmations = unspent['confirmations'] status = Transfer.query.filter_by(tx_id=txid).all() print("ststus............", status) if status: confirmation_status = status[-1].confirmation_status if txid not in db_txs: confirmation_status = 0 db.session.delete(balances) db.session.commit() if unConfirmedBalanceBTC > 0: new_unconfirmed_balance_btc = '%.07f' % ( unConfirmedBalanceBTC + amount) else: new_unconfirmed_balance_btc = '%.07f' % (confirmedBalanceBTC + amount) new_balances = Balance( confirmed_balance_btc=confirmedBalanceBTC, unconfirmed_balance_btc=new_unconfirmed_balance_btc, balance_usd=balanceUsd, user_id=user.id) transfer = Transfer(tx_type='deposit', amount=amount, currency='BTC', tx_id=txid, confirmation_status=confirmation_status, user_id=user.id) print("new_balance_btc...........", new_balances) db.session.add_all([transfer, new_balances]) db.session.commit() deposit = txid if confirmations >= 1 and confirmation_status == 0: print("confirmation greater than 6....") confirmation_status = 1 db.session.delete(balances) db.session.commit() print("unConfirmedBalanceBTC..........", unConfirmedBalanceBTC) new_confirmed_balance_btc = unConfirmedBalanceBTC unConfirmedBalanceBTC = 0.00 new_balances = Balance( confirmed_balance_btc=new_confirmed_balance_btc, unconfirmed_balance_btc=unConfirmedBalanceBTC, balance_usd=balanceUsd, user_id=user.id) transfer = Transfer(tx_type='deposit', amount=amount, currency='BTC', tx_id=txid, confirmation_status=confirmation_status, user_id=user.id) db.session.add_all([transfer, new_balances]) db.session.commit() deposit = txid return jsonify(result=deposit)