def test_is_init_pending_status(self): handshake = Handshake( hs_type=3, chain_id=4, user_id=99, outcome_id=88, odds=1.2, amount=1, currency='ETH', side=2, remaining_amount=0, from_address='0x123', status=0, ) actual = handshake_bl.is_init_pending_status(handshake) expected = False self.assertEqual(actual, expected) handshake = Handshake( hs_type=3, chain_id=4, user_id=99, outcome_id=88, odds=1.2, amount=1, currency='ETH', side=2, remaining_amount=0, from_address='0x123', status=-1 ) actual = handshake_bl.is_init_pending_status(handshake) expected = False self.assertEqual(actual, expected) handshake = Handshake( hs_type=3, chain_id=4, user_id=99, outcome_id=88, odds=1.2, amount=1, currency='ETH', side=2, remaining_amount=0, from_address='0x123', status=-1, bk_status=-1 ) actual = handshake_bl.is_init_pending_status(handshake) expected = True self.assertEqual(actual, expected)
def test_find_all_matched_handshakes_with_side_against(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=1, remaining_amount=1, from_address='0x123', status=0 ) db.session.add(handshake) db.session.commit() # ----- 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() handshakes = handshake_bl.find_all_matched_handshakes( side=2, odds=5.0, outcome_id=88, amount=0.25, maker=88) # cannot shake to myself self.assertEqual(len(handshakes), 0) # shake with another user handshakes = handshake_bl.find_all_matched_handshakes( side=2, odds=5.0, outcome_id=88, amount=0.25, maker=99) self.assertEqual(len(handshakes), 2) self.assertEqual(float(handshakes[0].odds), 1.1) self.assertEqual(float(handshakes[1].odds), 1.2)
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 refund(): """ " Refund real bet: " This step make sure user's feed will update pending status """ try: uid = int(request.headers['Uid']) user = User.find_user_with_id(uid) data = request.json if data is None: return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA) offchain = data.get('offchain', '') if len(offchain) == 0: return response_error(MESSAGE.MISSING_OFFCHAIN, CODE.MISSING_OFFCHAIN) offchain = offchain.replace(CONST.CRYPTOSIGN_OFFCHAIN_PREFIX, '') outcome = None if 'm' in offchain: offchain = int(offchain.replace('m', '')) handshake = db.session.query(Handshake).filter(and_(Handshake.id==offchain, Handshake.user_id==user.id)).first() if handshake is None: return response_error(MESSAGE.HANDSHAKE_CANNOT_REFUND, CODE.HANDSHAKE_CANNOT_REFUND) outcome = Outcome.find_outcome_by_id(handshake.outcome_id) elif 's' in offchain: offchain = int(offchain.replace('s', '')) shaker = db.session.query(Shaker).filter(and_(Shaker.id==offchain, Shaker.shaker_id==user.id)).first() if shaker is None: return response_error(MESSAGE.HANDSHAKE_CANNOT_REFUND, CODE.HANDSHAKE_CANNOT_REFUND) handshake = Handshake.find_handshake_by_id(shaker.handshake_id) outcome = Outcome.find_outcome_by_id(handshake.outcome_id) if outcome is None: return response_error(MESSAGE.OUTCOME_INVALID, CODE.OUTCOME_INVALID) handshakes = db.session.query(Handshake).filter(and_(Handshake.status.in_([HandshakeStatus['STATUS_INITED'], HandshakeStatus['STATUS_RESOLVED']]), Handshake.user_id==user.id, Handshake.outcome_id==outcome.id)).all() shakers = db.session.query(Shaker).filter(and_(Shaker.status.in_([HandshakeStatus['STATUS_SHAKER_SHAKED'], HandshakeStatus['STATUS_RESOLVED']]), Shaker.shaker_id==user.id, Shaker.handshake_id.in_(db.session.query(Handshake.id).filter(Handshake.outcome_id==outcome.id)))).all() for h in handshakes: h.bk_status = h.status h.status = HandshakeStatus['STATUS_REFUND_PENDING'] db.session.merge(h) for s in shakers: s.bk_status = s.status s.status = HandshakeStatus['STATUS_REFUND_PENDING'] db.session.merge(s) db.session.commit() handshake_bl.update_handshakes_feed(handshakes, shakers) return response_ok() except Exception, ex: db.session.rollback() return response_error(ex.message)
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 can_withdraw(handshake, shaker=None): outcome = None result = None if shaker is None: if handshake is not None: if handshake.status == HandshakeStatus[ 'STATUS_INITED'] or handshake.status == HandshakeStatus[ 'STATUS_RESOLVED']: outcome = Outcome.find_outcome_by_id(handshake.outcome_id) result = handshake.side else: return MESSAGE.CANNOT_WITHDRAW else: return MESSAGE.CANNOT_WITHDRAW else: if shaker.status == HandshakeStatus[ 'STATUS_SHAKER_SHAKED'] or shaker.status == HandshakeStatus[ 'STATUS_RESOLVED']: handshake = Handshake.find_handshake_by_id(shaker.handshake_id) outcome = Outcome.find_outcome_by_id(handshake.outcome_id) result = shaker.side else: return MESSAGE.CANNOT_WITHDRAW if outcome is not None: if outcome.result != result: return MESSAGE.HANDSHAKE_NOT_THE_SAME_RESULT if match_bl.is_exceed_dispute_time(outcome.match_id) == False: return MESSAGE.HANDSHAKE_WITHDRAW_AFTER_DISPUTE else: return MESSAGE.OUTCOME_INVALID return ''
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)
def dispute(): """ " Dispute real bet: " This step make sure user's feed will update pending status """ try: handshakes = [] shakers = [] uid = int(request.headers['Uid']) user = User.find_user_with_id(uid) data = request.json if data is None: return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA) offchain = data.get('offchain', '') if len(offchain) == 0: return response_error(MESSAGE.MISSING_OFFCHAIN, CODE.MISSING_OFFCHAIN) offchain = offchain.replace(CONST.CRYPTOSIGN_OFFCHAIN_PREFIX, '') if 'm' in offchain: offchain = int(offchain.replace('m', '')) handshake = db.session.query(Handshake).filter(and_(Handshake.id==offchain, Handshake.user_id==user.id)).first() if handshake is None: return response_error(MESSAGE.HANDSHAKE_CANNOT_REFUND, CODE.HANDSHAKE_CANNOT_REFUND) # check: handshake didn't match with any shaker if handshake.remaining_amount >= handshake.amount: return response_error(MESSAGE.HANDSHAKE_CANNOT_DISPUTE, CODE.HANDSHAKE_CANNOT_DISPUTE) handshake.bk_status = handshake.status handshake.status = HandshakeStatus['STATUS_DISPUTE_PENDING'] db.session.flush() handshakes.append(handshake) elif 's' in offchain: offchain = int(offchain.replace('s', '')) shaker = db.session.query(Shaker).filter(and_(Shaker.id==offchain, Shaker.shaker_id==user.id)).first() if shaker is None: return response_error(MESSAGE.HANDSHAKE_CANNOT_REFUND, CODE.HANDSHAKE_CANNOT_REFUND) shaker.bk_status = shaker.status shaker.status = HandshakeStatus['STATUS_DISPUTE_PENDING'] db.session.flush() shakers.append(shaker) handshake = Handshake.find_handshake_by_id(shaker.handshake_id) if handshake is None: return response_error(MESSAGE.HANDSHAKE_CANNOT_REFUND, CODE.HANDSHAKE_CANNOT_REFUND) db.session.commit() handshake_bl.update_handshakes_feed(handshakes, shakers) return response_ok() except Exception, ex: db.session.rollback() return response_error(ex.message)
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 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_find_best_odds_which_match_support_side(self): self.clear_data_before_test() arr_hs = [] # ----- handshake = Handshake(hs_type=3, chain_id=4, user_id=88, outcome_id=88, odds=1.25, amount=1, currency='ETH', side=2, 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=88, odds=1.10, amount=1, currency='ETH', side=2, remaining_amount=1, from_address='0x1234', status=0) arr_hs.append(handshake) db.session.add(handshake) db.session.commit() expected_odds = 11 expected_amount = handshake.amount * (handshake.odds - 1) actual_odds, actual_amount = match_bl.find_best_odds_which_match_support_side( 88) self.assertEqual(expected_odds, actual_odds)
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 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
def test_run_bots_for_tx_with_init_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 tx tx = Tx( contract_method='init', offchain='cryptosign_m{}'.format(handshake.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='initTestDrive', offchain='cryptosign_m{}'.format(handshake.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)
def find_all_matched_handshakes(side, odds, outcome_id, amount, maker): outcome = db.session.query(Outcome).filter( and_(Outcome.result == CONST.RESULT_TYPE['PENDING'], Outcome.id == outcome_id)).first() if outcome is not None: win_value = amount * odds if win_value - amount > 0: # calculate matched odds v = odds / (odds - 1) v = float( Decimal(str(v)).quantize(Decimal('.1'), rounding=ROUND_HALF_DOWN)) print 'matched odds --> {}'.format(v) query = text( '''SELECT * FROM handshake where outcome_id = {} and odds <= {} and remaining_amount > 0 and status = {} and side != {} ORDER BY odds ASC;''' .format(outcome_id, v, CONST.Handshake['STATUS_INITED'], side)) handshakes = [] result_db = db.engine.execute(query) for row in result_db: if (verify_taker_odds(row['odds'], odds)): if maker != row['user_id']: handshake = Handshake( id=row['id'], hs_type=row['hs_type'], extra_data=row['extra_data'], description=row['description'], chain_id=row['chain_id'], user_id=row['user_id'], outcome_id=row['outcome_id'], odds=row['odds'], amount=row['amount'], currency=row['currency'], side=row['side'], remaining_amount=row['remaining_amount'], from_address=row['from_address'], shake_count=row['shake_count'], date_created=row['date_created'], date_modified=row['date_modified']) handshakes.append(handshake) return handshakes return []
def save_collect_state_for_shaker(shaker): if shaker is not None: handshake = Handshake.find_handshake_by_id(shaker.handshake_id) outcome = Outcome.find_outcome_by_id(handshake.outcome_id) if outcome is not None: if shaker.side == outcome.result: handshake.bk_status = handshake.status handshake.status = HandshakeStatus['STATUS_DONE'] db.session.merge(handshake) db.session.flush() handshakes, shakers = save_status_all_bet_which_user_win( shaker.shaker_id, outcome) if handshakes is None: handshakes = [] handshakes.append(handshake) return handshakes, shakers return None, None
def find_available_against_handshakes(outcome_id): outcome = db.session.query(Outcome).filter( and_(Outcome.result == CONST.RESULT_TYPE['PENDING'], Outcome.id == outcome_id)).first() if outcome is not None: handshakes = db.session.query( Handshake.odds, func.sum(Handshake.remaining_amount).label('amount')).filter( and_(Handshake.side == CONST.SIDE_TYPE['OPPOSE'], Handshake.outcome_id == outcome_id, Handshake.remaining_amount > 0, Handshake.status == CONST.Handshake['STATUS_INITED'])).group_by( Handshake.odds).order_by(Handshake.odds.desc()).all() if handshakes is not None and len(handshakes) > 0: return handshakes default_handshake = Handshake(amount=Decimal('0'), odds=Decimal('2.0')) response = [] response.append(default_handshake) return response return []
def can_refund(handshake, shaker=None): if handshake is None and shaker is None: return False outcome = None if handshake is not None: if handshake.status == HandshakeStatus['STATUS_REFUNDED']: return False outcome = Outcome.find_outcome_by_id(handshake.outcome_id) else: if shaker.status == HandshakeStatus['STATUS_REFUNDED']: return False handshake = Handshake.find_handshake_by_id(shaker.handshake_id) outcome = Outcome.find_outcome_by_id(handshake.outcome_id) if outcome is not None and outcome.hid is not None: if outcome.result == CONST.RESULT_TYPE['DRAW'] or ( match_bl.is_exceed_report_time(outcome.match_id) and outcome.result == -1): return True return False
def collect_free_bet(): """ " Collect free-bet in ETH """ try: 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) offchain = data.get('offchain', '') if len(offchain) == 0: return response_error(MESSAGE.MISSING_OFFCHAIN, CODE.MISSING_OFFCHAIN) h = [] s = [] offchain = offchain.replace(CONST.CRYPTOSIGN_OFFCHAIN_PREFIX, '') if 's' in offchain: offchain = int(offchain.replace('s', '')) shaker = db.session.query(Shaker).filter(and_(Shaker.id==offchain, Shaker.shaker_id==user.id)).first() msg = handshake_bl.can_withdraw(handshake=None, shaker=shaker) if len(msg) != 0: return response_error(msg, CODE.CANNOT_WITHDRAW) hs = Handshake.find_handshake_by_id(shaker.handshake_id) outcome = Outcome.find_outcome_by_id(hs.outcome_id) # check erc20 token or not token = Token.find_token_by_id(outcome.token_id) if token is not None: return response_error(MESSAGE.HANDSHAKE_CANNOT_WITHDRAW_FREEBET_IN_ERC20, CODE.HANDSHAKE_CANNOT_WITHDRAW_FREEBET_IN_ERC20) h = db.session.query(Handshake).filter(and_(Handshake.user_id==user.id, Handshake.outcome_id==hs.outcome_id, Handshake.side==shaker.side, Handshake.status==HandshakeStatus['STATUS_INITED'])).all() s = db.session.query(Shaker).filter(and_(Shaker.shaker_id==user.id, Shaker.side==shaker.side, Shaker.status==HandshakeStatus['STATUS_SHAKER_SHAKED'], Shaker.handshake_id.in_(db.session.query(Handshake.id).filter(Handshake.outcome_id==hs.outcome_id)))).all() data['hid'] = outcome.hid data['winner'] = shaker.from_address else: offchain = int(offchain.replace('m', '')) handshake = db.session.query(Handshake).filter(and_(Handshake.id==offchain, Handshake.user_id==user.id)).first() msg = handshake_bl.can_withdraw(handshake) if len(msg) != 0: return response_error(msg, CODE.CANNOT_WITHDRAW) outcome = Outcome.find_outcome_by_id(handshake.outcome_id) # check erc20 token or not token = Token.find_token_by_id(outcome.token_id) if token is not None: return response_error(MESSAGE.HANDSHAKE_CANNOT_WITHDRAW_FREEBET_IN_ERC20, CODE.HANDSHAKE_CANNOT_WITHDRAW_FREEBET_IN_ERC20) h = db.session.query(Handshake).filter(and_(Handshake.user_id==user.id, Handshake.outcome_id==handshake.outcome_id, Handshake.side==handshake.side, Handshake.status==HandshakeStatus['STATUS_INITED'])).all() s = db.session.query(Shaker).filter(and_(Shaker.shaker_id==user.id, Shaker.side==handshake.side, Shaker.status==HandshakeStatus['STATUS_SHAKER_SHAKED'], Shaker.handshake_id.in_(db.session.query(Handshake.id).filter(Handshake.outcome_id==handshake.outcome_id)))).all() data['hid'] = outcome.hid data['winner'] = handshake.from_address handshakes = [] shakers = [] response = {} # update status for hs in h: hs.status = HandshakeStatus['STATUS_COLLECT_PENDING'] db.session.flush() handshakes.append(hs) if hs.id == offchain: response = hs.to_json() for sk in s: sk.status = HandshakeStatus['STATUS_COLLECT_PENDING'] db.session.flush() shakers.append(sk) if sk.id == offchain: response = sk.to_json() data['uid'] = uid data['payload'] = user.payload data['free_bet'] = 1 contract = Contract.find_contract_by_id(outcome.contract_id) if contract is None: return response_error(MESSAGE.CONTRACT_INVALID, CODE.CONTRACT_INVALID) # add task task = Task( task_type=CONST.TASK_TYPE['FREE_BET'], data=json.dumps(data), action=CONST.TASK_ACTION['COLLECT'], status=-1, contract_address=contract.contract_address, contract_json=contract.json_name ) db.session.add(task) db.session.commit() handshake_bl.update_handshakes_feed(handshakes, shakers) return response_ok(response) except Exception, ex: db.session.rollback() return response_error(ex.message)
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
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 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_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 test_find_all_joined_handshakes_with_side_support(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=1, remaining_amount=1, from_address='0x123', status=0 ) db.session.add(handshake) db.session.commit() # ----- handshake = Handshake( hs_type=3, chain_id=4, user_id=88, outcome_id=88, odds=1.1, amount=1, currency='ETH', side=2, remaining_amount=1, from_address='0x1234', status=0 ) db.session.add(handshake) db.session.commit() handshakes = handshake_bl.find_all_joined_handshakes( side=1, outcome_id=88) self.assertEqual(len(handshakes), 1) self.assertEqual(float(handshakes[0].odds), 1.1) # ----- handshake = Handshake( hs_type=3, chain_id=4, user_id=88, outcome_id=88, odds=1.0, amount=1, currency='ETH', side=2, remaining_amount=1, from_address='0x1234', status=0 ) db.session.add(handshake) db.session.commit() handshakes = handshake_bl.find_all_joined_handshakes( side=1, outcome_id=88) self.assertEqual(len(handshakes), 2) self.assertEqual(float(handshakes[0].odds), 1.1) self.assertEqual(float(handshakes[1].odds), 1.0)
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_find_available_against_handshakes(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.25, from_address='0x123', status=0 ) db.session.add(handshake) db.session.commit() # ----- handshake = Handshake( hs_type=3, chain_id=4, user_id=99, outcome_id=88, odds=1.2, amount=0.25, currency='ETH', side=2, remaining_amount=0.0625, from_address='0x123', status=0 ) db.session.add(handshake) db.session.commit() # ----- handshake = Handshake( hs_type=3, chain_id=4, user_id=88, outcome_id=88, odds=1.1, amount=1, currency='ETH', side=2, remaining_amount=0.10, from_address='0x1234', status=0 ) db.session.add(handshake) db.session.commit() # ----- handshake = Handshake( hs_type=3, chain_id=4, user_id=88, outcome_id=88, odds=1.1, amount=0.1, currency='ETH', side=2, remaining_amount=0.01, from_address='0x1234', status=0 ) db.session.add(handshake) db.session.commit() # ----- handshake = Handshake( hs_type=3, chain_id=4, user_id=99, outcome_id=88, odds=1.1, amount=1, currency='ETH', side=2, remaining_amount=0.1, from_address='0x12345', status=0 ) db.session.add(handshake) db.session.commit() handshakes = handshake_bl.find_available_against_handshakes( outcome_id=88) self.assertEqual(len(handshakes), 2) self.assertEqual(float(handshakes[0].amount), 0.3125) self.assertEqual(float(handshakes[1].amount), 0.21)
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 test_can_withdraw(self): self.clear_data_before_test() match = Match.find_match_by_id(1) t = datetime.now().timetuple() seconds = local_to_utc(t) if match is None: match = Match( public=1, date=seconds - 100, reportTime=seconds + 200, disputeTime=seconds + 300, source_id = source.id ) db.session.add(match) db.session.commit() else: match.date = time.time() - 100 match.disputeTime = time.time() + 200 match.reportTime = time.time() + 300 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() actual = handshake_bl.can_withdraw(None, shaker=None) self.assertNotEqual(len(actual), 0) # ----- handshake = Handshake( hs_type=3, chain_id=4, user_id=88, outcome_id=9999999, odds=1.2, amount=1, currency='ETH', side=1, remaining_amount=0, from_address='0x123', status=0 ) actual = handshake_bl.can_withdraw(handshake, shaker=None) self.assertEqual(actual, MESSAGE.OUTCOME_INVALID) # ----- 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 ) actual = handshake_bl.can_withdraw(handshake, shaker=None) self.assertEqual(actual, MESSAGE.HANDSHAKE_NOT_THE_SAME_RESULT) # ----- handshake = Handshake( hs_type=3, chain_id=4, user_id=88, outcome_id=88, odds=1.2, amount=1, currency='ETH', side=1, remaining_amount=0, from_address='0x123', status=0 ) actual = handshake_bl.can_withdraw(handshake, shaker=None) self.assertEqual(actual, MESSAGE.HANDSHAKE_WITHDRAW_AFTER_DISPUTE) match = Match.find_match_by_id(1) match.disputeTime = time.time() - 1000 match.reportTime = time.time() - 1000 db.session.commit() # ----- handshake = Handshake( hs_type=3, chain_id=4, user_id=88, outcome_id=88, odds=1.2, amount=1, currency='ETH', side=1, remaining_amount=0, from_address='0x123', status=0 ) actual = handshake_bl.can_withdraw(handshake, shaker=None) self.assertEqual(actual, '')
def test_can_refund_for_maker(self): self.clear_data_before_test() t = datetime.now().timetuple() seconds = local_to_utc(t) match = Match.find_match_by_id(1) match.disputeTime = seconds + 1100 match.reportTime = seconds + 1000 db.session.merge(match) 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) actual = handshake_bl.can_refund(handshake) expected = False self.assertEqual(actual, expected) # test cannot refund outcome = Outcome.find_outcome_by_id(88) outcome.result = 1 db.session.merge(outcome) db.session.flush() actual = handshake_bl.can_refund(handshake) expected = False self.assertEqual(actual, expected) # test refund if time exceed report time outcome.result = -1 db.session.merge(outcome) db.session.flush() match.reportTime = seconds - 2000 db.session.merge(match) db.session.commit() actual = handshake_bl.can_refund(handshake) expected = True self.assertEqual(actual, expected) for item in arr_hs: db.session.delete(item) db.session.commit()
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)