Exemplo n.º 1
0
 def get_game_instance(self, user_id=''):
     with MysqlTools().session_scope() as session:
         account_service = AccountService()
         instance_info = session.query(InstantGameInstanceModel). \
             order_by(InstantGameInstanceModel.created_at.desc()).first()
         if instance_info is None:
             self.return_error(40005)
         balance_btc = ''
         balance_eth = ''
         balance_usdt = ''
         balance_eos = ''
         balance_exp = ''
         if user_id != '':
             account_balance = account_service.get_user_token_list(
                 user_id, None, 1, 10)['content'][0]
             balance_btc = account_balance['BTC']
             balance_eth = account_balance['ETH']
             if account_balance.get('EOS', None) is not None:
                 balance_eos = account_balance['EOS']
             else:
                 balance_eos = 0
             balance_usdt = account_balance['USDT']
             balance_exp = account_balance['USDT_EXPERIENCE']
         result = {
             'instance': {
                 'id': instance_info._id,
                 'game_serial': instance_info.game_serial,
                 'game_title': instance_info.game_title,
                 'game_describe': instance_info.game_describe,
                 'need': instance_info.need,
                 'status': instance_info.status,
                 'bet_token': self.get_coin_name(instance_info.bet_token),
                 'max_bet_ratio': instance_info.max_bet_ratio
             },
             'current_price': {
                 'from': get_exchange_rate(int(_COIN_ID_BTC))['from'],
                 'eth': get_exchange_rate(int(_COIN_ID_ETH))['price'],
                 'btc': get_exchange_rate(int(_COIN_ID_BTC))['price'],
                 'eos': get_exchange_rate(int(_COIN_ID_EOS))['price']
             },
             'balance': {
                 'btc': decimal_to_str(balance_btc, 8),
                 'eth': decimal_to_str(balance_eth, 8),
                 'eos': decimal_to_str(balance_eos, 8),
                 'usdt': decimal_to_str(balance_usdt, 4),
                 'exp': decimal_to_str(balance_exp, 4),
             }
         }
         return result
 def automatic_release(self, session, template_id):
     # now = int(time.time())
     # time_struct = time.localtime(now)
     # str_time = time.strftime("%Y-%m-%d %H:%M:%S", time_struct)
     template_id = 1
     str_time = get_utc_now()
     with MysqlTools().session_scope() as session:
         template_info = session.query(InstantGameTemplateModel). \
             filter(InstantGameTemplateModel._id == template_id).first()
         # 判断存在在"启用"状态 且 自动发布的模板
         if template_info.template_status == 1 and template_info.auto_release == 1:
             # 查询btc 与 usdt 转换比
             btc_usdt_rate = get_exchange_rate(
                 template_info.reward_token)['price']
             if btc_usdt_rate > template_info.need_ceiling or btc_usdt_rate < template_info.need_floor:
                 raise_logger("automatic_release out of rate", 'rs',
                              'error')
                 return {"status": False}
             need = btc_usdt_rate * template_info.reward_quantity
             game_serial = generate_phase(str(template_info.phase_prefix))
             digital_instance_model = InstantGameInstanceModel(
                 template_id=template_id,
                 game_serial=game_serial,
                 game_title=template_info.game_title,
                 bet_token=template_info.bet_token,
                 bet_unit=template_info.bet_unit,
                 support_token=template_info.support_token,
                 reward_token=template_info.reward_token,
                 reward_quantity=template_info.reward_quantity,
                 handling_fee=template_info.handling_fee,
                 game_describe=template_info.game_describe,
                 experience=template_info.experience,
                 merge_threshold=template_info.merge_threshold,
                 max_bet_ratio=template_info.max_bet_ratio,
                 release_time=str_time,
                 need=int(need),
                 status=-1,
                 release_type=1,
                 chain_status=0)
             session.add(digital_instance_model)
             # session.flush()
             session.commit()
         return {"status": True}
