Esempio n. 1
0
def run_bots_for_tx(tx, debug=False):
    if tx is not None:
        # Run bots
        if tx.contract_method in [
                'init', 'shake', 'initTestDrive', 'shakeTestDrive'
        ] and tx.offchain is not None:
            offchain = tx.offchain.replace(CONST.CRYPTOSIGN_OFFCHAIN_PREFIX,
                                           '')
            if 'm' in offchain:
                offchain = offchain.replace('m', '')
                h = Handshake.find_handshake_by_id(offchain)
                if h is not None:
                    if debug:
                        return h.outcome_id
                    else:
                        run_bots.delay(h.outcome_id)

            elif 's' in offchain:
                offchain = offchain.replace('s', '')
                s = Shaker.find_shaker_by_id(offchain)
                if s is not None:
                    if debug:
                        return s.handshake.outcome_id
                    else:
                        run_bots.delay(s.handshake.outcome_id)
    return None
	def test_save_collect_state_for_shaker(self):
		self.clear_data_before_test()
		# -----
		handshake = Handshake(
				hs_type=3,
				chain_id=4,
				user_id=88,
				outcome_id=88,
				odds=1.2,
				amount=1,
				currency='ETH',
				side=2,
				remaining_amount=0,
				from_address='0x123',
				status=0
		)
		db.session.add(handshake)
		db.session.commit()

		# -----
		shaker = Shaker(
					shaker_id=66,
					amount=0.2,
					currency='ETH',
					odds=6,
					side=1,
					handshake_id=handshake.id,
					from_address='0x123',
					chain_id=4,
					status=2
				)
		db.session.add(shaker)
		db.session.commit()

		outcome = Outcome.find_outcome_by_id(88)
		outcome.result = 1
		db.session.flush()

		handshake_bl.save_collect_state_for_shaker(shaker)
		db.session.commit()

		h = Handshake.find_handshake_by_id(handshake.id)
		s = Shaker.find_shaker_by_id(shaker.id)

		self.assertEqual(h.status, 6)
		self.assertEqual(s.status, 6)
Esempio n. 3
0
    def test_parse_shakers_array(self):
        shakers = []

        expected = []
        actual = parse_shakers_array(shakers)
        self.assertEqual(expected, actual)

        expected = []
        actual = parse_shakers_array(None)
        self.assertEqual(expected, actual)

        shaker = Shaker(shaker_id=1)
        shakers.append(shaker)
        shaker = Shaker(shaker_id=2)
        shakers.append(shaker)

        expected = [1, 2]
        actual = parse_shakers_array(shakers)
        self.assertEqual(expected, actual)
	def test_rollback_shake_state(self):
		self.clear_data_before_test()

		# -----
		handshake = Handshake(
				hs_type=3,
				chain_id=4,
				user_id=88,
				outcome_id=88,
				odds=1.2,
				amount=1,
				currency='ETH',
				side=2,
				remaining_amount=0,
				from_address='0x123',
				status=0
		)
		db.session.add(handshake)
		db.session.commit()

		# -----
		shaker = Shaker(
					shaker_id=88,
					amount=0.2,
					currency='ETH',
					odds=6,
					side=1,
					handshake_id=handshake.id,
					from_address='0x123',
					chain_id=4
				)
		db.session.add(shaker)
		db.session.commit()

		handshake_bl.rollback_shake_state(shaker)

		h = Handshake.find_handshake_by_id(handshake.id)
		s = Shaker.find_shaker_by_id(shaker.id)

		self.assertEqual(h.remaining_amount, 1)
		self.assertEqual(s.status, HandshakeStatus['STATUS_SHAKER_ROLLBACK'])
	def test_has_valid_shaker(self):
		self.clear_data_before_test()
		arr_hs = []

		outcome = Outcome.find_outcome_by_id(88)
		outcome.result = 1

		# -----
		handshake = Handshake(
						hs_type=3,
						chain_id=4,
						user_id=88,
						outcome_id=88,
						odds=1.5,
						amount=1,
						currency='ETH',
						side=2,
						remaining_amount=0,
						from_address='0x123',
						status=0
					)
		db.session.add(handshake)
		db.session.commit()
		arr_hs.append(handshake)
		actual = handshake_bl.has_valid_shaker(handshake)
		expected = False
		self.assertEqual(actual, expected)

		shaker = Shaker(
					shaker_id=66,
					amount=0.2,
					currency='ETH',
					odds=6,
					side=1,
					handshake_id=handshake.id,
					from_address='0x123',
					chain_id=4,
					status=2
				)
		db.session.add(shaker)
		db.session.commit()
		arr_hs.append(shaker)

		actual = handshake_bl.has_valid_shaker(handshake)
		expected = True
		self.assertEqual(actual, expected)

		for item in arr_hs:
			db.session.delete(item)
			db.session.commit()
	def test_data_need_set_result_for_outcome(self):
		self.clear_data_before_test()
		arr_hs = []
		
		outcome = Outcome.find_outcome_by_id(88)
		outcome.result = 1

		# -----
		handshake = Handshake(
						hs_type=3,
						chain_id=4,
						user_id=88,
						outcome_id=88,
						odds=1.5,
						amount=1,
						currency='ETH',
						side=2,
						remaining_amount=0,
						from_address='0x123',
						status=0
					)
		db.session.add(handshake)
		db.session.commit()
		arr_hs.append(handshake)
		
		shaker = Shaker(
					shaker_id=66,
					amount=0.2,
					currency='ETH',
					odds=6,
					side=1,
					handshake_id=handshake.id,
					from_address='0x123',
					chain_id=4,
					status=-1
				)
		db.session.add(shaker)
		db.session.commit()
		arr_hs.append(shaker)

		handshake_bl.data_need_set_result_for_outcome(outcome)

		hs = Handshake.find_handshake_by_id(handshake.id)
		self.assertEqual(hs.status, HandshakeStatus['STATUS_MAKER_SHOULD_UNINIT'])

		for item in arr_hs:
			db.session.delete(item)
			db.session.commit()
def save_failed_handshake_method_for_event(method, tx):
    if method == 'init' or method == 'initTestDrive':
        offchain = tx.offchain.replace(CONST.CRYPTOSIGN_OFFCHAIN_PREFIX, '')
        offchain = int(offchain.replace('m', ''))
        handshake = Handshake.find_handshake_by_id(offchain)
        if handshake is not None:
            handshake.status = HandshakeStatus['STATUS_INIT_FAILED']
            db.session.flush()

            arr = []
            arr.append(handshake)
            return arr, None

    elif method == 'shake' or method == 'shakeTestDrive':
        offchain = tx.offchain.replace(CONST.CRYPTOSIGN_OFFCHAIN_PREFIX, '')
        offchain = int(offchain.replace('s', ''))
        shaker = Shaker.find_shaker_by_id(offchain)
        if shaker is not None:
            if shaker.status == HandshakeStatus['STATUS_PENDING']:
                shaker = rollback_shake_state(shaker)

            shaker.status = HandshakeStatus['STATUS_SHAKE_FAILED']
            db.session.flush()

            arr = []
            arr.append(shaker)
            return None, arr

    elif method == 'report':
        payload = tx.payload
        data = json.loads(payload)

        if '_options' in data:
            options = data['_options']
            if 'onchainData' in options:
                onchain = options['onchainData']
                if 'hid' in onchain:
                    hid = int(onchain['hid'])
                    outcome = Outcome.find_outcome_by_hid(hid)
                    if outcome is not None and outcome.result == CONST.RESULT_TYPE[
                            'PROCESSING']:
                        outcome.result = CONST.RESULT_TYPE['REPORT_FAILED']
                        db.session.flush()
        send_report_slack.delay(outcome.id, result, status=2)
        return None, None

    return None, None
