Example #1
0
    def test_create_market(self):
        oracle = CentralizedOracleFactory()
        event = CategoricalEventFactory(oracle=oracle)
        market = MarketFactory()

        block = {
            'number': market.creation_block,
            'timestamp': mktime(market.creation_date_time.timetuple())
        }

        market_dict = {
            'address':
            market.factory,
            'params': [{
                'name': 'creator',
                'value': market.creator
            }, {
                'name': 'centralizedOracle',
                'value': oracle.address,
            }, {
                'name': 'marketMaker',
                'value': market.market_maker
            }, {
                'name': 'fee',
                'value': market.fee
            }, {
                'name': 'market',
                'value': market.address
            }]
        }
        market.delete()

        s = MarketSerializer(data=market_dict, block=block)
        self.assertFalse(s.is_valid(), s.errors)

        market_dict.get('params').append({
            'name': 'eventContract',
            'value': market.address
        })

        market_dict.get('params').append({'name': 'fee', 'value': market.fee})

        s = MarketSerializer(data=market_dict, block=block)
        self.assertFalse(s.is_valid(), s.errors)

        market_dict.get('params')[-2]['value'] = event.address

        s = MarketSerializer(data=market_dict, block=block)
        self.assertFalse(s.is_valid(), s.errors)

        marketMaker = [
            x for x in market_dict.get('params')
            if x.get('name') == 'marketMaker'
        ][0]
        marketMaker.update({'value': settings.LMSR_MARKET_MAKER})

        s = MarketSerializer(data=market_dict, block=block)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()
        self.assertIsNotNone(instance)
Example #2
0
    def test_market_trading_volume(self):

        # create markets
        market = MarketFactory()

        market_response_data = self.client.get(reverse('api:markets'),
                                               content_type='application/json')
        self.assertEquals(market_response_data.status_code, status.HTTP_200_OK)
        self.assertEquals(
            len(json.loads(market_response_data.content).get('results')), 1)

        self.assertEqual(
            json.loads(
                market_response_data.content)['results'][0]['tradingVolume'],
            "0")

        market.trading_volume = 12
        market.save()

        market_response_data2 = self.client.get(
            reverse('api:markets'), content_type='application/json')
        self.assertEquals(market_response_data2.status_code,
                          status.HTTP_200_OK)
        self.assertEquals(
            len(json.loads(market_response_data2.content).get('results')), 1)

        self.assertEqual(
            json.loads(
                market_response_data2.content)['results'][0]['tradingVolume'],
            "12")
 def test_market_address_getter(self):
     getter = MarketAddressGetter()
     self.assertListEqual([], getter.get_addresses())
     market = MarketFactory.create()
     self.assertIsNotNone(market)
     self.assertTrue(getter.__contains__(market.address))
     self.assertListEqual([market.address], getter.get_addresses())
     market2 = MarketFactory.create()
     self.assertListEqual([market.address, market2.address],
                          getter.get_addresses())
Example #4
0
    def test_decimal_field_frontier_value(self):
        market = MarketFactory()
        market.funding = 2 ** 256
        market.save()

        market_response_data = self.client.get(reverse('api:markets'), content_type='application/json')
        self.assertEquals(market_response_data.status_code, status.HTTP_200_OK)
        self.assertEquals(len(json.loads(market_response_data.content).get('results')), 1)

        self.assertEqual(str(market.funding), json.loads(market_response_data.content)['results'][0]['funding'])
Example #5
0
    def test_market_receiver(self):
        oracle = CentralizedOracleFactory()
        oracle.event_description.outcomes = ['1', '2', '3']
        oracle.event_description.save()
        event = CategoricalEventFactory(oracle=oracle)
        market = MarketFactory()
        event_address = event.address

        block = {
            'number': market.creation_block,
            'timestamp': self.to_timestamp(market.creation_date_time)
        }

        market_dict = {
            'name':
            'StandardMarketCreation',
            'address':
            market.factory,
            'params': [{
                'name': 'creator',
                'value': market.creator
            }, {
                'name': 'centralizedOracle',
                'value': oracle.address,
            }, {
                'name': 'marketMaker',
                'value': market.market_maker
            }, {
                'name': 'fee',
                'value': market.fee
            }, {
                'name': 'eventContract',
                'value': event_address
            }, {
                'name': 'fee',
                'value': market.fee
            }, {
                'name': 'market',
                'value': market.address
            }]
        }

        market.delete()

        MarketFactoryReceiver().save(market_dict, block)
        with self.assertRaises(Market.DoesNotExist):
            Market.objects.get(event=event_address)

        market_dict.get('params')[2].update(
            {'value': settings.LMSR_MARKET_MAKER})
        MarketFactoryReceiver().save(market_dict, block)
        saved_market = Market.objects.get(event=event_address)
        self.assertIsNotNone(saved_market.pk)
        self.assertEquals(len(market.net_outcome_tokens_sold), 2)
        self.assertEquals(len(saved_market.net_outcome_tokens_sold), 3)