Exemplo n.º 3
0
def automatic_release_instance():
    now = int(time.time())
    time_struct = time.localtime(now)
    str_time = time.strftime("%Y-%m-%d %H:%M:%S", time_struct)

    # current_date = datetime.datetime.utcnow()
    db = pymysql.connect("rm-2zes47ke8wo3utd54.mysql.rds.aliyuncs.com",
                         "H34pHJ2jdtGC", "BF1xE960ivNd", "tokenpark")
    cursor = db.cursor(cursor=pymysql.cursors.DictCursor)
    # cursor = db.cursor()
    template_sql = "SELECT * FROM TokenPark.game_digital_template WHERE template_status = 1 AND auto_release = 1"
    try:
        cursor.execute(template_sql)
        template_result = cursor.fetchall()
        if len(template_result) > 0:
            for row in template_result:
                btc_usdt_rate = get_exchange_rate(row['reward_token'])['price']
                ceiling = row['need_ceiling']
                floor = row['need_floor']
                if btc_usdt_rate > ceiling or btc_usdt_rate < floor:
                    # TODO 发警告邮件
                    send_mail('未实例化成功')
                else:
                    template_id = row['_id']
                    instance_sql = "SELECT * FROM TokenPark.game_digital_instance \
                      WHERE game_digital_instance.status = 0 AND \
                      game_digital_instance.template_id = %d" % template_id
                    cursor.execute(instance_sql)
                    instance_result = cursor.fetchall()
                    if len(instance_result) <= 0:
                        reward_quantity = row['reward_quantity']
                        exceeded_ratio = row['exceeded_ratio']
                        # game_serial = row['game_serial']
                        game_title = row['game_title']
                        bet_token = row['bet_token']
                        bet_unit = row['bet_unit']
                        reward_token = row['reward_token']
                        handling_fee = row['handling_fee']
                        game_describe = row['game_describe']
                        # status = row['status']
                        # release_type = row['release_type']
                        phase_prefix = row['phase_prefix']
                        need = btc_usdt_rate * reward_quantity * (
                            (100 + exceeded_ratio) / 100)
                        game_serial = generate_phase(str(phase_prefix))
                        create_all_bet_number(game_serial, int(need))
                        release_sql = "INSERT INTO game_digital_instance(template_id,game_serial,game_title,bet_token\
                            ,bet_unit,reward_token,reward_quantity, release_time,need,status,release_type, handling_fee,\
                            game_describe) \
                            VALUES('%d','%s','%s','%d','%d','%d','%d','%s','%d','%d','%d','%d','%s')"                                                                                                      % \
                                      (template_id, game_serial, game_title, bet_token, bet_unit,
                                       reward_token, reward_quantity, str_time, int(need), 0, 1, handling_fee
                                       , game_describe)
                        cursor.execute(release_sql)
        db.commit()
    except:
        print("Error: unable to fetch data")
        db.rollback()

    # 关闭数据库连接
    db.close()