Esempio n. 8
0
def update_feed_status():
	try:
		data = request.json
		is_maker = int(data.get('is_maker', -1))
		item_id = int(data.get('id', -1))
		status = int(data.get('status', -1))
		amount = data.get('amount') # string
		remaining_amount = data.get('remaining_amount') # string

		if is_maker == -1 or status == -1 or item_id == -1:
			return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

		handshake = None

		if is_maker == 1:
			handshake = Handshake.find_handshake_by_id(item_id)
			if handshake is not None:
				handshake.status = status
				if amount is not None:
					handshake.amount = amount
				if remaining_amount is not None:
					handshake.remaining_amount = remaining_amount
		else:
			shaker = Shaker.find_shaker_by_id(item_id)
			if shaker is not None:
				shaker.status = status
				handshake = Handshake.find_handshake_by_id(shaker.handshake_id)
				if handshake is not None:
					status = handshake.status

					if amount is not None:
						handshake.amount = amount
					if remaining_amount is not None:
						handshake.remaining_amount = remaining_amount

		db.session.flush()
		db.session.commit()
		update_status_feed.delay(handshake.id, status, amount=amount, remaining_amount=remaining_amount)
		return response_ok()

	except Exception, ex:
		db.session.rollback()
		return response_error(ex.message)
def save_collect_state_for_maker(handshake):
    if handshake is not None:
        outcome = Outcome.find_outcome_by_id(handshake.outcome_id)
        if outcome is not None:
            if handshake.side == outcome.result:
                shaker = Shaker.find_shaker_by_handshake_id(handshake.id)
                if shaker is not None:
                    shaker.bk_status = shaker.status
                    shaker.status = HandshakeStatus['STATUS_DONE']

                    db.session.merge(shaker)
                    db.session.flush()
                    handshakes, shakers = save_status_all_bet_which_user_win(
                        handshake.user_id, outcome)

                    if shakers is None:
                        shakers = []
                    shakers.append(shaker)
                    return handshakes, shakers
    return None, None
    def test_user_reputation(self):
        t = datetime.now().timetuple()
        seconds = local_to_utc(t)
        db.session.query(Handshake).filter(Handshake.outcome_id.in_([1000, 1001, 1002])).delete(synchronize_session="fetch")

        db.session.query(Shaker).filter(Shaker.handshake_id.in_(\
            db.session.query(Handshake.id).filter(Handshake.outcome_id.in_([1000, 1001, 1002]))\
        )).delete(synchronize_session="fetch")

        arr_hs = []

        match = Match.find_match_by_id(1)
        if match is not None:
            match.date=seconds - 100,
            match.reportTime=seconds + 100,
            match.disputeTime=seconds + 200,
            db.session.flush()
        else:
            match = Match(
                id=1,
                date=seconds - 100,
                reportTime=seconds + 100,
                disputeTime=seconds + 200,
            )
            db.session.add(match)

        outcome1 = Outcome.find_outcome_by_id(1000)
        if outcome1 is not None:
            db.session.delete(outcome1)
            db.session.commit()

        outcome1 = Outcome(
            id=1000,
            match_id=match.id,
            result=1,
            name="1"
        )
        db.session.add(outcome1)
        db.session.commit()
        
        outcome2 = Outcome.find_outcome_by_id(1001)
        if outcome2 is not None:
            db.session.delete(outcome2)
            db.session.commit()

        outcome2 = Outcome(
            id=1001,
            match_id=match.id,
            result=1,
            name="1"
        )
        db.session.add(outcome2)
        db.session.commit()
        
        outcome3 = Outcome.find_outcome_by_id(1002)
        if outcome3 is not None:
            db.session.delete(outcome3)
            db.session.commit()

        outcome3 = Outcome(
            id=1002,
            match_id=match.id,
            result=1,
            name="1"
        )
        db.session.add(outcome3)
        db.session.commit()
        
        user1 = User.find_user_with_id(88)
        if user1 is None:
            user1 = User(
                id=88
            )
            db.session.add(user1)
            db.session.commit()
        
        user2 = User.find_user_with_id(89)
        if user2 is None:
            user2 = User(
                id=89
            )
            db.session.add(user2)
            db.session.commit()
        
        user3 = User.find_user_with_id(100)
        if user3 is None:
            user3 = User(
                id=100
            )
            db.session.add(user3)
        db.session.commit()
        
        handshake1 = Handshake(
                hs_type=3,
                chain_id=4,
                user_id=user1.id,
                outcome_id=outcome1.id,
                odds=1.5,
                amount=1,
                currency='ETH',
                side=outcome1.result,
                remaining_amount=0,
                from_address='0x123',
                status=HandshakeStatus['STATUS_DONE']
            )
        db.session.add(handshake1)
        arr_hs.append(handshake1)
        
        handshake2 = Handshake(
                hs_type=3,
                chain_id=4,
                user_id=user1.id,
                outcome_id=outcome2.id,
                odds=1.5,
                amount=1,
                currency='ETH',
                remaining_amount=0,
                from_address='0x123',
                status=HandshakeStatus['STATUS_DONE'],
                side=outcome2.result
            )
        db.session.add(handshake2)
        arr_hs.append(handshake2)
        
        handshake3 = Handshake(
                hs_type=3,
                chain_id=4,
                user_id=user1.id,
                outcome_id=outcome2.id,
                odds=1.5,
                amount=1,
                currency='ETH',
                remaining_amount=0,
                from_address='0x123',
                status=HandshakeStatus['STATUS_DONE'],
                side=outcome2.result
            )
        db.session.add(handshake3)
        arr_hs.append(handshake3)
        
        handshake4 = Handshake(
                hs_type=3,
                chain_id=4,
                user_id=user2.id,
                outcome_id=outcome1.id,
                odds=1.5,
                amount=1,
                currency='ETH',
                remaining_amount=0,
                from_address='0x123',
                status=HandshakeStatus['STATUS_DONE'],
                side=outcome1.result
            )
        db.session.add(handshake4)
        arr_hs.append(handshake4)
        
        handshake5 = Handshake(
                hs_type=3,
                chain_id=4,
                user_id=user2.id,
                outcome_id=outcome1.id,
                odds=1.5,
                amount=1,
                currency='ETH',
                remaining_amount=0,
                from_address='0x123',
                status=HandshakeStatus['STATUS_DONE'],
                side=outcome1.result
            )
        db.session.add(handshake5)
        arr_hs.append(handshake5)
        
        handshake6 = Handshake(
                hs_type=3,
                chain_id=4,
                user_id=user3.id,
                outcome_id=outcome3.id,
                odds=1.5,
                amount=1,
                currency='ETH',
                remaining_amount=0,
                from_address='0x123',
                status=HandshakeStatus['STATUS_DONE'],
                side=outcome3.result + 1
            )
        db.session.add(handshake6)
        arr_hs.append(handshake6)
        
        handshake7 = Handshake(
                hs_type=3,
                chain_id=4,
                user_id=user3.id,
                outcome_id=outcome3.id,
                odds=1.5,
                amount=1,
                currency='ETH',
                remaining_amount=0,
                from_address='0x123',
                status=HandshakeStatus['STATUS_DONE'],
                side=outcome3.result + 1
            )
        db.session.add(handshake7)
        arr_hs.append(handshake7)
        
        shaker1 = Shaker(
            shaker_id=user2.id,
            amount=0.2,
            currency='ETH',
            odds=6,
            side=outcome1.result,
            handshake_id=handshake1.id,
            from_address='0x123',
            chain_id=4,
            status=HandshakeStatus['STATUS_DONE']
        )
        db.session.add(shaker1)
        arr_hs.append(shaker1)
        db.session.commit()
        
        shaker2 = Shaker(
            shaker_id=user3.id,
            amount=0.2,
            currency='ETH',
            odds=6,
            side=outcome1.result,
            handshake_id=handshake1.id,
            from_address='0x123',
            chain_id=4,
            status=HandshakeStatus['STATUS_DONE']
        )
        db.session.add(shaker2)
        arr_hs.append(shaker2)
        db.session.commit()
        
        # hs_bets = db.session.query(Handshake.user_id.label("user_id"), bindparam("is_hs", 1), Handshake.free_bet, Handshake.status, Handshake.side, Handshake.from_address, Outcome.id, Outcome.name)\
        #     .filter(Handshake.outcome_id == Outcome.id)\
        #     .filter(Outcome.match_id == 1)\
        #     .filter(Handshake.user_id == user1.id)
        # s_bets = db.session.query(Shaker.shaker_id.label("user_id"), bindparam("is_hs", 0), Shaker.free_bet, Handshake.status, Shaker.side, Shaker.from_address, Outcome.id, Outcome.name)\
        #     .filter(Shaker.handshake_id == Handshake.id)\
        #     .filter(Handshake.outcome_id == Outcome.id)\
        #     .filter(Outcome.match_id == 1)\
        #     .filter(Shaker.shaker_id == user1.id)
        # bets = hs_bets.union_all(s_bets).order_by(Outcome.id.desc()).all()
        # print bets
        # Get all user betted this outcome
        
        hs_user = db.session.query(Handshake.user_id.label("user_id"))\
            .filter(Handshake.outcome_id == outcome1.id)
        s_user = db.session.query(Shaker.shaker_id.label("user_id"))\
            .filter(Shaker.handshake_id == Handshake.id)\
            .filter(Handshake.outcome_id == outcome1.id)
        total_users = hs_user.union_all(s_user).group_by('user_id')
        # users = db.session.query(User).filter(User.id.in_(hs_user.union_all(s_user).group_by('user_id'))).all()
        hs_all_bets = db.session.query(Handshake.user_id.label("user_id"), bindparam("is_hs", 1), Handshake.free_bet, Handshake.status.label("status"), Handshake.side.label('side'), Handshake.from_address, Outcome.result.label('outcome_result'))\
            .filter(Outcome.id == Handshake.outcome_id)
        s_all_bets = db.session.query(Shaker.shaker_id.label("user_id"), bindparam("is_hs", 0), Shaker.free_bet, Shaker.status.label("status"), Shaker.side.label('side'), Shaker.from_address, Outcome.result.label('outcome_result'))\
            .filter(Shaker.handshake_id == Handshake.id)\
            .filter(Outcome.id == Handshake.outcome_id)
        bets_query = hs_all_bets.union_all(s_all_bets).subquery()
        bets = db.session.query(
            bets_query.c.user_id.label('user_id'),
            func.count(bets_query.c.user_id).label('total_bets'),
            bindparam("total_bets_win", 0)
        )\
        .filter(bets_query.c.user_id.in_(total_users))\
        .filter(bets_query.c.status.in_([HandshakeStatus['STATUS_DONE'], HandshakeStatus['INDUSTRIES_NONE']]))\
        .group_by(bets_query.c.user_id)
        
        bets_win = db.session.query(
            bets_query.c.user_id.label('user_id'),
            bindparam("total_bets", 0),
            func.count(bets_query.c.user_id).label('total_bets_win'),
        )\
        .filter(bets_query.c.user_id.in_(total_users))\
        .filter(bets_query.c.status.in_([HandshakeStatus['STATUS_DONE'], HandshakeStatus['INDUSTRIES_NONE']]))\
        .filter(bets_query.c.side == bets_query.c.outcome_result)\
        .group_by(bets_query.c.user_id)
        
        result_query = bets.union_all(bets_win).subquery()
        adset_list = db.session.query(
            result_query.c.user_id,
            func.sum(result_query.c.total_bets_win).label('total_bets_win'),
            func.sum(result_query.c.total_bets).label('total_bets')
        ).group_by(result_query.c.user_id)
        
        results = adset_list.all()
        for item in results:
            if item.user_id ==  user1.id:
                self.assertTrue(item.total_bets_win == 3)
        for item in arr_hs:
            db.session.delete(item)
            db.session.commit()
        #########################################################################
        #                                                                       #
        #########################################################################
        user_id = 789
        user = User.find_user_with_id(789)
        arr_hs = []
        arr_hs.append(match)
        if user is not None:
            outcomes = db.session.query(Outcome)\
            .filter(Outcome.created_user_id == user_id)\
            .all()

            for oc in outcomes:
                # arr_delete.extend(oc)
                hs = db.session.query(Handshake)\
                .filter(Outcome.id == oc.id)\
                .all()

                for h in hs:
                    sh = db.session.query(Shaker)\
                        .filter(Shaker.handshake_id == Handshake.id)\
                        .filter(Handshake.outcome_id == oc.id)\
                        .all()

                    for s in sh:
                        db.session.delete(s)
                    db.session.delete(h)
                db.session.delete(oc)
            db.session.commit()
        else:
            user = User(
                id=user_id,
                fcm_token="",
                payload=""
            )
            db.session.add(user)
            db.session.commit()
        
        outcome1 = Outcome(
            created_user_id=user_id,
            match_id=match.id,
            result=1,
            hid=789
        )
        db.session.add(outcome1)
        arr_hs.append(outcome1)

        outcome2 = Outcome(
            created_user_id=user_id,
            match_id=match.id,
            result=1,
            hid=790
        )
        db.session.add(outcome2)
        arr_hs.append(outcome2)

        outcome_dispute = Outcome(
            created_user_id=user_id,
            match_id=1,
            result=-3,
            hid=793
        )
        db.session.add(outcome_dispute)
        db.session.commit()
        arr_hs.append(outcome_dispute)

        total_amount = 0
        total_dispute_amount = 0
        total_bet = 0
        total_dispute_bet = 0
        total_dispute_event = 1

        hs1 = Handshake(
                hs_type=3,
                chain_id=4,
                user_id=user_id,
                outcome_id=outcome1.id,
                odds=1.5,
                amount=0.000227075,
                currency='ETH',
                remaining_amount=0,
                from_address='0x123',
                status=HandshakeStatus['STATUS_DONE'],
                side=outcome3.result + 1
            )
        db.session.add(hs1)
        db.session.commit()
        arr_hs.append(hs1)

        total_amount += 0.000227075
        total_bet += 1

        shaker2 = Shaker(
            shaker_id=user_id,
            amount=0.0001234455,
            currency='ETH',
            odds=6,
            side=outcome1.result,
            handshake_id=hs1.id,
            from_address='0x123',
            chain_id=4,
            status=HandshakeStatus['STATUS_DONE']
        )
        db.session.add(shaker2)
        db.session.commit()
        arr_hs.append(shaker2)

        total_amount += 0.0001234455
        total_bet += 1

        hs2 = Handshake(
                hs_type=3,
                chain_id=4,
                user_id=user_id,
                outcome_id=outcome2.id,
                odds=1.5,
                amount=0.00032612678,
                currency='ETH',
                remaining_amount=0,
                from_address='0x123',
                status=HandshakeStatus['STATUS_DONE'],
                side=outcome3.result + 1
            )
        db.session.add(hs2)
        db.session.commit()
        arr_hs.append(hs2)
        total_amount += 0.00032612678
        total_bet += 1

        hs_dispute = Handshake(
                hs_type=3,
                chain_id=4,
                user_id=user_id,
                outcome_id=outcome_dispute.id,
                odds=1.5,
                amount=0.0006427075,
                currency='ETH',
                remaining_amount=0,
                from_address='0x123',
                status=HandshakeStatus['STATUS_DISPUTED'],
                side=1
            )
        db.session.add(hs_dispute)
        db.session.commit()
        arr_hs.append(hs_dispute)
        total_amount += 0.0006427075

        total_bet += 1
        total_dispute_amount += 0.0006427075
        total_dispute_bet += 1

        hs_dispute2 = Handshake(
                hs_type=3,
                chain_id=4,
                user_id=user_id,
                outcome_id=outcome1.id,
                odds=1.5,
                amount=0.0003227075,
                currency='ETH',
                remaining_amount=0,
                from_address='0x123',
                status=HandshakeStatus['STATUS_DISPUTE_PENDING'],
                side=1
            )
        db.session.add(hs_dispute2)
        db.session.commit()
        arr_hs.append(hs_dispute2)
        total_amount += 0.0003227075

        total_bet += 1
        total_dispute_amount += 0.0003227075
        total_dispute_bet += 1

        s_dispute2 = Shaker(
            shaker_id=user_id,
            amount=0.00012344379,
            currency='ETH',
            odds=6,
            side=outcome1.result,
            handshake_id=hs_dispute2.id,
            from_address='0x123',
            chain_id=4,
            status=HandshakeStatus['STATUS_USER_DISPUTED']
        )
        db.session.add(s_dispute2)
        db.session.commit()
        arr_hs.append(s_dispute2)

        total_amount += 0.00012344379
        total_bet += 1
        total_dispute_amount += 0.00012344379
        total_dispute_bet += 1

        with self.client:
            response = self.client.get(
                                    '/reputation/{}'.format(user_id),
                                    content_type='application/json',
                                    headers={
                                        "Uid": "{}".format(66),
                                        "Fcm-Token": "{}".format(123),
                                        "Payload": "{}".format(123),
                                    })

            data = json.loads(response.data.decode()) 
            self.assertTrue(data['status'] == 1)
            self.assertEqual(response.status_code, 200)

            self.assertTrue(data['data']['total_events'] == 3)
            self.assertTrue(data['data']['total_amount'] == total_amount)
            # self.assertTrue(data['data']['total_bets'] == total_bet)
            # self.assertTrue(data['data']['total_disputed_amount'] == total_dispute_amount)
            self.assertTrue(data['data']['total_disputed_bets'] == total_dispute_bet)
            # self.assertTrue(data['data']['total_disputed_events'] == 1)            

            for item in arr_hs:
                db.session.delete(item)
                db.session.commit()
	def test_test_save_refund_state_for_all(self):
		self.clear_data_before_test()
		arr_hs = []
		arr_sk = []

		# -----
		handshake1 = Handshake(
						hs_type=3,
						chain_id=4,
						user_id=88,
						outcome_id=88,
						odds=1.5,
						amount=1,
						currency='ETH',
						side=2,
						remaining_amount=0,
						from_address='0x123',
						status=HandshakeStatus['STATUS_REFUND_PENDING']
					)
		db.session.add(handshake1)
		db.session.commit()
		arr_hs.append(handshake1)

		handshake2 = Handshake(
						hs_type=3,
						chain_id=4,
						user_id=88,
						outcome_id=88,
						odds=1.5,
						amount=1,
						currency='ETH',
						side=2,
						remaining_amount=0,
						from_address='0x123',
						status=HandshakeStatus['STATUS_MAKER_UNINITED']
					)
		db.session.add(handshake2)
		db.session.commit()
		arr_hs.append(handshake2)

		handshake3 = Handshake(
						hs_type=3,
						chain_id=4,
						user_id=99,
						outcome_id=88,
						odds=1.5,
						amount=1,
						currency='ETH',
						side=2,
						remaining_amount=0,
						from_address='0x123',
						status=HandshakeStatus['STATUS_INITED']
					)
		db.session.add(handshake3)
		db.session.commit()
		arr_hs.append(handshake3)

		# -----
		shaker1 = Shaker(
					shaker_id=88,
					amount=0.2,
					currency='ETH',
					odds=6,
					side=1,
					handshake_id=handshake1.id,
					from_address='0x123',
					chain_id=4,
					status=HandshakeStatus['STATUS_REFUND_PENDING']
				)
		db.session.add(shaker1)
		db.session.commit()
		arr_sk.append(shaker1)

		# -----
		shaker2 = Shaker(
					shaker_id=88,
					amount=0.2,
					currency='ETH',
					odds=6,
					side=1,
					handshake_id=handshake3.id,
					from_address='0x123',
					chain_id=4,
					status=HandshakeStatus['STATUS_REFUND_PENDING']
				)
		db.session.add(shaker2)
		db.session.commit()
		arr_sk.append(shaker2)

		handshakes, shakers = handshake_bl.save_refund_state_for_all(88, 88)
		actual = None

		hs1 = Handshake.find_handshake_by_id(handshake1.id)
		self.assertEqual(hs1.status, HandshakeStatus['STATUS_REFUNDED'])
		hs2 = Handshake.find_handshake_by_id(handshake2.id)
		self.assertEqual(hs2.status, HandshakeStatus['STATUS_MAKER_UNINITED'])
		hs3 = Handshake.find_handshake_by_id(handshake3.id)
		self.assertEqual(hs3.status, HandshakeStatus['STATUS_INITED'])

		sk1 = Shaker.find_shaker_by_id(shaker1.id)
		self.assertEqual(sk1.status, HandshakeStatus['STATUS_REFUNDED'])
		sk2 = Shaker.find_shaker_by_id(shaker2.id)
		self.assertEqual(sk2.status, HandshakeStatus['STATUS_REFUNDED'])

		for item in arr_hs:
			db.session.delete(item)
			db.session.commit()
		for item in arr_sk:
			db.session.delete(item)
			db.session.commit()