Example #6
0
    def test_market_factory_rollback(self):
        oracle = CentralizedOracleFactory()
        event = CategoricalEventFactory(oracle=oracle)
        market = MarketFactory()

        block = {
            'number': oracle.creation_block,
            'timestamp': self.to_timestamp(oracle.creation_date_time)
        }

        market_creation_event = {
            'name': 'StandardMarketCreation',
            'address': market.factory,
            'params': [
                {
                    'name': 'creator',
                    'value': market.creator
                },
                {
                    'name': 'centralizedOracle',
                    'value': oracle.address,
                },
                {
                    'name': 'marketMaker',
                    'value': settings.LMSR_MARKET_MAKER
                },
                {
                    'name': 'fee',
                    'value': market.fee
                },
                {
                    'name': 'eventContract',
                    'value': event.address
                },
                {
                    'name': 'market',
                    'value': market.address
                }
            ]
        }
        market.delete()

        MarketFactoryReceiver().save(market_creation_event, block)
        market_without_rollback = Market.objects.get(event=event.address)
        self.assertIsNotNone(market_without_rollback.pk)
        # Rollback
        MarketFactoryReceiver().rollback(market_creation_event, block)
        with self.assertRaises(Market.DoesNotExist):
            Market.objects.get(event=event.address)
Example #7
0
    def test_market_funding_rollback(self):
        market_factory = MarketFactory()
        block = {
            'number': 1,
            'timestamp': self.to_timestamp(datetime.now())
        }
        market_funding_event = {
            'name': 'MarketFunding',
            'address': market_factory.address,
            'params': [
                {
                    'name': 'funding',
                    'value': 100
                }
            ]
        }

        MarketInstanceReceiver().save(market_funding_event)
        market_without_rollback = Market.objects.get(address=market_factory.address)
        self.assertEquals(market_without_rollback.stage, 1)
        self.assertEquals(market_without_rollback.funding, 100)
        # Rollback
        MarketInstanceReceiver().rollback(market_funding_event, block)
        market_with_rollback = Market.objects.get(address=market_factory.address)
        self.assertEquals(market_with_rollback.stage, 0)
        self.assertIsNone(market_with_rollback.funding)