Exemplo n.º 4
0
    def bet_in(self, dic):
        id = dic.get("game_instance_id", "")  # 项目id
        user_id = dic.get("user_id", "")  # 用户id
        user_channel_id = dic.get("user_channel_id", "")  # 用户下注渠道id
        conin_id = dic.get("conin_id", "")  # 投入币种id
        bet_amount = dic.get("bet_amount", "")  # 投注数量
        merge_id = dic.get("merge_id", -1)  # 合并投注id
        # transaction_password = dic.get("transaction_password", "")  # 交易密码

        with MysqlTools().session_scope() as session:
            # 查询项目
            model = session.query(GameDigitalInstanceModel).filter(
                GameDigitalInstanceModel._id == id).with_for_update().first()
            if model is None:
                return self.return_error(60001)
            if model.status == 1:
                return self.return_error(60002)
            if model.status == 2:
                return self.return_error(60003)
            if model.status == 0:
                can_bet = model.need - model.bet_number
                if can_bet <= 0:
                    return self.return_error(60002)
                if int(bet_amount) > can_bet:
                    return self.return_error(60004)

            if model.support_token >= 0 and int(
                    conin_id) != model.support_token and int(conin_id) != int(
                        _COIN_ID_EXP):
                return self.return_error(60008)

            # 查询币价 币种实际需要金额
            exchange_rate = get_exchange_rate(int(conin_id))

            # (投注数量 * 投注单位) / 投注币种兑换usdt比例
            bet_money = (int(bet_amount) *
                         model.bet_unit) / exchange_rate['price']

            # 体验金相关逻辑
            if int(conin_id) == int(_COIN_ID_EXP):
                # 检查本次投注体验金使用数量 (允许范围: 1~10)
                if int(bet_amount) < 1 or int(bet_amount) > 10:
                    self.return_error(60015)
                # 体验金使用额度
                exp = int(model.experience / 100 * model.need)
                # 检查项目体验金占比剩余额度以及个人当天最大体验金使用额度(每天最多用10个)
                limit = self.check_instance_exp_limit(session, user_id, id)
                instance_limit = limit['instance_limit']
                user_limit = limit['user_limit']
                if user_limit > 10 - int(bet_amount):
                    self.return_error(60017)
                if instance_limit >= exp:
                    self.return_error(60016)

            # 查询用户资产
            account_service = AccountService()
            user_info = account_service.get_inner_user_account_by_token(
                session, user_id, conin_id)
            if isinstance(user_info, int):
                if user_info == 20001:
                    return self.return_error(20001)

            balance = get_decimal(user_info.get("balance"),
                                  digits=8,
                                  decimal_type="down")

            # 账户余额 < 需要下注金额
            if balance < bet_money:
                return self.return_error(60005)

            # 验证交易密码
            # if account_service.check_pay_password(user_id, transaction_password) is False:
            #     return self.return_error(35024)
            # raise_logger("begin", "game_bet_in", "info")
            # 获取下注编号
            game_numbers = session.query(GameNumbersSetModel).filter(
                GameNumbersSetModel.game_serial ==
                model.game_serial).with_for_update().all()
            numbers = []
            for num in game_numbers:
                numbers.append(num.number)
            numbers = random.sample(numbers, int(bet_amount))
            # raise_logger("get game_numbers", "game_bet_in", "info")
            if isinstance(numbers, list):
                nick_name = account_service.get_inner_user_account_info(
                    session, user_id).get("nick_name")
                try:
                    # 添加参与记录
                    participate_in_model = ParticipateInModel(
                        game_instance_id=model._id,
                        template_id=model.template_id,
                        game_serial=model.game_serial,
                        game_title=model.game_title,
                        release_type=model.release_type,
                        bet_token=model.bet_token,
                        bet_unit=model.bet_unit,
                        user_id=user_id,
                        nick_name=nick_name,
                        channel=user_channel_id,
                        bet_number=int(bet_amount),
                        pay_token=int(conin_id),
                        pay_number=get_decimal(bet_money,
                                               digits=8,
                                               decimal_type="down"),
                        award_numbers=json.dumps(numbers),
                        user_type=0,
                        merge_id=merge_id)
                    session.add(participate_in_model)
                    session.flush()
                    # raise_logger("add participate_in_model", "game_bet_in", "info")
                    # 提交扣款申请
                    result = account_service.do_bet(
                        session, user_id, conin_id,
                        get_decimal(bet_money, digits=8, decimal_type="down"),
                        str(participate_in_model._id), int(bet_amount),
                        model.game_serial, user_channel_id)
                    # raise_logger("do_bet success", "game_bet_in", "info")
                    if isinstance(result, int):
                        if result == 0:
                            # 修改项目状态
                            game_service = GameService()
                            # raise_logger("modifyDigitalInstance begin", "game_bet_in", "info")
                            if game_service.modifyDigitalInstance(
                                    model, {
                                        "game_id": id,
                                        "add_bet_number": int(bet_amount),
                                        "full_load_time":
                                        participate_in_model.created_at,
                                        "add_people": 1
                                    }) is False:
                                session.rollback()
                                raise_logger("modifyDigitalInstance err",
                                             "game_bet_in", "info")
                                return self.return_error(80005)
                            # raise_logger("modifyDigitalInstance succ", "game_bet_in", "info")
                            try:
                                created_at_str = str(
                                    participate_in_model.created_at)
                                update_at_str = str(
                                    participate_in_model.update_at)
                                deleted_at_str = str(
                                    participate_in_model.deleted_at)
                                deleted_str = str(participate_in_model.deleted)
                                if BlockChainInfoService(
                                ).insert_block_chain_info(
                                        user_id,
                                        participate_in_model.game_instance_id,
                                        1,
                                    {
                                        "id":
                                        participate_in_model._id,
                                        "created_at":
                                        created_at_str[0:19],
                                        "update_at":
                                        update_at_str[0:19],
                                        "deleted_at":
                                        deleted_at_str[0:19],
                                        "deleted":
                                        deleted_str[0:19],
                                        "game_instance_id":
                                        str(participate_in_model.
                                            game_instance_id),
                                        "template_id":
                                        participate_in_model.template_id,
                                        "game_serial":
                                        participate_in_model.game_serial,
                                        "bet_token":
                                        participate_in_model.bet_token,
                                        "user_id":
                                        participate_in_model.user_id,
                                        "nick_name":
                                        participate_in_model.nick_name,
                                        "channel":
                                        participate_in_model.channel,
                                        "pay_token":
                                        participate_in_model.pay_token,
                                        "bet_number":
                                        participate_in_model.bet_number,
                                        "pay_number":
                                        str(participate_in_model.pay_number),
                                        "award_numbers":
                                        participate_in_model.award_numbers,
                                        "user_type":
                                        participate_in_model.user_type,
                                    }):
                                    participate_in_model.chain_status = 1
                                    # raise_logger("insert_block succ", "game_bet_in", "info")
                                else:
                                    raise_logger("insert_block err",
                                                 "game_bet_in", "info")
                            except Exception as e:
                                session.rollback()
                                raise_logger(e, "game_bet_in", "info")
                            # raise_logger("pri del GameNumbersSetModel", "game_bet_in", "info")
                            for i in numbers:
                                # raise_logger("pri del GameNumbersSetModel", "game_bet_in", "info")
                                # game_number_filters = {"game_serial": model.game_serial, "number": i}
                                session.query(GameNumbersSetModel). \
                                    filter(GameNumbersSetModel.game_serial == model.game_serial,
                                           GameNumbersSetModel.number == i).delete()
                                # number_filter.time_stamp = 1
                                # session.delete(num_filters)
                            # raise_logger("GameNumbersSetModel delete succ", "game_bet_in", "info")

                            # # 检测游戏是否售罄需要申请开奖
                            # instance = session.query(GameDigitalInstanceModel).filter(
                            #     GameDigitalInstanceModel._id == id).first()
                            if int(model.status) == 1:
                                add_result = WalletEosService().lottery_adduce(
                                    id, get_timestamp(model.full_load_time))
                                if not add_result:
                                    raise_logger("lottery_adduce fail",
                                                 "game_bet_in", "info")

                            session.commit()
                            # raise_logger("commit succ", "game_bet_in", "info")
                            try:
                                # # 提交验证是否需要上线新项目
                                game_service.automatic_release(
                                    session, model.template_id)
                            except Exception as e:
                                raise_logger(e, "game_bet_in", "info")

                            can_merge = False
                            if int(
                                    bet_amount
                            ) >= model.merge_threshold and merge_id == -1:
                                can_merge = True
                            # raise_logger("pri return", "game_bet_in", "info")
                            return {
                                'numbers': numbers,
                                'can_merge': can_merge,
                                'part_in_id': participate_in_model._id
                            }

                        else:
                            session.rollback()
                            return self.return_error(60009)
                    else:
                        session.rollback()
                        return self.return_error(60010)

                except Exception as e:
                    raise_logger(e, "game_bet_in", "info")
                    session.rollback()
                    return self.return_error(60011)

                if isinstance(numbers, int):
                    session.rollback()
                    return self.return_error(60012)

            else:
                session.rollback()
                return self.return_error(60007)