def save_handshake_for_event(event_name, inputs):
    offchain, hid, state, outcome_result = parse_inputs(inputs)
    offchain = offchain.replace(CONST.CRYPTOSIGN_OFFCHAIN_PREFIX, '')

    if event_name == '__createMarket':
        print '__createMarket'
        offchain = int(offchain.replace('createMarket', ''))
        outcome = Outcome.find_outcome_by_id(offchain)
        if outcome is not None:
            outcome.hid = hid

            if 'closingTime' in inputs and \
             'reportTime' in inputs and \
             'disputeTime' in inputs:
                m = Match.find_match_by_id(outcome.match_id)
                m.date = int(inputs['closingTime'])
                m.reportTime = int(inputs['reportTime'])
                m.disputeTime = int(inputs['disputeTime'])

            db.session.flush()

            if outcome_bl.is_outcome_created_by_user(outcome):
                send_email_event_verification_success.delay(
                    outcome.match_id, outcome.created_user_id)

        return None, None

    elif event_name == '__report':
        print '__report'
        # report{outcome_id}_{side}
        # side 1: SUPPORT, 2: OPPOSE, 3: DRAW
        outcome_id, result = offchain.replace('report', '').split('_')
        if outcome_id is None or result is None:
            return None, None

        outcome = Outcome.find_outcome_by_id(outcome_id)
        if len(result) > -1 and outcome is not None:
            result = int(result)
            outcome.result = result
            db.session.flush()

            handshakes, shakers = data_need_set_result_for_outcome(outcome)

            # send result email to users who play in
            send_result_email(outcome.id, result)

            send_report_slack.delay(outcome.id, result, status=1)

            return handshakes, shakers

        return None, None

    elif event_name == '__shake':
        print '__shake'
        offchain = offchain.replace('s', '')
        shaker = Shaker.find_shaker_by_id(int(offchain))
        if shaker is not None:
            shaker.status = HandshakeStatus['STATUS_SHAKER_SHAKED']
            shaker.bk_status = HandshakeStatus['STATUS_SHAKER_SHAKED']
            db.session.flush()

            # Add shuriken
            if shaker.free_bet == 1:
                add_shuriken.delay(shaker.shaker_id,
                                   CONST.SHURIKEN_TYPE['FREE'])
            else:
                add_shuriken.delay(shaker.shaker_id,
                                   CONST.SHURIKEN_TYPE['REAL'])

            # Give redeem code for referral user
            u = User.find_user_with_id(shaker.shaker_id)
            if u is not None and u.played_bet == 0:
                referral_bl.give_redeem_code_for_referred_user(
                    shaker.shaker_id)
                u.played_bet = 1
                db.session.flush()

            arr = []
            arr.append(shaker)

            return None, arr

        return None, None

    elif event_name == '__collect':
        print '__collect'

        if 's' in offchain:
            offchain = offchain.replace('s', '')
            shaker = Shaker.find_shaker_by_id(int(offchain))
            if shaker is not None:
                # update status of shaker and handshake to done
                # find all bets belongs to this outcome which user join
                # update all statuses (shaker and handshake) of them to done
                return save_collect_state_for_shaker(shaker)

        elif 'm' in offchain:
            offchain = offchain.replace('m', '')
            handshake = Handshake.find_handshake_by_id(int(offchain))
            if handshake is not None:
                # update status of shaker and handshake to done
                # find all bets belongs to this outcome which user join
                # update all statuses (shaker and handshake) of them to done
                return save_collect_state_for_maker(handshake)

        return None, None

    elif event_name == '__init':
        print '__init'
        offchain = offchain.replace('m', '')
        handshake = Handshake.find_handshake_by_id(int(offchain))
        if handshake is not None:
            handshake.status = HandshakeStatus['STATUS_INITED']
            handshake.bk_status = HandshakeStatus['STATUS_INITED']

            db.session.flush()

            arr = []
            arr.append(handshake)

            # Add shuriken
            if handshake.free_bet == 1:
                add_shuriken.delay(handshake.user_id,
                                   CONST.SHURIKEN_TYPE['FREE'])
            else:
                add_shuriken.delay(handshake.user_id,
                                   CONST.SHURIKEN_TYPE['REAL'])

            # Give redeem code for referral user
            u = User.find_user_with_id(handshake.user_id)
            if u is not None and u.played_bet == 0:
                referral_bl.give_redeem_code_for_referred_user(
                    handshake.user_id)
                u.played_bet = 1
                db.session.flush()

            return arr, None

        return None, None

    elif event_name == '__uninit':
        print '__uninit'
        offchain = offchain.replace('m', '')
        handshake = Handshake.find_handshake_by_id(int(offchain))
        if handshake is not None:
            handshake.status = HandshakeStatus['STATUS_MAKER_UNINITED']
            handshake.bk_status = HandshakeStatus['STATUS_MAKER_UNINITED']
            db.session.flush()

            arr = []
            arr.append(handshake)
            return arr, None
        return None, None

    elif event_name == '__refund':
        print '__refund'
        handshake = None
        user_id = None
        free_bet = False
        if 's' in offchain:
            offchain = offchain.replace('s', '')
            shaker = Shaker.find_shaker_by_id(int(offchain))
            if shaker is None:
                return None, None

            user_id = shaker.shaker_id
            free_bet = shaker.free_bet
            handshake = Handshake.find_handshake_by_id(shaker.handshake_id)

        elif 'm' in offchain:
            offchain = offchain.replace('m', '')
            handshake = Handshake.find_handshake_by_id(int(offchain))
            user_id = handshake.user_id
            free_bet = handshake.free_bet

        if handshake is None or user_id is None:
            return None, None

        if free_bet is True:
            redeem_bl.issue_new_redeem_code_for_user(user_id)

        return save_refund_state_for_all(user_id, handshake.outcome_id)

    elif event_name == '__dispute':
        print '__dispute'
        shaker_dispute = []
        handshake_dispute = []
        handshake = None
        user_id = None
        side = None

        if outcome_result is None:
            return None, None

        if state < 2:
            return None, None

        if 's' in offchain:
            offchain = offchain.replace('s', '')
            shaker = Shaker.find_shaker_by_id(int(offchain))
            user_id = shaker.shaker_id
            side = shaker.side

            if shaker is not None:
                handshake = Handshake.find_handshake_by_id(shaker.handshake_id)

        elif 'm' in offchain:
            offchain = offchain.replace('m', '')
            handshake = Handshake.find_handshake_by_id(int(offchain))
            user_id = handshake.user_id
            side = handshake.side

        if handshake is None or user_id is None:
            return None, None

        outcome = Outcome.find_outcome_by_id(handshake.outcome_id)
        if outcome is None:
            return None, None

        update_amount_for_outcome(outcome.id, user_id, side, outcome_result)

        if state == 3 and outcome.result != CONST.RESULT_TYPE['DISPUTED']:
            outcome.result = CONST.RESULT_TYPE['DISPUTED']
            db.session.flush()
            handshake_dispute, shaker_dispute = save_disputed_state(outcome.id)

            # Send mail to admin
            send_dispute_email.delay(outcome.match.name)

        else:
            handshake_dispute, shaker_dispute = save_user_disputed_state(
                handshake, user_id, side, outcome_result)

        return handshake_dispute, shaker_dispute

    elif event_name == '__resolve':
        # resolve{outcome_id}_{side}
        print '__resolve'
        outcome_id, result = offchain.replace('resolve', '').split('_')
        if outcome_id is None or result is None:
            return None, None

        # 1: SUPPORT, 2: OPPOSE, 3: DRAW: It's depended on smart contract definition.
        if len(result) == 0 or int(result) not in [1, 2, 3]:
            return None, None
        outcome = Outcome.find_outcome_by_id(outcome_id)
        if outcome is None:
            return None, None

        result = int(result)
        outcome.total_dispute_amount = 0
        outcome.result = result
        db.session.flush()

        handshakes, shakers = save_resolve_state_for_outcome(outcome.id)

        # send result email to users who play in
        send_result_email(outcome.id, result)
        return handshakes, shakers