Example #8
0
    def test_market_trades(self):
        url = reverse('api:trades-by-market', kwargs={'market_address': '{:040d}'.format(1000)})
        trades_response = self.client.get(url, content_type='application/json')
        self.assertEquals(trades_response.status_code, status.HTTP_404_NOT_FOUND)

        # create markets
        outcome_token = OutcomeTokenFactory()
        event = outcome_token.event
        oracle = event.oracle
        market = MarketFactory(event=event)
        creation_date_time = datetime.now()

        # Create Order
        order = ShortSellOrder()
        order.creation_date_time = creation_date_time
        order.creation_block = 0
        order.market = market
        order.sender = '0x1'
        order.outcome_token = outcome_token
        order.outcome_token_count = 1
        order.cost = 1
        order.net_outcome_tokens_sold = market.net_outcome_tokens_sold
        order.marginal_prices = ["0.5000", "0.5000"]
        order.save()

        url = reverse('api:trades-by-market', kwargs={'market_address': market.address})

        trades_response = self.client.get(url, content_type='application/json')
        trades_data = json.loads(trades_response.content)
        self.assertEquals(trades_response.status_code, status.HTTP_200_OK)
        self.assertEquals(len(trades_data.get('results')), 1)
        self.assertEquals(trades_data.get('results')[0].get('marginalPrices')[0], order.marginal_prices[0])

        from_date = (creation_date_time - timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S')
        to_date = (creation_date_time + timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S')
        url = reverse('api:trades-by-market',
                      kwargs={'market_address': market.address})
        url += '?creation_date_time_0=' + from_date + '&creation_date_time_1='+to_date
        trades_response = self.client.get(url, content_type='application/json')
        self.assertEquals(trades_response.status_code, status.HTTP_200_OK)
        self.assertEquals(len(json.loads(trades_response.content).get('results')), 1)

        # test querying date with no orders
        from_date = (creation_date_time - timedelta(days=5)).strftime('%Y-%m-%d %H:%M:%S')
        to_date = (creation_date_time - timedelta(days=4)).strftime('%Y-%m-%d %H:%M:%S')
        url = reverse('api:trades-by-market',
                      kwargs={'market_address': market.address})
        url += '?creation_date_time_0=' + from_date + '&creation_date_time_1=' + to_date
        trades_response = self.client.get(url, content_type='application/json')
        self.assertEquals(trades_response.status_code, status.HTTP_200_OK)
        self.assertEquals(len(json.loads(trades_response.content).get('results')), 0)

        # test querying date passing only the from param
        from_date = (creation_date_time - timedelta(days=5)).strftime('%Y-%m-%d %H:%M:%S')
        url = reverse('api:trades-by-market',
                      kwargs={'market_address': market.address})
        url += '?creation_date_time_0=' + from_date
        trades_response = self.client.get(url, content_type='application/json')
        self.assertEquals(trades_response.status_code, status.HTTP_200_OK)
        self.assertEquals(len(json.loads(trades_response.content).get('results')), 1)
Example #9
0
    def test_market_participant_history(self):
        outcome_token = OutcomeTokenFactory()
        event = outcome_token.event
        oracle = event.oracle
        market = MarketFactory(event=event)
        creation_date_time = datetime.now()
        sender_address = '{:040d}'.format(100)

        response = self.client.get(
            reverse('api:trades-by-owner', kwargs={'market_address': market.address, 'owner_address': sender_address}),
            content_type='application/json'
        )
        self.assertEquals(response.status_code, status.HTTP_200_OK)
        self.assertEquals(len(json.loads(response.content).get('results')), 0)

        # Buy Order
        BuyOrderFactory(market=market, sender=sender_address)
        BuyOrderFactory(market=market, sender=sender_address)

        response = self.client.get(
            reverse('api:trades-by-owner', kwargs={'market_address': market.address, 'owner_address': sender_address}),
            content_type='application/json'
        )
        self.assertEquals(response.status_code, status.HTTP_200_OK)
        self.assertEquals(len(json.loads(response.content).get('results')), 2)
Example #10
0
    def test_shares_by_account(self):
        account1 = '{:040d}'.format(13)
        account2 = '{:040d}'.format(14)

        url = reverse('api:shares-by-account', kwargs={'account_address': account1})
        empty_shares_response = self.client.get(url, content_type='application/json')
        self.assertEquals(len(json.loads(empty_shares_response.content).get('results')), 0)

        oracle = CentralizedOracleFactory()
        event = CategoricalEventFactory(oracle=oracle)
        market = MarketFactory(event=event, creator=account1)
        outcome_token = OutcomeTokenFactory(event=market.event)
        OutcomeTokenBalanceFactory(owner=market.creator, outcome_token=outcome_token)
        BuyOrderFactory(outcome_token=outcome_token, sender=account1, market=market)

        url = reverse('api:shares-by-account', kwargs={'account_address': account1})
        shares_response = self.client.get(url, content_type='application/json')
        decoded_response = json.loads(shares_response.content)
        self.assertEquals(len(decoded_response.get('results')), 1)
        self.assertEquals(
            decoded_response.get('results')[0].get('eventDescription').get('title'),
            oracle.event_description.title
        )
        self.assertEquals(
            decoded_response.get('results')[0].get('marginalPrice'),
            0.5
        )

        url = reverse('api:shares-by-account', kwargs={'account_address': account2})
        no_shares_response = self.client.get(url, content_type='application/json')
        self.assertEquals(len(json.loads(no_shares_response.content).get('results')), 0)
Example #11
0
    def test_markets_with_event_description(self):
        # test empty events response
        empty_markets_response = self.client.get(
            reverse('api:markets'), content_type='application/json')
        self.assertEquals(
            len(json.loads(empty_markets_response.content).get('results')), 0)

        # create markets
        oracle = CentralizedOracleFactory()
        event = CategoricalEventFactory(oracle=oracle)
        market = MarketFactory(event=event)

        market_response_data = self.client.get(reverse('api:markets'),
                                               content_type='application/json')
        self.assertEquals(market_response_data.status_code, status.HTTP_200_OK)
        results = json.loads(market_response_data.content).get('results')
        self.assertEquals(len(results), 1)

        self.assertIsNotNone(
            results[0]['event']['oracle'].get('eventDescription'))
        self.assertIsNotNone(
            results[0]['event']['oracle']['eventDescription'].get('ipfsHash'))
        self.assertEqual(
            results[0]['event']['oracle']['eventDescription']['ipfsHash'],
            oracle.event_description.ipfs_hash)
Example #12
0
    def test_market_history(self):
        # create markets
        outcome_token = OutcomeTokenFactory()
        event = outcome_token.event
        oracle = event.oracle
        market = MarketFactory(event=event)
        creation_date_time = datetime.now()

        # Create Order
        order = ShortSellOrder()
        order.creation_date_time = creation_date_time
        order.creation_block = 0
        order.market = market
        order.sender = '0x1'
        order.outcome_token = outcome_token
        order.outcome_token_count = 1
        order.cost = 1
        order.net_outcome_tokens_sold = market.net_outcome_tokens_sold
        order.save()

        url = reverse('api:history-by-market') + '?market=' + market.address
        history_data = self.client.get(url, content_type='application/json')
        self.assertEquals(history_data.status_code, status.HTTP_200_OK)
        self.assertEquals(len(json.loads(history_data.content).get('results')),
                          1)

        from_date = (creation_date_time -
                     timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S')
        to_date = (creation_date_time +
                   timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S')
        url = reverse(
            'api:history-by-market'
        ) + '?market=' + market.address + '&from=' + from_date + '&to=' + to_date
        history_data = self.client.get(url, content_type='application/json')
        self.assertEquals(history_data.status_code, status.HTTP_200_OK)
        self.assertEquals(len(json.loads(history_data.content).get('results')),
                          1)

        # test querying date with no orders
        from_date = (creation_date_time -
                     timedelta(days=5)).strftime('%Y-%m-%d %H:%M:%S')
        to_date = (creation_date_time -
                   timedelta(days=4)).strftime('%Y-%m-%d %H:%M:%S')
        url = reverse(
            'api:history-by-market'
        ) + '?market=' + market.address + '&from=' + from_date + '&to=' + to_date
        history_data = self.client.get(url, content_type='application/json')
        self.assertEquals(history_data.status_code, status.HTTP_200_OK)
        self.assertEquals(len(json.loads(history_data.content).get('results')),
                          0)

        # test querying date passing only the from param
        from_date = (creation_date_time -
                     timedelta(days=5)).strftime('%Y-%m-%d %H:%M:%S')
        url = reverse('api:history-by-market'
                      ) + '?market=' + market.address + '&from=' + from_date
        history_data = self.client.get(url, content_type='application/json')
        self.assertEquals(history_data.status_code, status.HTTP_200_OK)
        self.assertEquals(len(json.loads(history_data.content).get('results')),
                          1)
Example #13
0
    def test_shares_by_owner(self):
        market = MarketFactory()
        response = self.client.get(reverse('api:shares-by-owner',
                                           kwargs={
                                               'market_address':
                                               market.address,
                                               'owner_address': market.creator
                                           }),
                                   content_type='application/json')
        self.assertEquals(response.status_code, status.HTTP_200_OK)
        self.assertEquals(len(json.loads(response.content).get('results')), 0)

        outcome_token = OutcomeTokenFactory(event=market.event)
        outcome_token2 = OutcomeTokenFactory(event=market.event)
        OutcomeTokenBalanceFactory(owner=market.creator,
                                   outcome_token=outcome_token)
        response = self.client.get(reverse('api:shares-by-owner',
                                           kwargs={
                                               'market_address':
                                               market.address,
                                               'owner_address': market.creator
                                           }),
                                   content_type='application/json')
        self.assertEquals(response.status_code, status.HTTP_200_OK)
        self.assertEquals(len(json.loads(response.content).get('results')), 1)
Example #14
0
    def test_markets_by_resolution_date(self):
        # test empty events response
        empty_markets_response = self.client.get(
            reverse('api:markets'), content_type='application/json')
        self.assertEquals(
            len(json.loads(empty_markets_response.content).get('results')), 0)

        oracle = CentralizedOracleFactory()
        event = CategoricalEventFactory(oracle=oracle)
        market = MarketFactory(event=event)
        from_date = (datetime.now() -
                     timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S')

        url = reverse('api:markets') + '?resolution_date_time_0=' + from_date
        correct_date_time_range_response = self.client.get(
            url, content_type='application/json')
        self.assertEquals(
            len(
                json.loads(
                    correct_date_time_range_response.content).get('results')),
            1)

        url = reverse(
            'api:markets'
        ) + '?resolution_date_time_0=' + from_date + '&resolution_date_time_1=' + from_date
        empty_date_time_range_response = self.client.get(
            url, content_type='application/json')
        self.assertEquals(
            len(
                json.loads(
                    empty_date_time_range_response.content).get('results')), 0)
Example #15
0
 def test_market_trades_unknown_market(self):
     market = MarketFactory()
     url = reverse('api:trades-by-market',
                   kwargs={'market_address': market.address})
     history_data = self.client.get(url, content_type='application/json')
     self.assertEquals(history_data.status_code, status.HTTP_200_OK)
     self.assertEquals(len(json.loads(history_data.content).get('results')),
                       0)
Example #16
0
    def test_market_outcome_token_purchase_rollback(self):
        oracle_factory = CentralizedOracleFactory()
        event_factory = CategoricalEventFactory(oracle=oracle_factory)
        outcome_token = OutcomeTokenFactory(event=event_factory, index=0)
        market_without_rollback = MarketFactory(event=event_factory)
        buyer_address = '{:040d}'.format(100)
        self.assertIsNotNone(market_without_rollback.pk)

        block = {
            'number': oracle_factory.creation_block,
            'timestamp': self.to_timestamp(oracle_factory.creation_date_time)
        }

        outcome_token_purchase_event = {
            'name':
            'OutcomeTokenPurchase',
            'address':
            market_without_rollback.address,
            'params': [
                {
                    'name': 'outcomeTokenCost',
                    'value': 100
                },
                {
                    'name': 'marketFees',
                    'value': 10
                },
                {
                    'name': 'buyer',
                    'value': buyer_address
                },
                {
                    'name': 'outcomeTokenIndex',
                    'value': 0
                },
                {
                    'name': 'outcomeTokenCount',
                    'value': 10
                },
            ]
        }

        # Send outcome token purchase event
        MarketInstanceReceiver().save(outcome_token_purchase_event, block)
        orders_before_rollback = BuyOrder.objects.filter(
            creation_block=block.get('number'),
            sender=buyer_address,
            market=market_without_rollback)
        self.assertEquals(len(orders_before_rollback), 1)

        # Outcome token purchase rollback
        MarketInstanceReceiver().rollback(outcome_token_purchase_event, block)
        market_with_rollback = Market.objects.get(event=event_factory.address)
        orders_after_rollback = BuyOrder.objects.filter(
            creation_block=block.get('number'),
            sender=buyer_address,
            market=market_with_rollback)
        self.assertEquals(len(orders_after_rollback), 0)
Example #17
0
    def test_market_closing_receiver(self):
        market_factory = MarketFactory()
        closing_event = {
            'name': 'MarketClosing',
            'address': market_factory.address,
            'params': []
        }

        MarketInstanceReceiver().save(closing_event)
        market = Market.objects.get(address=market_factory.address)
        self.assertEquals(market.stage, 2)
Example #18
0
    def test_market_marginal_prices(self):
        oracle = CentralizedOracleFactory()
        categorical_event = CategoricalEventFactory(oracle=oracle)
        outcome_token = OutcomeTokenFactory(event=categorical_event)
        market = MarketFactory(event=categorical_event)
        sender_address = '{:040d}'.format(100)

        # Buy Order
        order_one = BuyOrderFactory(market=market, sender=sender_address)
        order_two = BuyOrderFactory(market=market, sender=sender_address)
        market_response = self.client.get(reverse('api:markets-by-name', kwargs={'market_address': market.address}), content_type='application/json')
        market_data = json.loads(market_response.content)
        self.assertEquals(market_data.get('marginalPrices'), order_two.marginal_prices)
Example #19
0
    def test_calc_lmsr_marginal_price(self):
        outcomeTokenIndex = 0
        outcomeTokenCount = 1e18
        # create markets
        outcome_token = OutcomeTokenFactory()
        event = outcome_token.event
        market = MarketFactory(event=event)

        net_outcome_tokens_sold = [0, 1]  # market.net_outcome_tokens_sold
        result = calc_lmsr_marginal_price(1, net_outcome_tokens_sold,
                                          market.funding)
        self.assertIsNotNone(result)
        self.assertTrue(result > 0)
Example #20
0
    def test_collected_fees(self):
        categorical_event = CategoricalEventFactory()
        outcome_token = OutcomeTokenFactory(event=categorical_event, index=0)
        market = MarketFactory(event=categorical_event)
        sender_address = '{:040d}'.format(100)
        fees = 10

        outcome_token_purchase_event = {
            'name':
            'OutcomeTokenPurchase',
            'address':
            market.address,
            'params': [
                {
                    'name': 'outcomeTokenCost',
                    'value': 100
                },
                {
                    'name': 'marketFees',
                    'value': fees
                },
                {
                    'name': 'buyer',
                    'value': sender_address
                },
                {
                    'name': 'outcomeTokenIndex',
                    'value': 0
                },
                {
                    'name': 'outcomeTokenCount',
                    'value': 10
                },
            ]
        }

        block = {'number': 1, 'timestamp': self.to_timestamp(datetime.now())}

        # Save event
        MarketInstanceReceiver().save(outcome_token_purchase_event, block)
        # Check that collected fees was incremented
        market_check = Market.objects.get(address=market.address)
        self.assertEquals(market_check.collected_fees,
                          market.collected_fees + fees)

        block.update({'number': 2})
        MarketInstanceReceiver().save(outcome_token_purchase_event, block)
        market_check = Market.objects.get(address=market.address)
        self.assertEquals(market_check.collected_fees,
                          market.collected_fees + fees + fees)
Example #21
0
    def test_market_funding_receiver(self):
        market_factory = MarketFactory()
        funding_event = {
            'name': 'MarketFunding',
            'address': market_factory.address,
            'params': [{
                'name': 'funding',
                'value': 100
            }]
        }

        MarketInstanceReceiver().save(funding_event)
        market = Market.objects.get(address=market_factory.address)
        self.assertEquals(market.stage, 1)
        self.assertEquals(market.funding, 100)
Example #22
0
    def test_market_fee_withdrawal_receiver(self):
        market_factory = MarketFactory()
        withdraw_event = {
            'name': 'FeeWithdrawal',
            'address': market_factory.address,
            'params': [{
                'name': 'fees',
                'value': 10
            }]
        }

        MarketInstanceReceiver().save(withdraw_event)
        market = Market.objects.get(address=market_factory.address)
        # self.assertEquals(market.stage, 3)
        self.assertEquals(market.withdrawn_fees,
                          market_factory.withdrawn_fees + 10)
Example #23
0
    def test_markets(self):
        # test empty events response
        empty_markets_response = self.client.get(
            reverse('api:markets'), content_type='application/json')
        self.assertEquals(
            len(json.loads(empty_markets_response.content).get('results')), 0)

        # create markets
        markets = [MarketFactory() for x in range(0, 10)]
        marketsdb = Market.objects.all()
        self.assertEquals(len(markets), marketsdb.count())

        market_response_data = self.client.get(reverse('api:markets'),
                                               content_type='application/json')
        self.assertEquals(market_response_data.status_code, status.HTTP_200_OK)
        self.assertEquals(
            len(json.loads(market_response_data.content).get('results')),
            len(markets))

        market_search_response = self.client.get(
            reverse('api:markets-by-name',
                    kwargs={'market_address': markets[0].address}),
            content_type='application/json')
        self.assertEquals(market_search_response.status_code,
                          status.HTTP_200_OK)
        self.assertEquals(
            json.loads(
                market_search_response.content).get('contract').get('creator'),
            add_0x_prefix(markets[0].creator))
        # test empty response
        market_empty_search_response = self.client.get(
            reverse('api:markets-by-name',
                    kwargs={'market_address': "abcdef0"}),
            content_type='application/json')
        self.assertEquals(market_empty_search_response.status_code,
                          status.HTTP_404_NOT_FOUND)

        market_search_response = self.client.get(
            reverse('api:markets-by-name',
                    kwargs={'market_address': markets[0].address}),
            content_type='application/json')
        self.assertEquals(market_search_response.status_code,
                          status.HTTP_200_OK)
        self.assertEquals(
            json.loads(
                market_search_response.content).get('contract').get('address'),
            add_0x_prefix(markets[0].address))
Example #24
0
    def test_outcome_token_purchase_marginal_price(self):
        categorical_event = CategoricalEventFactory()
        OutcomeTokenFactory(event=categorical_event, index=0)
        OutcomeTokenFactory(event=categorical_event, index=1)
        market = MarketFactory(event=categorical_event,
                               funding=1e18,
                               net_outcome_tokens_sold=[0, 0])
        sender_address = '{:040d}'.format(100)

        outcome_token_purchase_event = {
            'name':
            'OutcomeTokenPurchase',
            'address':
            market.address,
            'params': [
                {
                    'name': 'outcomeTokenCost',
                    'value': 1000000000000000000
                },
                {
                    'name': 'marketFees',
                    'value': 0
                },
                {
                    'name': 'buyer',
                    'value': sender_address
                },
                {
                    'name': 'outcomeTokenIndex',
                    'value': 0
                },
                {
                    'name': 'outcomeTokenCount',
                    'value': 1584900000000000000
                },
            ]
        }

        block = {'number': 1, 'timestamp': self.to_timestamp(datetime.now())}

        self.assertEquals(BuyOrder.objects.all().count(), 0)
        MarketInstanceReceiver().save(outcome_token_purchase_event, block)
        buy_orders = BuyOrder.objects.all()
        self.assertEquals(buy_orders.count(), 1)
        self.assertListEqual(
            buy_orders[0].marginal_prices,
            [Decimal(0.7500), Decimal(0.2500)])  # outcomeTokenCost+fee
Example #25
0
    def test_market_outcome_token_sale_rollback(self):
        categorical_event = CategoricalEventFactory()
        outcome_token = OutcomeTokenFactory(event=categorical_event, index=0)
        market = MarketFactory(event=categorical_event)
        seller_address = '{:040d}'.format(100)

        block = {'number': 1, 'timestamp': self.to_timestamp(datetime.now())}
        outcome_token_sell_event = {
            'name':
            'OutcomeTokenSale',
            'address':
            market.address,
            'params': [
                {
                    'name': 'outcomeTokenProfit',
                    'value': 100
                },
                {
                    'name': 'marketFees',
                    'value': 10
                },
                {
                    'name': 'seller',
                    'value': seller_address
                },
                {
                    'name': 'outcomeTokenIndex',
                    'value': 0
                },
                {
                    'name': 'outcomeTokenCount',
                    'value': 10
                },
            ]
        }

        MarketInstanceReceiver().save(outcome_token_sell_event, block)
        orders_before_rollback = SellOrder.objects.filter(
            creation_block=block.get('number'), sender=seller_address)
        self.assertEquals(len(orders_before_rollback), 1)

        # Outcome token sell rollback
        MarketInstanceReceiver().rollback(outcome_token_sell_event, block)
        orders_before_rollback = SellOrder.objects.filter(
            creation_block=block.get('number'), sender=seller_address)
        self.assertEquals(len(orders_before_rollback), 0)
Example #26
0
    def test_outcome_token_purchase(self):
        categorical_event = CategoricalEventFactory()
        outcome_token = OutcomeTokenFactory(event=categorical_event, index=0)
        market = MarketFactory(event=categorical_event)
        sender_address = '{:040d}'.format(100)

        outcome_token_purchase_event = {
            'name':
            'OutcomeTokenPurchase',
            'address':
            market.address,
            'params': [
                {
                    'name': 'outcomeTokenCost',
                    'value': 100
                },
                {
                    'name': 'marketFees',
                    'value': 10
                },
                {
                    'name': 'buyer',
                    'value': sender_address
                },
                {
                    'name': 'outcomeTokenIndex',
                    'value': 0
                },
                {
                    'name': 'outcomeTokenCount',
                    'value': 10
                },
            ]
        }

        block = {'number': 1, 'timestamp': self.to_timestamp(datetime.now())}

        self.assertEquals(BuyOrder.objects.all().count(), 0)
        MarketInstanceReceiver().save(outcome_token_purchase_event, block)
        buy_orders = BuyOrder.objects.all()
        self.assertEquals(buy_orders.count(), 1)
        self.assertEquals(buy_orders[0].cost, 110)  # outcomeTokenCost+fee
Example #27
0
    def test_outcome_token_sell(self):
        categorical_event = CategoricalEventFactory()
        outcome_token = OutcomeTokenFactory(event=categorical_event, index=0)
        market = MarketFactory(event=categorical_event)
        sender_address = '{:040d}'.format(100)

        outcome_token_sell_event = {
            'name':
            'OutcomeTokenSale',
            'address':
            market.address,
            'params': [
                {
                    'name': 'outcomeTokenProfit',
                    'value': 100
                },
                {
                    'name': 'marketFees',
                    'value': 10
                },
                {
                    'name': 'seller',
                    'value': sender_address
                },
                {
                    'name': 'outcomeTokenIndex',
                    'value': 0
                },
                {
                    'name': 'outcomeTokenCount',
                    'value': 10
                },
            ]
        }

        block = {'number': 1, 'timestamp': self.to_timestamp(datetime.now())}

        self.assertEquals(SellOrder.objects.all().count(), 0)
        MarketInstanceReceiver().save(outcome_token_sell_event, block)
        sell_orders = SellOrder.objects.all()
        self.assertEquals(sell_orders.count(), 1)
        self.assertEquals(sell_orders[0].profit, 90)  # outcomeTokenProfit-fee
Example #28
0
    def test_market_participant_history(self):
        outcome_token = OutcomeTokenFactory()
        event = outcome_token.event
        oracle = event.oracle
        market = MarketFactory(event=event)
        creation_date_time = datetime.now()
        sender_address = '{:040d}'.format(100)

        response = self.client.get(reverse('api:trades-by-owner',
                                           kwargs={
                                               'market_address':
                                               market.address,
                                               'owner_address': sender_address
                                           }),
                                   content_type='application/json')
        self.assertEquals(response.status_code, status.HTTP_200_OK)
        self.assertEquals(len(json.loads(response.content).get('results')), 0)

        # Create Order
        order = ShortSellOrder()
        order.creation_date_time = creation_date_time
        order.creation_block = 0
        order.market = market
        order.sender = sender_address
        order.outcome_token = outcome_token
        order.outcome_token_count = 1
        order.cost = 1
        order.net_outcome_tokens_sold = market.net_outcome_tokens_sold
        order.save()

        response = self.client.get(reverse('api:trades-by-owner',
                                           kwargs={
                                               'market_address':
                                               market.address,
                                               'owner_address': sender_address
                                           }),
                                   content_type='application/json')
        self.assertEquals(response.status_code, status.HTTP_200_OK)
        self.assertEquals(len(json.loads(response.content).get('results')), 1)
Example #29
0
    def test_market_fee_withdrawal_rollback(self):
        market_factory = MarketFactory()
        block = {'number': 1, 'timestamp': self.to_timestamp(datetime.now())}
        market_withdraw_event = {
            'name': 'FeeWithdrawal',
            'address': market_factory.address,
            'params': [{
                'name': 'fees',
                'value': 10
            }]
        }

        MarketInstanceReceiver().save(market_withdraw_event)
        market_without_rollback = Market.objects.get(
            address=market_factory.address)
        self.assertEquals(market_without_rollback.withdrawn_fees,
                          market_factory.withdrawn_fees + 10)
        # Rollback
        MarketInstanceReceiver().rollback(market_withdraw_event, block)
        market_with_rollback = Market.objects.get(
            address=market_factory.address)
        self.assertEquals(market_with_rollback.withdrawn_fees,
                          market_factory.withdrawn_fees)
Example #30
0
 def test_history_unknown_market(self):
     market = MarketFactory()
     url = reverse('api:history-by-market') + '?market=' + market.address
     history_data = self.client.get(url, content_type='application/json')
     self.assertEquals(history_data.status_code, status.HTTP_404_NOT_FOUND)