Exemplo n.º 5
0
    def robot_bet_in(self, dic):
        id = dic.get("game_instance_id", "")  # 项目id
        user_id = dic.get("user_id", "")  # 用户id
        conin_id = dic.get("conin_id", 0)  # 投入币种id
        bet_amount = dic.get("bet_amount", 0)  # 投注数量
        time_stamp = dic.get("time_stamp", 0)  # 纪录时间戳

        with MysqlTools().session_scope() as session:
            # 查询项目
            model = session.query(GameDigitalInstanceModel).filter(
                GameDigitalInstanceModel._id == id).with_for_update().first()
            if model is None:
                raise_logger("机器人下注失败60001", "game_bet_in", "info")
                return 60001
            if model.status == 1:
                raise_logger("机器人下注失败60002", "game_bet_in", "info")
                return 60002
            if model.status == 2:
                raise_logger("机器人下注失败60003", "game_bet_in", "info")
                return 60003
            if model.status == 0:
                can_bet = model.need - model.bet_number
                if can_bet <= 0:
                    raise_logger("机器人下注失败60002", "game_bet_in", "info")
                    return 60005
                if int(bet_amount) > can_bet:
                    raise_logger("机器人下注失败60004", "game_bet_in", "info")
                    return 60004

            # 查询币价 币种实际需要金额
            exchange_rate = get_exchange_rate(int(conin_id))
            # (投注数量 * 投注单位) / 投注币种兑换usdt比例
            bet_money = (int(bet_amount) *
                         model.bet_unit) / exchange_rate['price']

            game_numbers = session.query(GameNumbersSetModel).filter(
                GameNumbersSetModel.game_serial ==
                model.game_serial).with_for_update().all()
            numbers = []
            for num in game_numbers:
                numbers.append(num.number)

            try:
                numbers = random.sample(numbers, int(bet_amount))
            except Exception as e:
                raise_logger("机器人下注失败 没有numbers", "game_bet_in", "info")
                return False
            if isinstance(numbers, list) and len(numbers) > 0:
                # try:
                # 修改机器人账户状态
                user = session.query(RobotAccountModel).filter(
                    RobotAccountModel.user_id ==
                    user_id).with_for_update().first()
                if user is None:
                    raise_logger("机器人下注失败70002", "game_bet_in", "info")
                    return 70002
                user.status = 0

                # 添加投注纪录
                participate_in_model = ParticipateInModel(
                    game_instance_id=model._id,
                    template_id=model.template_id,
                    game_serial=model.game_serial,
                    game_title=model.game_title,
                    release_type=model.release_type,
                    bet_unit=model.bet_unit,
                    bet_token=model.bet_token,
                    user_id=user_id,
                    nick_name=user.nick_name,
                    channel="0",
                    bet_number=int(bet_amount),
                    pay_token=int(conin_id),
                    pay_number=get_decimal(bet_money),
                    award_numbers=json.dumps(numbers),
                    user_type=1)
                session.add(participate_in_model)

                # 修改项目信息
                game_service = GameService()
                if game_service.modifyDigitalInstance(
                        model, {
                            "game_id": id,
                            "add_bet_number": int(bet_amount),
                            "full_load_time": participate_in_model.created_at,
                            "add_people": 1
                        }) is False:
                    session.rollback()
                    raise_logger("机器人下注失败80005", "game_bet_in", "info")
                    return 80005

                # 修改机器人配置纪录 下注状态
                record = session.query(RobotConfigRecordModel).filter(
                    RobotConfigRecordModel.game_instance_id == id,
                    RobotConfigRecordModel.user_id == user_id,
                    RobotConfigRecordModel.time_stamp ==
                    time_stamp).with_for_update().first()
                if record is None:
                    raise_logger("机器人下注失败70002", "game_bet_in", "info")
                    return 70002
                record.bet_status = 1

                # 查看本期 机器人是否都已下注完成
                is_finish = True
                robots = session.query(RobotConfigRecordModel).filter(
                    RobotConfigRecordModel.game_instance_id == id,
                    RobotConfigRecordModel.time_stamp == time_stamp).all()
                for r in robots:
                    if r.bet_status == 0 or r.bet_status == 2:
                        is_finish = False
                        break

                if is_finish:
                    # 修改 游戏机器人配置纪录
                    q = session.query(RobotGameConfigRecordModel).filter(
                        RobotGameConfigRecordModel.game_instance_id == id,
                        RobotGameConfigRecordModel.time_stamp ==
                        time_stamp).with_for_update().first()

                    if q is None:
                        raise_logger("机器人下注失败70003", "game_bet_in", "info")
                        return 70003

                    q.status = 2
                    q.end_of_real_time = datetime.datetime.utcnow().strftime(
                        '%Y-%m-%d %H:%M:%S')

                session.flush()

                try:
                    created_at_str = str(participate_in_model.created_at)
                    update_at_str = str(participate_in_model.update_at)
                    deleted_at_str = str(participate_in_model.deleted_at)
                    deleted_str = str(participate_in_model.deleted)
                    dic = {
                        "id": participate_in_model._id,
                        "created_at": created_at_str[0:19],
                        "update_at": update_at_str[0:19],
                        "deleted_at": deleted_at_str[0:19],
                        "deleted": deleted_str[0:19],
                        "game_instance_id":
                        participate_in_model.game_instance_id,
                        "template_id": participate_in_model.template_id,
                        "game_serial": participate_in_model.game_serial,
                        "bet_token": participate_in_model.bet_token,
                        "user_id": participate_in_model.user_id,
                        "nick_name": participate_in_model.nick_name,
                        "channel": participate_in_model.channel,
                        "pay_token": participate_in_model.pay_token,
                        "bet_number": participate_in_model.bet_number,
                        "pay_number": str(participate_in_model.pay_number),
                        "award_numbers": participate_in_model.award_numbers,
                        "user_type": participate_in_model.user_type,
                    }

                    if BlockChainInfoService().insert_block_chain_info(
                            user_id, participate_in_model.game_instance_id, 1,
                            dic):
                        participate_in_model.chain_status = 1

                except Exception as e:
                    session.rollback()
                    raise_logger("insert_block_chain_info", "game_bet_in",
                                 "info")

                g_service = model.game_serial
                for i in numbers:
                    session.query(GameNumbersSetModel).filter(
                        GameNumbersSetModel.game_serial == g_service,
                        GameNumbersSetModel.number == i).delete()
                # # 检测游戏是否售罄需要申请开奖
                if int(model.status) == 1:
                    add_result = WalletEosService().lottery_adduce(
                        id, get_timestamp(model.full_load_time))
                    if not add_result:
                        raise_logger("lottery_adduce fail", "game_bet_in",
                                     "info")

                session.commit()

                try:
                    # # 提交验证是否需要上线新项目
                    game_service.automatic_release(session, model.template_id)
                except Exception as e:
                    raise_logger("automatic_release", "game_bet_in", "info")

                return True

            # except Exception as e:
            #     session.rollback()
            #     raise_logger("机器人下注失败60006", "game_bet_in", "info")
            #     return 60006

            return False