Esempio n. 13
0
    def test_count_users_play_on_outcome(self):
        self.clear_data_before_test()

        arr_hs = []
        # -----
        handshake = Handshake(hs_type=3,
                              chain_id=4,
                              user_id=109,
                              outcome_id=109,
                              odds=1.2,
                              amount=1,
                              currency='ETH',
                              side=1,
                              remaining_amount=1,
                              from_address='0x123',
                              status=0)
        arr_hs.append(handshake)
        db.session.add(handshake)
        db.session.commit()

        # -----
        handshake = Handshake(hs_type=3,
                              chain_id=4,
                              user_id=88,
                              outcome_id=109,
                              odds=1.2,
                              amount=1,
                              currency='ETH',
                              side=1,
                              remaining_amount=1,
                              from_address='0x123',
                              status=-1)
        arr_hs.append(handshake)
        db.session.add(handshake)
        db.session.commit()

        # -----
        shaker = Shaker(shaker_id=88,
                        handshake_id=handshake.id,
                        status=2,
                        side=2)
        arr_hs.append(shaker)
        db.session.add(shaker)
        db.session.commit()

        # -----
        shaker = Shaker(shaker_id=109,
                        handshake_id=handshake.id,
                        status=2,
                        side=2)
        arr_hs.append(shaker)
        db.session.add(shaker)
        db.session.commit()

        actual = outcome_bl.count_users_play_on_outcome(109)
        expected = 2
        self.assertEqual(actual, expected)

        for handshake in arr_hs:
            db.session.delete(handshake)
            db.session.commit()
