def save(self, facebook_data): new_user = User.objects.create( username=self.cleaned_data['email'], email=self.cleaned_data['email'] ) new_user.first_name = facebook_data['first_name'] new_user.last_name = facebook_data['last_name'] new_user.save() new_user.set_unusable_password() new_username = int(new_user.id) + 1000000 # set network for the user after registration # todo: make it universal for all universities using email pattern network = Network.objects.get(id=1) profile = UserProfile( user=new_user, username=new_username, network=network ) profile.save() wallet = Wallet(user=new_user) wallet.save() notif_setting = NotificationSettings(user=new_user) notif_setting.save() # send email confirmation EmailConfirmation.objects.send_confirmation(self.cleaned_data['email'], profile) return new_user
def CreateWalletEndpoint(session, data): check_wallet_schema(data) pk = session.public_key invite_code = generate_random_string(48) if Wallet.select().where(Wallet.source == pk).exists(): raise APIError("Shared wallet linked with your key is already exists", 409) level = data['participants'] - data['signers'] device_uid = data.get('device_uid') wallet = Wallet.create( name=data['name'], signers=data['signers'], participants=data['participants'], invite_code=invite_code, level=level, source=pk) MultisigInfo.create( wallet=wallet.id, info=data['multisig_info'], level=0, device_uid=device_uid, source=pk) return jsonify({"invite_code": wallet.invite_code})
def create_wallet(user): name = input("Enter Wallet Name: ") bal = input("Enter Starting Balance: ") Wallet.create(name=name, balance=bal, owner=user, last_transaction=datetime.now())
def add_to_wallet(self, data): """ Encapsulates the saving into the wallet return: wallet saved row """ rec = Wallet(**data) rec.save() self.log.info('Added to wallet: %s', rec) return rec
async def buy(self, ctx: commands.context, code: str, count: int = 1): session_ = sessionmaker(bind=engine.get_engine()) session = session_() if count <= 0: count = 1 cn = session.query(Coin).filter_by(name=code).first() if cn is None: await ctx.reply("등록된 코인이 아닙니다.") else: wl = session.query(Wallet).filter_by(name=code, owner=str( ctx.author.id)).first() if wl is None: wl = Wallet() wl.name = code wl.owner = str(ctx.author.id) wl.count = 0 session.add(wl) wl_point = session.query(Point).filter_by( owner=str(ctx.author.id)).first() if wl_point is None: return await ctx.reply("먼저 포인트 지갑을 만들어야 합니다") if wl_point.point - (cn.price * count) >= 0: wl.count += count wl_point.point -= cn.price * count session.commit() await ctx.reply("구매 성공\n" "```\n" "-----------------------------------\n" f"- 거래한 코인: {count} 개\n" f"- 코인 거래 가격: {cn.price} P\n" f"- 거래 후 보유중인 코인: {wl.count} 개\n" "-----------------------------------\n" f"- 변동 포인트 : -{cn.price * count} P\n" f"- 거래 후 남은 포인트: {wl_point.point} P\n" "-----------------------------------\n" "```") else: await ctx.reply("구매 실패" "```\n" "-----------------------------------\n" f"- 거래한 코인: 0 개\n" f"- 코인 거래 가격: {cn.price} P\n" f"- 거래 후 보유중인 코인: {wl.count} 개\n" "-----------------------------------\n" f"- 변동 포인트 : -0 P\n" f"- 거래 후 남은 포인트: {wl_point.point} P\n" "-----------------------------------\n" "```")
def account(): wallets = Wallet.get_by_idowner(current_user.id) form = WalletForm() if form.validate_on_submit(): name = form.name.data key = form.key.data wallet = Wallet(name=name, owner_id=current_user.id, key = key) wallet.save() return redirect(url_for('account')) return render_template('myaccount.html', wallets=wallets, form=form)
async def f(session_data, *args, **kwargs): """get wallet by session.public_key""" pk = session_data.public_key try: wallet = await objects.get(Wallet.select().where(Wallet.source == pk)) except Wallet.DoesNotExist: try: wallet = await objects.get(Wallet.select().join(MultisigInfo).where(MultisigInfo.source == pk)) except Wallet.DoesNotExist: raise web.HTTPBadRequest(reason="No wallet assigned to your key") return await func(session_data, wallet, *args, **kwargs)
def check_balance(user_or_wallet): w = Wallet.get(user=user_or_wallet) if isinstance(user_or_wallet, Users) \ else user_or_wallet if isinstance(user_or_wallet, Wallet) \ else Wallet.get(address=user_or_wallet) if not w: return r = api.get_balance(w.address) balance = float( MinterConvertor.convert_value(r['result']['balance']['BIP'], 'bip')) w.balance = balance w.updated_dt = datetime.utcnow() w.save() return balance
def do_transfer_money(self, line): """transfer_money from_wallet_id to_wallet_id amount""" from_w_id, to_w_id, amount = line.split() from_w_id, to_w_id = int(from_w_id), int(to_w_id) try: from_w = Wallet.get_obj(from_w_id) to_w = Wallet.get_obj(to_w_id) from_w.transfer(to_w, float(amount)) self.write('Done') self.write_table(Wallet.SHOW_PROPS, [from_w.prop_list, to_w.prop_list]) except WalletError as e: self.write('Error: {0}'.format(str(e)))
def decorator(*args, **kwargs): update = args[0] username = update.effective_user.username uid = update.effective_user.id first_name = update.effective_user.first_name last_name = update.effective_user.last_name user, is_created = Users.get_or_create(telegram_id=uid) user.first_name = first_name user.last_name = last_name user.username = username user.last_active_dt = dt.now() if is_created: user.created_dt = dt.now() if not user.wallets: w = MinterWallet.create() wallet = Wallet.create(user=user, mnemonic=w['mnemonic'], address=w['address'], balance=0) wallet.save() user.save() new_args = list(args) new_args.append(user) logger.info('Entering: %s', func.__name__) for a in new_args: logger.info(a) for k in kwargs: logger.info(k) return func(*new_args, **kwargs)
def create_wallet(wallet: CreateWalletRequestSchema, db: Session = Depends(get_db)): db_wallet = Wallet(balance=wallet.balance) db.add(db_wallet) db.commit() db.refresh(db_wallet) return db_wallet
def create_wallet(self, uuid, created, user_id, is_active=True, balance=current_config.START_BALANCE): """ Регистрация (создание) нового кошелька :param uuid: UUID кошелька :param created: Дата создания :param user_id: Идентификатор пользователя :param is_active: Активность :param balance: Баланс (при регистрации равен START_BALANCE) :return: Результат выполнения функции (Строка) """ try: wallet = Wallet(uuid=uuid, created=created, is_active=is_active, balance=balance) self.session.add(wallet) self.session.flush() self.session.commit() user = self.session.query(Users).filter( Users.id == user_id).first() user.wallet_id = wallet.id self.session.flush() self.session.commit() return 'Поздравляем, регистрации кошелька прошла успешно.' except Exception as e: return f'Ошибка регистрации кошелька: {e}'
def add_transaction(user): wallets = user.wallets for wallet in wallets: print(wallet.id, wallet.name, wallet.balance) ch = int(input("Choose a Wallet ID: ")) wallet = Wallet.get(Wallet.id == ch) is_expense = int(input("Choose Type:\n0. Income\n1.Expense")) if not is_expense: from_person = input("From Who: ") else: from_person = "None" tranx_name = input("Enter Purpose: ") amount = float(input("Enter Amount: ")) comment = input("Any comments? \n") Transaction.create(owner=user, wallet=wallet, name=tranx_name, amount=amount, comment=comment, from_person=from_person, timestamp=datetime.now(), is_expense=bool(is_expense))
async def registerwallet(ctx, address): """ Register your wallet in the DB """ address = address.strip() err_embed = discord.Embed(title=":x:Error:x:", colour=discord.Colour(0xf44242)) good_embed = discord.Embed(title="{}'s Wallet".format( ctx.message.author.name), colour=discord.Colour(0xD4AF37)) if address is None: err_embed.description = "Please provide an address" await client.send_message(ctx.message.author, embed=err_embed) return exists = session.query(Wallet).filter( Wallet.userid == ctx.message.author.id).first() addr_exists = session.query(Wallet).filter( Wallet.address == address).first() if exists: good_embed.title = "Your wallet exists!".format(exists.address) good_embed.description = "```{}``` use `{}updatewallet <addr>` to change".format( exists.address, config['prefix']) await client.send_message(ctx.message.author, embed=good_embed) return if addr_exists: err_embed.description = "Address already registered by another user!" await client.send_message(ctx.message.author, embed=err_embed) return elif not exists and len(address) == config['addrLength']: w = Wallet(address, ctx.message.author.id, ctx.message.id) session.add(w) session.commit() good_embed.title = "Successfully registered your wallet" good_embed.description = "```{}```".format(address) await client.send_message(ctx.message.author, embed=good_embed) pid = gen_paymentid(address) balance = session.query(TipJar).filter(TipJar.paymentid == pid).first() if not balance: t = TipJar(pid, ctx.message.author.id, 0) session.add(t) else: balance.paymentid = pid session.commit() tipjar_addr = rpc.getAddresses()['addresses'][0] good_embed.title = "Your Tipjar Info" good_embed.description = "Deposit {} to start tipping! ```transfer 3 {} <amount> -p {}```".format( config['symbol'], tipjar_addr, pid) balance = session.query(TipJar).filter(TipJar.paymentid == pid).first() await client.send_message(ctx.message.author, embed=good_embed) return elif len(address) > config['addrLength']: err_embed.description = "Your wallet must be {} characeters long, your entry was too long".format( config['addrLength']) elif len(address) < config['addrLength']: err_embed.description = "Your wallet must be {} characeters long, your entry was too short".format( config['addrLength']) await client.say(embed=err_embed)
def BasicWalletInfoEndpoint(): invite_code = request.args.get('invite_code') try: wallet = Wallet.get(invite_code=invite_code) except Wallet.DoesNotExist: raise APIError("Wallet not found", status_code=404) return get_wallet_scheme(wallet)
def get_already_cashed_bonuses(self): """ Get already cashed bonuses return: cashed bonuses list """ filter_by = {'user': self.user, 'transaction_type': 'CASHIN'} return [c.bonus_cashed.id for c in Wallet.objects(**filter_by)]
def craete_utils(): # refereal program rp = ReferralProgram("10-1-1", 10, 1, 1) db.session.add(rp) rp1 = ReferralProgram("15-2-1", 15, 2, 1) db.session.add(rp1) #db.session.commit() rbu = PaymentSystems("Ref bonus", "logo", "url") rbu.unit = "USD" db.session.add(rbu) rbb = PaymentSystems("Ref bonus", "logo", "url") rbb.unit = "BTC" db.session.add(rbb) pm = PaymentSystems("Perfect money", "logo", "url") pm.unit = "USD" db.session.add(pm) bc = PaymentSystems("BitCoint", "logo", "url") bc.unit = "BTC" db.session.add(bc) wallet = Wallet("Perfect Money", "url") wallet.paymentSystem = pm wallet.unit = 'USD' db.session.add(wallet) wallet = Wallet("Bitcoin", "url") wallet.paymentSystem = bc wallet.unit = 'BTC' db.session.add(wallet) ip = InvestmentPlan(0, 1, 3, "3% per day", 1) ip1 = InvestmentPlan(0, 1, 3.5, "3.5% per day") db.session.add(ip) db.session.add(ip1) #db.session.commit() tr = TransactionType("Login") db.session.add(tr) tr = TransactionType("Logout") db.session.add(tr) tr = TransactionType("Request deposit") db.session.add(tr) tr = TransactionType("Re-invest") db.session.add(tr) tr = TransactionType("Withdraw") db.session.add(tr) tr = TransactionType("Reset password") db.session.add(tr) tr = TransactionType("Change settings") db.session.add(tr) #db.session.commit() return rp, wallet
def get_bonus_money(self): """ Gets the total bonus money in the wallet return: bonus money amount """ filter_by = {'user': self.user, 'currency': 'BNS', 'id__nin': self.get_already_cashed_bonuses()} return Wallet.objects(**filter_by).sum('value')
def get_wallets(self): """ Get all wallets on account associated with API_KEY - Requires authentication. @return Array <models.Wallet> """ endpoint = "auth/r/wallets" raw_wallets = self.post(endpoint) return [Wallet(*rw[:4]) for rw in raw_wallets]
def f(session_data, *args, **kwargs): """get wallet by session.public_key""" pk = session_data.public_key wallet = Wallet.select().join(MultisigInfo).where( (Wallet.source == pk) | (Wallet.multisig_source == pk) | (MultisigInfo.source == pk) | (MultisigInfo.multisig_source == pk)).first() if not wallet: raise APIError("No wallet assigned to your key", status_code=400) return func(session_data, wallet, *args, **kwargs)
def CreateWalletEndpointV2(session, data): check_wallet_schema(data) pk = session.public_key invite_code = generate_random_string(48) if Wallet.select().where(Wallet.source == pk).exists(): raise APIError("Shared wallet linked with your key is already exists", 409) level = data['participants'] - data['signers'] wallet = Wallet.create( signers=data['signers'], participants=data['participants'], invite_code=invite_code, supported_protocols=','.join(data['supported_protocols']), level=level, source=pk, ) return jsonify({"invite_code": wallet.invite_code})
def ExistsWalletInfoEndpoint(): pk = request.args.get('public_key') wallet = Wallet.select().join(MultisigInfo).where( (Wallet.source == pk) | (Wallet.multisig_source == pk) | (MultisigInfo.source == pk) | (MultisigInfo.multisig_source == pk)).first() if not wallet: raise APIError("Wallet not found", status_code=404) return get_wallet_scheme(wallet)
def do_draw_money(self, line): """draw_money wallet_id amount""" w_id, amount = line.split() w_id = int(w_id) try: w = Wallet.get_obj(w_id) w.draw(float(amount)) self.write('Done') self.write_table(w.SHOW_PROPS, [w.prop_list]) except WalletError as e: self.write('Error: {0}'.format(str(e)))
async def registerwallet(ctx, address): """ .registerwallet <addr> - Register your wallet in the database """ err_embed = discord.Embed(title="Error", colour=discord.Colour(0xf44242)) good_embed = discord.Embed(title="{}'s Wallet".format( ctx.message.author.name), colour=discord.Colour(0xD4AF37)) if address is None: err_embed.description = "Please provide an address" await client.send_message(ctx.message.author, embed=err_embed) return exists = session.query(Wallet).filter( Wallet.userid == ctx.message.author.id).first() addr_exists = session.query(Wallet).filter( Wallet.address == address).first() if exists: good_embed.title = "Your wallet exists!".format(exists.address) good_embed.description = "```{}``` use `{}updatewallet <addr>` to change".format( exists.address, config['prefix']) await client.send_message(ctx.message.author, embed=good_embed) return if addr_exists: err_embed.description = "Address already registered by another user!" await client.send_message(ctx.message.author, embed=err_embed) return elif not exists and len(address) == 98: w = Wallet(address, ctx.message.author.id, ctx.message.id) session.add(w) session.commit() good_embed.title = "Successfully registered your wallet" good_embed.description = "```{}```".format(address) await client.send_message(ctx.message.author, embed=good_embed) pid = gen_paymentid(address) balance = session.query(TipJar).filter(TipJar.paymentid == pid).first() if not balance: t = TipJar(pid, ctx.message.author.id, 0) session.add(t) else: balance.paymentid = pid session.commit() tipjar_addr = "ccx7Wga6b232eSVfy8KQmBjho5TRXxX8rZ2zoCTyixfvEBQTj1g2Ysz1hZKxQtw874W3w6BZkMFSn5h3gUenQemZ2xiyyjxBR7" good_embed.title = "Your Tipjar Info" good_embed.description = "Deposit {} to start tipping! ```transfer 0 {} <amount> -p {}```".format( config['symbol'], tipjar_addr, pid) balance = session.query(TipJar).filter(TipJar.paymentid == pid).first() await client.send_message(ctx.message.author, embed=good_embed) return elif len(address) > 98: err_embed.description = "Your wallet must be 98 characeters long, your entry was too long" elif len(address) < 98: err_embed.description = "Your wallet must be 98 characeters long, your entry was too short" await client.say(embed=err_embed)
def count_wagered_money(self): """ Sum of the total wagered money since the last cash-in return: wagered money """ # get total wagered money filter_by = {'user': self.user, 'currency': 'EUR', 'transaction_type': 'BET'} bets = Wallet.objects(**filter_by).only('value') bets = sum([abs(b.value) for b in bets]) # get total cashed in bonus requirements filter_by = {'user': self.user, 'transaction_type': 'CASHIN', 'value__gt': 0} cashins = Wallet.objects(**filter_by) cashins = sum([c.bonus.value * c.bonus.wagering_requirement for c in cashins]) return bets - cashins
def create_user(username, password): wallet = Wallet.create_wallet(password) user = User(username=username, wallet=wallet) user.set_password(password) try: user.save() except Exception as e: wallet.delete() raise e return user
def create_wallet(wallet_dto): try: user = session.query(User).filter_by( id=int(wallet_dto['user_id'])).one() except: return HttpResponse("NOT_FOUND", 404) wallets = session.query(Wallet).filter_by( owner_id=int(wallet_dto['user_id'])).all() if len(wallets) >= 1: wallet = Wallet(balance=0, owner_id=wallet_dto['user_id'], is_default=False) else: wallet = Wallet(balance=0, owner_id=wallet_dto['user_id'], is_default=True) session.add(wallet) session.commit() return HttpResponse("SUCCESSFULLY_CREATED_WALLET", 201)
def contract(id): contracts = Contract.get_by_idowner(current_user.id) #traigo todos los contratos del que este usuario es dueño form = ContractForm() if form.validate_on_submit(): title = form.title.data description = form.description.data price = form.price.data wallet = Wallet.get_by_id(current_user.id) contract_address = newContract(title, price, wallet.key) #inicio contrato y creo en la base de datos contract = Contract(owner_id= current_user.id, address = contract_address, title = title, description = description, price = price) contract.save() Contract.onSale_True(contract) return redirect(url_for('contract')) return render_template('contract.html', contracts=contracts, form=form)
def wallet(): try: consumer = KafkaConsumer('wallet', bootstrap_servers=bootstrap_servers, value_deserializer=value_deserializer) except Exception as e: print(str(e)) for message in consumer: print(message.value) ed = Wallet(user_id=message.value['user_id'], balance=message.value['balance']) session.add(ed) session.commit()
def buy(id): contract = Contract.get_by_id(id) #instancio contrato user = User.get_by_id(current_user.id) #instancio comprador if (contract.owner_id == current_user.id): flash('Usted es el dueño de este contrato') return render_template('newContract.html') walletV = Wallet.get_by_idownerunico(contract.owner_id) acctV = w3.eth.account.privateKeyToAccount(walletV.key) #direccion vendedor walletC = Wallet.get_by_idownerunico(current_user.id) acctC = w3.eth.account.privateKeyToAccount(walletC.key) #direccion comprador signed_txn = w3.eth.account.signTransaction(dict( nonce=w3.eth.getTransactionCount(str(acctC.address)), gasPrice=w3.eth.gasPrice, gas=100000, to=str(acctV.address), value=int(contract.price), data=b'', ), str(walletC.key), ) tx_hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction) tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash) hash = w3.toHex(tx_receipt['transactionHash']) Contract.update_idowner(contract, current_user.id) Contract.onSale_False(contract) #contract_instance = w3.eth.contract(address= contract.address, abi = abi) #tx_hash2 = contract_instance.functions.setOwner(acctC.address).transact() #tx_receipt2 = w3.eth.waitForTransactionReceipt(tx_hash2) #hash2 = w3.toHex(tx_receipt2['transactionHash']) flash('Contract adquired') return render_template('newContract.html', hash=hash) #hash2 = hash2
def do_show_wallets(self, line): """show_accounts [wallet_id]""" if line: wallet_id = int(line) try: w = Wallet.get_obj(wallet_id) self.write_table(w.SHOW_PROPS, [w.prop_list]) except WalletError as e: self.write('Error: {0}'.format(str(e))) elif not Wallet.objects: self.columnize([]) else: self.write_table(Wallet.SHOW_PROPS, [ w.prop_list for _, w in sorted(Wallet.objects.iteritems(), key=lambda (k, v): k) ])
class XCPApplication(PyQtGui.QApplication): """ A basic subclass of the QApplication object that provides us with some app-wide state """ def __init__(self, *args, **kwargs): super(XCPApplication, self).__init__(*args, **kwargs) self.wallet = Wallet() self.xcp_client = XCPAsyncAppClient() self.btc_client = BTCAsyncAppClient() self.LAST_BLOCK = None def examine_local_wallet(self, after): def cb(res): self.wallet.update_addresses(res) after() self.btc_client.get_wallet_addresses(cb) def fetch_initial_data(self, update_wallet_callback_func): """ Fetch the initial data and insert it into our model in the correct format. Because we use callbacks, the appearance of this staircase-like method is a bit hideous, but makes the sense if you look at the bottom first. Since all callbacks are posted to the main thread, there are no concerns of races. """ wallet = self.wallet def fetch_data_after_wallet_update(): def process_balances(bals): portfolios = {} assets = set() for entry in bals: asset = entry['asset'] assets.add(asset) address = entry['address'] amount = entry['amount'] if address not in portfolios: portfolios[address] = {} p = portfolios[address] p[asset] = p.get(asset, 0) + amount # don't get_asset_info for XCP, we already know the info and the RCP does not take well with that request if XCP in assets: assets.remove(XCP) asset_name_list = list(assets) def process_asset_info(asset_info_results): asset_info_list = [{'name': asset_name, 'divisible': res['divisible'], 'callable': res['callable'], 'owner': res['owner']} for asset_name, res in zip(asset_name_list, asset_info_results)] # now massage the portfolios dictionary to be the desired format of the wallet method new_portfolios = [] for address in portfolios: p = portfolios[address] assets = list(p.keys()) values = [p[a] for a in assets] new_portfolios.append({'address': address, 'assets': assets, 'values': values}) wallet.update_portfolios(asset_info_list, new_portfolios) update_wallet_callback_func(wallet.addresses) # we need to get a list of all the assets and their results (to see what is divisible and what isn't) # and also to suggest to the user when they type an asset to make an order for def process_issuances(issuances): for i in issuances: name = i['asset'] if name not in wallet.assets: issuer = i['issuer'] divisible = i['divisible'] callable = i['callable'] wallet.assets[name] = Asset(name, divisible, callable, issuer) self.xcp_client.get_issuances(process_issuances) self.xcp_client.get_assets_info(asset_name_list, process_asset_info) self.xcp_client.get_balances(wallet.addresses, process_balances) self.examine_local_wallet(fetch_data_after_wallet_update)
def __init__(self, *args, **kwargs): super(XCPApplication, self).__init__(*args, **kwargs) self.wallet = Wallet() self.xcp_client = XCPAsyncAppClient() self.btc_client = BTCAsyncAppClient() self.LAST_BLOCK = None