Exemplo n.º 6
0
 def post(self):
     request_data = self.get_argument_dict(must_keys=['conin_id'])
     return get_exchange_rate(request_data['conin_id'])
Exemplo n.º 7
0
    def automatic_release_instance(self):
        # now = int(time.time())
        # time_struct = time.localtime(now)
        # str_time = time.strftime("%Y-%m-%d %H:%M:%S", time_struct)
        str_time = get_utc_now()

        with MysqlTools().session_scope() as session:
            template_result = session.query(GameDigitalTemplateModel). \
                filter(GameDigitalTemplateModel.template_status == 1,
                       GameDigitalTemplateModel.auto_release == 1).all()
            if len(template_result) > 0:
                for row in template_result:
                    btc_usdt_rate = get_exchange_rate(
                        row.reward_token)['price']
                    ceiling = row.need_ceiling
                    floor = row.need_floor
                    email_config = get_sms_email('common')
                    if email_config == {}:
                        self.return_error(35034)
                    send_email_config = get_sms_email("send_email_config")
                    subject = email_config['email_subject']
                    if btc_usdt_rate > ceiling or btc_usdt_rate < floor:
                        self.slog.info("instantiation fail. rate is ",
                                       str(btc_usdt_rate))
                        self.slog.info("game template id is ", str(row._id))
                        # 警告邮件
                        send_mail(
                            "game自动实例化失败, GAME模板id:" + str(row._id) +
                            ",奖励币种价格:" + str(btc_usdt_rate),
                            send_email_config['user'],
                            send_email_config['pwd'], email_config['email'],
                            subject, send_email_config['smtp_server'],
                            send_email_config['smtp_port'])
                    else:
                        template_id = row._id
                        instance_list = session.query(GameDigitalInstanceModel). \
                            filter(GameDigitalInstanceModel.status == 0,
                                   GameDigitalInstanceModel.template_id == template_id).all()
                        if len(instance_list) <= 0:
                            phase_prefix = row.phase_prefix
                            need = btc_usdt_rate * row.reward_quantity * (
                                (100 + row.exceeded_ratio) / 100)
                            game_serial = generate_phase(str(phase_prefix))
                            digital_instance_model = GameDigitalInstanceModel(
                                template_id=template_id,
                                game_serial=game_serial,
                                game_title=row.game_title,
                                bet_token=row.bet_token,
                                bet_unit=row.bet_unit,
                                support_token=row.support_token,
                                reward_token=row.reward_token,
                                reward_quantity=row.reward_quantity,
                                handling_fee=row.handling_fee,
                                game_describe=row.game_describe,
                                experience=row.experience,
                                merge_threshold=row.merge_threshold,
                                release_time=str_time,
                                need=int(need),
                                status=0,
                                release_type=1,
                                chain_status=0)
                            # if create_all_bet_number(game_serial, int(need)) != 2000:
                            #     self.slog.info("create all bet number fail")
                            if not GameNumberSetService().createNumbers(
                                {
                                    "game_serial": game_serial,
                                    "total": int(need)
                                }):
                                self.slog.info("create all bet number fail")
                                self.return_error(40015)
                            session.add(digital_instance_model)
                            session.flush()
                            try:
                                # 发布信息上链
                                if BlockChainInfoService(
                                ).insert_block_chain_info(
                                        '', str(digital_instance_model._id), 2,
                                    {
                                        "instance_id":
                                        digital_instance_model._id,
                                        "template_id":
                                        template_id,
                                        "game_serial":
                                        game_serial,
                                        "support_token":
                                        row.support_token,
                                        "bet_token":
                                        row.bet_token,
                                        "bet_unit":
                                        row.bet_unit,
                                        "reward_token":
                                        row.reward_token,
                                        "reward_quantity":
                                        row.reward_quantity,
                                        "handling_fee":
                                        str(row.handling_fee),
                                        "game_describe":
                                        row.game_describe,
                                        "release_time":
                                        str_time.strftime("%Y-%m-%d %H:%M:%S"),
                                        "status":
                                        0,
                                        "need":
                                        int(need),
                                        "release_type":
                                        0,
                                    }):
                                    digital_instance_model.chain_status = 1
                                    self.slog.info(
                                        "insert_block_chain_info success")
                                else:
                                    self.slog.info(
                                        "insert_block_chain_info fail")
                            except Exception as e:
                                self.slog.info("insert_block_chain_info fail")
                                self.slog.info(f"Exception: {e}")
                                # self.slog.info("automatic_release_instance fail")
                                # session.rollback()
                            session.commit()
                            # send_mail("game自动实例化成功, GAME模板id:" + str(template_id) + ",奖励币种价格:" + str(btc_usdt_rate),
                            #           send_email_config['user'], send_email_config['pwd'],
                            #           email_config['email'],
                            #           subject, send_email_config['smtp_server'], send_email_config['smtp_port'])
                            self.slog.info(
                                "automatic_release_instance success")