def save_handshake_method_for_event(method, inputs):
    offchain, hid, state, outcome_result = parse_inputs(inputs)
    if method == 'init' or method == 'initTestDrive':
        offchain = offchain.replace(CONST.CRYPTOSIGN_OFFCHAIN_PREFIX, '')
        offchain = int(offchain.replace('m', ''))
        handshake = Handshake.find_handshake_by_id(offchain)
        if handshake is not None:
            handshake.bk_status = handshake.status
            handshake.status = HandshakeStatus['STATUS_INIT_FAILED']
            db.session.flush()

            arr = []
            arr.append(handshake)
            return arr, None

    elif method == 'shake' or method == 'shakeTestDrive':
        offchain = offchain.replace(CONST.CRYPTOSIGN_OFFCHAIN_PREFIX, '')
        offchain = int(offchain.replace('s', ''))
        shaker = Shaker.find_shaker_by_id(offchain)
        if shaker is not None:
            if shaker.status == HandshakeStatus['STATUS_PENDING']:
                shaker = rollback_shake_state(shaker)

            shaker.bk_status = shaker.status
            shaker.status = HandshakeStatus['STATUS_SHAKE_FAILED']
            db.session.flush()

            arr = []
            arr.append(shaker)
            return None, arr

    elif method == 'uninit' or method == 'uninitTestDrive':
        offchain = offchain.replace(CONST.CRYPTOSIGN_OFFCHAIN_PREFIX, '')
        offchain = int(offchain.replace('m', ''))
        handshake = Handshake.find_handshake_by_id(offchain)
        if handshake is not None:
            handshake.bk_status = handshake.status
            handshake.status = HandshakeStatus['STATUS_MAKER_UNINIT_FAILED']
            db.session.flush()

            arr = []
            arr.append(handshake)
            return arr, None

    elif method == 'collect' or method == 'collectTestDrive':
        offchain = offchain.replace(CONST.CRYPTOSIGN_OFFCHAIN_PREFIX, '')

        if 'm' in offchain:
            offchain = int(offchain.replace('m', ''))
            handshake = Handshake.find_handshake_by_id(offchain)
            if handshake is not None:
                handshake.bk_status = handshake.status
                handshake.status = HandshakeStatus['STATUS_COLLECT_FAILED']
                db.session.flush()

                arr = []
                arr.append(handshake)
                return arr, None

        elif 's' in offchain:
            offchain = int(offchain.replace('s', ''))
            shaker = Shaker.find_shaker_by_id(offchain)
            if shaker is not None:
                shaker.bk_status = shaker.status
                shaker.status = HandshakeStatus['STATUS_COLLECT_FAILED']
                db.session.flush()

                arr = []
                arr.append(shaker)
                return None, arr

    elif method == 'refund':
        offchain = offchain.replace(CONST.CRYPTOSIGN_OFFCHAIN_PREFIX, '')

        if 'm' in offchain:
            offchain = int(offchain.replace('m', ''))
            handshake = Handshake.find_handshake_by_id(offchain)
            if handshake is not None:
                handshake.bk_status = handshake.status
                handshake.status = HandshakeStatus['STATUS_REFUND_FAILED']
                db.session.flush()

                arr = []
                arr.append(handshake)
                return arr, None

        elif 's' in offchain:
            offchain = int(offchain.replace('s', ''))
            shaker = Shaker.find_shaker_by_id(offchain)
            if shaker is not None:
                shaker.bk_status = shaker.status
                shaker.status = HandshakeStatus['STATUS_REFUND_FAILED']
                db.session.flush()

                arr = []
                arr.append(shaker)
                return None, arr

    elif method == 'report':
        outcome_id, result = offchain.replace('cryptosign_report',
                                              '').split('_')
        if outcome_id is None:
            return None, None
        print 'report fail with outcome_id {}'.format(outcome_id)
        outcome = Outcome.find_outcome_by_id(outcome_id)

        if outcome is not None and outcome.result == CONST.RESULT_TYPE[
                'PROCESSING']:
            outcome.result = CONST.RESULT_TYPE['REPORT_FAILED']
            db.session.flush()
        send_report_slack.delay(outcome.id, result, status=0)

    elif method == 'resolve':
        outcome_id, result = offchain.replace('cryptosign_resolve',
                                              '').split('_')
        if outcome_id is None:
            return None, None
        print 'resolve fail with outcome_id {}'.format(outcome_id)
        outcome = Outcome.find_outcome_by_id(outcome_id)

        if outcome is not None and outcome.result == CONST.RESULT_TYPE[
                'DISPUTED']:
            outcome.result = CONST.RESULT_TYPE['REPORT_FAILED']
            db.session.flush()

    return None, None
	def test_can_refund_for_shaker(self):
		self.clear_data_before_test()
		match = Match.find_match_by_id(1)
		if match is None:
    			match = Match(
				public=1,
				date=seconds - 100,
				reportTime=seconds + 1000,
				disputeTime=seconds + 1000,
				source_id = source.id
			)

			db.session.add(match)
			db.session.commit()
		else:
			match.date = time.time() - 100
			match.disputeTime = time.time() + 1000
			match.reportTime = time.time() + 1000
			db.session.merge(match)
			db.session.commit()

		outcome = Outcome.find_outcome_by_id(88)
		if outcome is not None:
			outcome.result = 1
			outcome.match_id=match.id
		else:
			outcome = Outcome(
				id=88,
				match_id=match.id,
				result=1,
				hid=88,
				contract_id=1
			)
			db.session.add(outcome)
		db.session.commit()

		arr_hs = []

		# -----
		handshake = Handshake(
						hs_type=3,
						chain_id=4,
						user_id=88,
						outcome_id=88,
						odds=1.5,
						amount=1,
						currency='ETH',
						side=2,
						remaining_amount=0,
						from_address='0x123',
						status=0
					)
		db.session.add(handshake)
		db.session.commit()
		arr_hs.append(handshake)

		# -----
		shaker = Shaker(
					shaker_id=66,
					amount=0.2,
					currency='ETH',
					odds=6,
					side=1,
					handshake_id=handshake.id,
					from_address='0x123',
					chain_id=4,
					status=2
				)
		db.session.add(shaker)
		db.session.commit()
		arr_hs.append(shaker)


		actual = handshake_bl.can_refund(None, shaker=shaker)
		expected = False
		self.assertEqual(actual, expected)

		outcome = Outcome.find_outcome_by_id(88)
		outcome.result = 3
		db.session.merge(outcome)
		db.session.flush()

		actual = handshake_bl.can_refund(None, shaker=shaker)
		expected = True
		self.assertEqual(actual, expected)


		for item in arr_hs:
			db.session.delete(item)
			db.session.commit()
	def test_send_email_result_notifcation(self):
		user = User(
			email="*****@*****.**",
			payload="LDwp7UQoRNW5tUwzrA6q2trkwJLS3q6IHdOB0vt4T3dWV-a720yuWC1A9g==",
			is_subscribe=1
		)
		db.session.add(user)
		db.session.commit()

		match = Match(
			name="match test email"
		)
		db.session.add(match)
		db.session.commit()

		outcome = Outcome(
			match_id=match.id,
			name="Outcome Name",
			result=1,
			hid=9999999,
			contract_id=1
		)
		db.session.add(outcome)
		db.session.commit()

		outcome_draw = Outcome(
			match_id=match.id,
			name="Outcome Draw",
			result=3,
			contract_id=1
		)
		db.session.add(outcome_draw)
		db.session.commit()

		handshake_win = Handshake(
						hs_type=3,
						chain_id=4,
						user_id=user.id,
						outcome_id=outcome.id,
						odds=1.5,
						amount=1,
						currency='ETH',
						side=outcome.result,
						remaining_amount=0,
						from_address='0x123',
						status=0
					)
		db.session.add(handshake_win)
		db.session.commit()

		handshake_draw = Handshake(
						hs_type=3,
						chain_id=4,
						user_id=user.id,
						outcome_id=outcome.id,
						odds=1.5,
						amount=1,
						currency='ETH',
						side=2,
						remaining_amount=0,
						from_address='0x123',
						status=0
					)
		db.session.add(handshake_draw)
		db.session.commit()

		handshake_draw = Handshake(
				hs_type=3,
				chain_id=4,
				user_id=user.id,
				outcome_id=outcome_draw.id,
				odds=1.5,
				amount=1,
				currency='ETH',
				side=1,
				remaining_amount=0,
				from_address='0x123',
				status=0
			)
		db.session.add(handshake_draw)
		db.session.commit()

		# -----
		shaker_lose = Shaker(
			shaker_id=user.id,
			amount=0.2,
			currency='ETH',
			odds=6,
			side=2,
			handshake_id=handshake_win.id,
			from_address='0x123',
			chain_id=4,
			status=2
		)
		db.session.add(shaker_lose)
		db.session.commit()

		with self.client:
			params = {
                "contract": app.config.get("PREDICTION_JSON"),
                "eventName": "__report",
                "status": 1,
                'id': outcome_draw.id,
                "inputs": {
                    "offchain": "cryptosign_report{}_3".format(outcome_draw.id),
                    "hid": outcome_draw.hid
                }   
            }

			response = self.client.post(
                                    '/event',
                                    data=json.dumps(params), 
                                    content_type='application/json',
                                    headers={
                                        "Uid": "{}".format(1),
                                        "Fcm-Token": "{}".format(123),
                                        "Payload": "{}".format(123),
                                    })

			data = json.loads(response.data.decode()) 
			self.assertTrue(data['status'] == 1)
	def test_can_uninit(self):
		self.clear_data_before_test()
		# -----
		handshake = Handshake(
				hs_type=3,
				chain_id=4,
				user_id=88,
				outcome_id=88,
				odds=1.2,
				amount=1,
				currency='ETH',
				side=2,
				remaining_amount=0,
				from_address='0x123',
				status=0
		)
		db.session.add(handshake)
		db.session.commit()

		# not free-bet
		actual = handshake_bl.can_uninit(handshake)
		expected = True
		self.assertEqual(actual, expected)

		handshake.free_bet = 1
		db.session.merge(handshake)
		db.session.commit()

		# free-bet
		actual = handshake_bl.can_uninit(handshake)
		expected = False
		self.assertEqual(actual, expected)

		# -----
		shaker = Shaker(
					shaker_id=88,
					amount=0.2,
					currency='ETH',
					odds=6,
					side=1,
					handshake_id=handshake.id,
					from_address='0x123',
					chain_id=4,
					status=-1
				)
		db.session.add(shaker)
		db.session.commit()

		# free-bet with shaker status = -1
		actual = handshake_bl.can_uninit(handshake)
		expected = False
		self.assertEqual(actual, expected)

		# decrease date create of shaker
		shaker.date_created = datetime(2018, 6, 12)
		db.session.merge(shaker)
		db.session.flush()

		actual = handshake_bl.can_uninit(handshake)
		expected = True
		self.assertEqual(actual, expected)

		# set shaker status = 2
		shaker.status = 2
		db.session.merge(shaker)
		db.session.flush()

		actual = handshake_bl.can_uninit(handshake)
		expected = False
		self.assertEqual(actual, expected)

		handshake.free_bet = 0
		db.session.flush()

		actual = handshake_bl.can_uninit(handshake)
		expected = False
		self.assertEqual(actual, expected)