Exemplo n.º 8
0
    def bet_in(self, dic):
        change_type_41 = '41'  # 即时开中奖
        change_type_42 = '42'  # 即时开投注
        id = dic.get("game_instance_id", "")  # 项目id
        user_id = dic.get("user_id", "")  # 用户id
        user_channel_id = dic.get("user_channel_id", "")  # 用户下注渠道id
        conin_id = dic.get("coin_id", "")  # 投入币种id
        bet_amount = dic.get("bet_amount", "")  # 投注数量
        bet_start = dic.get("bet_start", 0)
        bet_end = dic.get("bet_end", 0)
        faker = True
        # merge_id = dic.get("merge_id", -1)  # 合并投注id
        # transaction_password = dic.get("transaction_password", "")  # 交易密码
        with MysqlTools().session_scope() as session:
            # 查询项目
            model = session.query(InstantGameInstanceModel).filter(
                InstantGameInstanceModel._id == id).first()
            template = session.query(InstantGameTemplateModel). \
                order_by(InstantGameTemplateModel._id.desc()).first()
            if model is None:
                return self.return_error(60001)
            if model.status == 1:
                return self.return_error(60002)
            if model.status == 2:
                return self.return_error(60003)
            if model.status == 0:
                can_bet = model.need - model.bet_number
                if can_bet <= 0:
                    return self.return_error(60002)
                if int(bet_amount) > can_bet:
                    return self.return_error(60004)

            if model.support_token >= 0 and int(
                    conin_id) != model.support_token and int(conin_id) != int(
                        _COIN_ID_EXP):
                return self.return_error(60008)

            if int(bet_amount) > model.need * (model.max_bet_ratio / 100):
                return self.return_error(40025)

            # 查询币价 币种实际需要金额
            exchange_rate = get_exchange_rate(int(conin_id))

            # (投注数量 * 投注单位) / 投注币种兑换usdt比例
            bet_money = (int(bet_amount) *
                         model.bet_unit) / exchange_rate['price']

            # 体验金相关逻辑
            if int(conin_id) == int(_COIN_ID_EXP):
                # 检查本次投注体验金使用数量 (允许范围: 1~10)
                if int(bet_amount) < 1 or int(bet_amount) > 10:
                    self.return_error(60015)
                # 体验金使用额度
                exp = int(model.experience / 100 * model.need)
                # 检查项目体验金占比剩余额度以及个人当天最大体验金使用额度(每天最多用10个)
                limit = self.check_instance_exp_limit(session, user_id,
                                                      model.game_serial)
                # instance_limit = limit['instance_limit']
                user_limit = limit['user_limit']
                total_pay_number = limit['total_pay_number']
                if user_limit > 10 - int(bet_amount):
                    self.return_error(60017)
                # if instance_limit >= exp:
                #     self.return_error(60016)
                if total_pay_number >= int(
                        model.need) * model.reward_quantity * (
                            (100 + template.exceeded_ratio) / 100):
                    model.full_load_time = datetime.datetime.utcnow()
                    faker = False
            else:
                limit = self.check_instance_exp_limit(session, user_id,
                                                      model.game_serial)
                total_pay_number = limit['total_pay_number']
                raise_logger("总下注金额" + "USDT:" + str(total_pay_number),
                             "game_publish_lottery", "info")
                if total_pay_number >= int(
                        model.need) * model.reward_quantity * (
                            (100 + template.exceeded_ratio) / 100):
                    model.full_load_time = datetime.datetime.utcnow()
                    faker = False

            # 查询用户资产
            account_service = AccountService()
            user_info = account_service.get_inner_user_account_by_token(
                session, user_id, conin_id)
            if isinstance(user_info, int):
                if user_info == 20001:
                    return self.return_error(20001)

            balance = get_decimal(user_info.get("balance"),
                                  digits=8,
                                  decimal_type="down")

            # 账户余额 < 需要下注金额
            if balance < bet_money:
                return self.return_error(60005)

            # 获取下注编号
            numbers = []
            user_lottery_num_list = []
            i = int(bet_amount)
            # start_num = random.randint(1, model.need 0- int(bet_amount))
            bet_start = int(bet_start)
            bet_end = int(bet_end)
            user_lottery_num_list.append(bet_start)
            user_lottery_num_list.append(bet_end)
            while i > 0:
                numbers.append(bet_start)
                bet_start += 1
                i -= 1
            if isinstance(numbers, list):
                nick_name = account_service.get_inner_user_account_info(
                    session, user_id).get("nick_name")
                # 添加参与记录
                participate_in_model = ParticipateInModel(
                    game_instance_id=0,
                    template_id=model.template_id,
                    game_serial=model.game_serial,
                    game_title=model.game_title,
                    release_type=model.release_type,
                    bet_token=model.bet_token,
                    bet_unit=model.bet_unit,
                    user_id=user_id,
                    nick_name=nick_name,
                    channel=user_channel_id,
                    bet_number=int(bet_amount),
                    pay_token=int(conin_id),
                    pay_number=get_decimal(bet_money,
                                           digits=8,
                                           decimal_type="down"),
                    award_numbers=json.dumps(numbers),
                    user_type=0,
                    merge_id=-1)
                session.add(participate_in_model)
                session.flush()
                # raise_logger("add participate_in_model", "game_bet_in", "info")
                # 提交扣款申请
                result = account_service.do_bet(
                    session, user_id, conin_id,
                    get_decimal(bet_money, digits=8, decimal_type="down"),
                    str(participate_in_model._id), int(bet_amount),
                    model.game_serial, user_channel_id, change_type_42)
                # raise_logger("do_bet success", "game_bet_in", "info")
                if isinstance(result, int):
                    if result == 0:
                        instant_game_service = InstantGameModelService()
                        # print('user_lottery_num_list-=-=', user_lottery_num_list)
                        # print('model.need-=-=', model.need)
                        # print('faker-=-=', faker)
                        lottery_result = WalletEosService().\
                            lottery_instant_adduce(get_timestamp(), user_lottery_num_list, model.need, faker)
                        # print('lottery_result-=-=', lottery_result)
                        if not any(lottery_result):
                            raise_logger("lottery_result empty", "game_bet_in",
                                         "info")
                            session.rollback()
                            return self.return_error(40026)
                        # 开奖
                        hash_numbers = lottery_result['block_hash']
                        raise_logger(
                            "项目:" + str(id) + "   中奖区块号:" + str(hash_numbers),
                            "game_publish_lottery", "info")
                        if hash_numbers == "":
                            raise_logger("开奖异常:80001", "game_publish_lottery",
                                         "info")
                            return False
                        # prize_number = int(hash_numbers, 16) % model.need + 1
                        prize_number = lottery_result['lottery_num']
                        raise_logger(
                            "项目:" + str(id) + "    中奖号码:" + str(prize_number),
                            "game_publish_lottery", "info")
                        participate_in_model.win_number = prize_number
                        participate_in_model.block_no = lottery_result[
                            'block_num']
                        participate_in_model.bet_hash = hash_numbers
                        participate_in_model.received_time = lottery_result[
                            'timestamp']
                        # 中奖
                        is_win = False
                        if prize_number in numbers:
                            is_win = True
                            participate_in_model.result = 1
                            model.lottery_time = datetime.datetime.utcnow()
                            instant_game_service.automatic_release(
                                session, model.template_id)
                            do_win = account_service.do_win(
                                session, user_id, model.reward_token,
                                model.reward_quantity,
                                str(participate_in_model._id), int(bet_amount),
                                model.game_serial, change_type_41)
                            if isinstance(do_win, int) is False:
                                raise_logger("分钱失败" + "user:"******"game_publish_lottery", "info")
                                session.rollback()
                                return False
                            if do_win != 0:
                                raise_logger("分钱失败" + "user:"******"game_publish_lottery", "info")
                                session.rollback()
                                return False

                        session.commit()

                        return {
                            'is_win': is_win,
                            'prize_number': prize_number,
                            'part_in_id': participate_in_model._id
                        }
                    else:
                        session.rollback()
                        return self.return_error(60009)
                else:
                    session.rollback()
                    return self.return_error(60010)
            else:
                session.rollback()
                return self.return_error(60007)