def init():
	"""
	" User plays bet in binary event.
	"""
	try:
		from_request = request.headers.get('Request-From', 'mobile')
		uid = int(request.headers['Uid'])
		chain_id = int(request.headers.get('ChainId', CONST.BLOCKCHAIN_NETWORK['RINKEBY']))
		user = User.find_user_with_id(uid)		

		data = request.json
		if data is None:
			return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

		hs_type = data.get('type', -1)
		extra_data = data.get('extra_data', '')
		description = data.get('description', '')
		outcome_id = data.get('outcome_id', -1)
		match_id = data.get('match_id', -1)
		odds = Decimal(data.get('odds', '2')).quantize(Decimal('.1'), rounding=ROUND_HALF_DOWN)
		amount = Decimal(data.get('amount'))
		currency = data.get('currency', 'ETH')
		side = int(data.get('side', CONST.SIDE_TYPE['SUPPORT']))
		chain_id = int(data.get('chain_id', CONST.BLOCKCHAIN_NETWORK['RINKEBY']))
		from_address = data.get('from_address', '')
		free_bet = data.get('free_bet', 0)

		print '-------- DEBUG INIT -------'
		print '-------- amount = {}, type = {}, request = {} -------'.format(amount, type(amount), data.get('amount'))

		if hs_type != CONST.Handshake['INDUSTRIES_BETTING']:
			return response_error(MESSAGE.HANDSHAKE_INVALID_BETTING_TYPE, CODE.HANDSHAKE_INVALID_BETTING_TYPE)

		if len(from_address) < 40:
			return response_error(MESSAGE.INVALID_ADDRESS, CODE.INVALID_ADDRESS)

		# check valid outcome or not
		outcome = None
		if match_id == -1:
			outcome = Outcome.find_outcome_by_id(outcome_id)
		else:
			match = Match.find_match_by_id(match_id)
			if match is not None and len(match.outcomes.all()) > 0:
				outcome = match.outcomes[0]

		if outcome is None:
			return response_error(MESSAGE.OUTCOME_INVALID, CODE.OUTCOME_INVALID)

		if outcome.result != CONST.RESULT_TYPE['PENDING']:
			return response_error(MESSAGE.OUTCOME_HAS_RESULT, CODE.OUTCOME_HAS_RESULT)

		outcome_id = outcome.id

		# make sure user cannot call free-bet in ERC20
		if free_bet == 1:
			token = Token.find_token_by_id(outcome.token_id)
			if token is not None:
				return response_error(MESSAGE.HANDSHAKE_CANNOT_CREATE_FREEBET_IN_ERC20, CODE.HANDSHAKE_CANNOT_CREATE_FREEBET_IN_ERC20)

		if odds <= 1:
			return response_error(MESSAGE.INVALID_ODDS, CODE.INVALID_ODDS)

		contract = Contract.find_contract_by_id(outcome.contract_id)
		if contract is None:
			return response_error(MESSAGE.CONTRACT_INVALID, CODE.CONTRACT_INVALID)

		# add to history
		history = History(			
			chain_id=chain_id,
			description=description,
			free_bet=free_bet,
			from_address=from_address,
			contract_address=contract.contract_address,
			contract_json=contract.json_name,
			odds=odds,
			amount=amount,
			currency=currency,
			from_request=from_request,
			side=side,
			user_id=uid,
			outcome_id=outcome_id
		)
		db.session.add(history)
		db.session.flush()

		# filter all handshakes which able be to match first
		handshakes = handshake_bl.find_all_matched_handshakes(side, odds, outcome_id, amount, uid)
		arr_hs = []
		if len(handshakes) == 0:
			handshake = Handshake(
				hs_type=hs_type,
				extra_data=extra_data,
				description=description,
				chain_id=chain_id,
				user_id=user.id,
				outcome_id=outcome_id,
				odds=odds,
				amount=amount,
				currency=currency,
				side=side,
				remaining_amount=amount,
				from_address=from_address,
				free_bet=free_bet,
				contract_address=contract.contract_address,
				contract_json=contract.json_name,
				from_request=from_request,
				history_id=history.id
			)

			db.session.add(handshake)
			db.session.commit()

			update_feed.delay(handshake.id)

			# response data
			hs_json = handshake.to_json()
			hs_json['maker_address'] = handshake.from_address
			hs_json['maker_odds'] = handshake.odds
			hs_json['hid'] = outcome.hid
			hs_json['type'] = 'init'
			hs_json['offchain'] = CONST.CRYPTOSIGN_OFFCHAIN_PREFIX + 'm' + str(handshake.id)
			arr_hs.append(hs_json)

			logfile.debug("Uid -> {}, json --> {}".format(uid, arr_hs))
		else:
			shaker_amount = amount

			hs_feed = []
			sk_feed = []
			for handshake in handshakes:
				if shaker_amount.quantize(Decimal('.00000000000000001'), rounding=ROUND_DOWN) <= 0:
					break

				handshake.shake_count += 1
				handshake_win_value = handshake.remaining_amount*handshake.odds
				shaker_win_value = shaker_amount*odds
				subtracted_amount_for_shaker = 0
				subtracted_amount_for_handshake = 0


				if is_equal(handshake_win_value, shaker_win_value):
					subtracted_amount_for_shaker = shaker_amount
					subtracted_amount_for_handshake = handshake.remaining_amount

				elif handshake_win_value >= shaker_win_value:
					subtracted_amount_for_shaker = shaker_amount
					subtracted_amount_for_handshake = shaker_win_value - subtracted_amount_for_shaker

				else:
					subtracted_amount_for_handshake = handshake.remaining_amount
					subtracted_amount_for_shaker = handshake_win_value - subtracted_amount_for_handshake

				handshake.remaining_amount -= subtracted_amount_for_handshake
				shaker_amount -= subtracted_amount_for_shaker
				db.session.merge(handshake)

				o = Outcome.find_outcome_by_id(handshake.outcome_id)

				if o is None:
					return response_error(MESSAGE.OUTCOME_INVALID, CODE.OUTCOME_INVALID)

				c = Contract.find_contract_by_id(o.contract_id)
				if c is None:
					return response_error(MESSAGE.CONTRACT_INVALID, CODE.CONTRACT_INVALID)

				# create shaker
				shaker = Shaker(
					shaker_id=user.id,
					amount=subtracted_amount_for_shaker,
					currency=currency,
					odds=odds,
					side=side,
					handshake_id=handshake.id,
					from_address=from_address,
					chain_id=chain_id,
					free_bet=free_bet,
					contract_address=c.contract_address,
					contract_json=c.json_name,
					from_request=from_request,
					history_id=history.id
				)

				db.session.add(shaker)
				db.session.flush()
				sk_feed.append(shaker)
				
				shaker_json = shaker.to_json()
				shaker_json['maker_address'] = handshake.from_address
				shaker_json['maker_odds'] = handshake.odds
				shaker_json['hid'] = outcome.hid
				shaker_json['type'] = 'shake'
				shaker_json['offchain'] = CONST.CRYPTOSIGN_OFFCHAIN_PREFIX + 's' + str(shaker.id)
				arr_hs.append(shaker_json)

			if shaker_amount.quantize(Decimal('.00000000000000001'), rounding=ROUND_DOWN) > Decimal(CONST.CRYPTOSIGN_MINIMUM_MONEY):
				handshake = Handshake(
					hs_type=hs_type,
					extra_data=extra_data,
					description=description,
					chain_id=chain_id,
					user_id=user.id,
					outcome_id=outcome_id,
					odds=odds,
					amount=shaker_amount,
					currency=currency,
					side=side,
					remaining_amount=shaker_amount,
					from_address=from_address,
					free_bet=free_bet,
					contract_address=contract.contract_address,
					contract_json=contract.json_name,
					from_request=from_request,
					history_id=history.id
				)
				db.session.add(handshake)
				db.session.flush()
				hs_feed.append(handshake)			

				hs_json = handshake.to_json()
				hs_json['maker_address'] = handshake.from_address
				hs_json['maker_odds'] = handshake.odds
				hs_json['hid'] = outcome.hid
				hs_json['type'] = 'init'
				hs_json['offchain'] = CONST.CRYPTOSIGN_OFFCHAIN_PREFIX + 'm' + str(handshake.id)
				arr_hs.append(hs_json)
			
			db.session.commit()
			logfile.debug("Uid -> {}, json --> {}".format(uid, arr_hs))

			handshake_bl.update_handshakes_feed(hs_feed, sk_feed)

		# make response
		response = {
			"handshakes": arr_hs,
			"total_bets": handshake_bl.get_total_real_bets()
		}
		return response_ok(response)

	except Exception, ex:
		db.session.rollback()
		return response_error(ex.message)
Esempio n. 19
0
    def test_run_bots_for_tx_with_shake_method(self):
        self.clear_data_before_test()

		# -----
        handshake = Handshake(
            hs_type=3,
            chain_id=4,
            user_id=88,
            outcome_id=88,
            odds=1.1,
            amount=1,
            currency='ETH',
            side=1,
            remaining_amount=1,
            from_address='0x1234',
            status=0
		)
        db.session.add(handshake)
        db.session.commit()

        # add shaker
        shaker = Shaker(
            shaker_id=66,
            amount=0.2,
            currency='ETH',
            odds=6,
            side=1,
            handshake_id=handshake.id,
            from_address='0x123',
            chain_id=4,
            status=-1
        )
        db.session.add(shaker)
        db.session.commit()

        # add tx
        tx = Tx(
            contract_method='shake',
            offchain='cryptosign_s{}'.format(shaker.id)
        )
        db.session.add(tx)
        db.session.commit()


        actual = event_bl.run_bots_for_tx(tx, debug=True)
        expected = handshake.outcome_id
        self.assertEqual(actual, expected)


        # add tx
        tx = Tx(
            contract_method='shakeTestDrive',
            offchain='cryptosign_s{}'.format(shaker.id)
        )
        db.session.add(tx)
        db.session.commit()


        actual = event_bl.run_bots_for_tx(tx, debug=True)
        expected = handshake.outcome_id
        self.assertEqual(actual, expected)