예제 #1
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.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(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.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(json.loads(response.content).get('results')), 1)
예제 #2
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.assertEqual(BuyOrder.objects.all().count(), 0)
        MarketInstanceReceiver().save(outcome_token_purchase_event, block)
        buy_orders = BuyOrder.objects.all()
        self.assertEqual(buy_orders.count(), 1)
        self.assertListEqual(buy_orders[0].marginal_prices, [Decimal(0.7500), Decimal(0.2500)])  # outcomeTokenCost+fee
예제 #3
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.assertEqual(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.assertEqual(market_check.collected_fees, market.collected_fees+fees+fees)
예제 #4
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.assertEqual(SellOrder.objects.all().count(), 0)
        MarketInstanceReceiver().save(outcome_token_sell_event, block)
        sell_orders = SellOrder.objects.all()
        self.assertEqual(sell_orders.count(), 1)
        self.assertEqual(sell_orders[0].profit, 90) # outcomeTokenProfit-fee
예제 #5
0
    def test_event_instance_revocation_receiver(self):
        outcome_token = OutcomeTokenFactory()
        revocation_event = {
            'name': 'Revocation',
            'address': outcome_token.address,
            'params': [
                {
                    'name': 'owner',
                    'value': outcome_token.event.creator
                },
                {
                    'name': 'amount',
                    'value': 1000,
                }
            ]
        }

        issuance_event = revocation_event.copy()
        issuance_event.update({'name': 'Issuance'})

        # do issuance
        OutcomeTokenInstanceReceiver().save(issuance_event)
        # do revocation
        OutcomeTokenInstanceReceiver().save(revocation_event)
        outcome_token_saved = OutcomeToken.objects.get(address= outcome_token.address)
        self.assertIsNotNone(outcome_token_saved.pk)
        self.assertEqual(outcome_token.total_supply, outcome_token_saved.total_supply)
예제 #6
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.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(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.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(json.loads(response.content).get('results')), 2)
예제 #7
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.assertEqual(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.assertEqual(len(orders_after_rollback), 0)
예제 #8
0
    def test_outcome_token_transfer_rollback(self):
        outcome_token_factory = OutcomeTokenFactory()
        owner_one = outcome_token_factory.address[0:-5] + 'other'
        owner_two = outcome_token_factory.address[0:-2] + 'to'
        block = {'number': 1, 'timestamp': self.to_timestamp(datetime.now())}
        issuance_event = {
            'name':
            'Issuance',
            'address':
            outcome_token_factory.address,
            'params': [{
                'name': 'owner',
                'value': owner_one
            }, {
                'name': 'amount',
                'value': 1000
            }]
        }
        transfer_event = {
            'name':
            'Transfer',
            'address':
            outcome_token_factory.address,
            'params': [{
                'name': 'from',
                'value': owner_one
            }, {
                'name': 'to',
                'value': owner_two
            }, {
                'name': 'value',
                'value': 10
            }]
        }

        OutcomeTokenInstanceReceiver().save(issuance_event)
        OutcomeTokenInstanceReceiver().save(transfer_event)
        outcome_token_balance_before_rollback = OutcomeTokenBalance.objects.get(
            owner=owner_two)
        self.assertEqual(outcome_token_balance_before_rollback.balance, 10)

        # Rollback
        OutcomeTokenInstanceReceiver().rollback(transfer_event, block)
        with self.assertRaises(OutcomeTokenBalance.DoesNotExist):
            OutcomeTokenBalance.objects.get(owner=owner_two)

        # Test with funds on owner2
        OutcomeTokenInstanceReceiver().save(issuance_event)
        isuance_event_owner_two = issuance_event.copy()
        isuance_event_owner_two.get('params')[0]['value'] = owner_two
        OutcomeTokenInstanceReceiver().save(isuance_event_owner_two)
        OutcomeTokenInstanceReceiver().save(transfer_event)
        OutcomeTokenInstanceReceiver().rollback(transfer_event, block)
        owner_two_token_balance = OutcomeTokenBalance.objects.get(
            owner=owner_two)
        self.assertEqual(owner_two_token_balance.balance, 1000)
예제 #9
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)
예제 #10
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.assertEqual(market_data.get('marginalPrices'),
                         order_two.marginal_prices)
예제 #11
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.assertEqual(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.assertEqual(len(orders_before_rollback), 0)
예제 #12
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.assertEqual(
            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.assertEqual(len(decoded_response.get('results')), 1)
        self.assertEqual(
            decoded_response.get('results')[0].get('eventDescription').get(
                'title'), oracle.event_description.title)
        self.assertEqual(
            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.assertEqual(
            len(json.loads(no_shares_response.content).get('results')), 0)
예제 #13
0
    def test_event_instance_issuance_receiver(self):
        outcome_token = OutcomeTokenFactory()
        event = {
            'name': 'Issuance',
            'address': outcome_token.address,
            'params': [
                {
                    'name': 'owner',
                    'value': outcome_token.event.creator
                },
                {
                    'name': 'amount',
                    'value': 1000,
                }
            ]
        }

        OutcomeTokenInstanceReceiver().save(event)
        outcome_token_saved = OutcomeToken.objects.get(address=outcome_token.address)
        self.assertIsNotNone(outcome_token_saved.pk)
        self.assertEqual(outcome_token.total_supply + 1000, outcome_token_saved.total_supply)
        outcome_token_balance = OutcomeTokenBalance.objects.get(owner=outcome_token.event.creator)
        self.assertIsNotNone(outcome_token_balance.pk)
        self.assertEqual(outcome_token_balance.balance, 1000)
예제 #14
0
    def test_event_instance_receiver(self):
        outcome_token = OutcomeTokenFactory()
        oracle = OracleFactory()
        event = ScalarEventFactory()
        event_address = event.address

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

        scalar_event = {
            'name': 'ScalarEventCreation',
            'address': event.factory,
            'params': [
                {
                    'name': 'creator',
                    'value': event.creator
                },
                {
                    'name': 'collateralToken',
                    'value': event.collateral_token
                },
                {
                    'name': 'oracle',
                    'value': oracle.address
                },
                {
                    'name': 'outcomeCount',
                    'value': 2
                },
                {
                    'name': 'upperBound',
                    'value': event.upper_bound
                },
                {
                    'name': 'lowerBound',
                    'value': event.lower_bound
                },
                {
                    'name': 'scalarEvent',
                    'value': event_address
                }
            ]
        }
        event.delete()

        EventFactoryReceiver().save(scalar_event, block)
        event = ScalarEvent.objects.get(address=event_address)

        block = {
            'number': event.creation_block,
            'timestamp': mktime(event.creation_date_time.timetuple())
        }
        outcome_token_address = outcome_token.address
        outcome_event = {
            'name': 'OutcomeTokenCreation',
            'address': event_address,
            'params': [
                {
                    'name': 'outcomeToken',
                    'value': outcome_token_address,
                },
                {
                    'name': 'index',
                    'value': outcome_token.index
                }
            ]
        }
        outcome_token.delete()
        EventInstanceReceiver().save(outcome_event, block)
        self.assertIsNotNone(OutcomeToken.objects.get(address=outcome_token_address))
예제 #15
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.assertEqual(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.assertEqual(trades_response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(trades_data.get('results')), 1)
        self.assertEqual(
            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.assertEqual(trades_response.status_code, status.HTTP_200_OK)
        self.assertEqual(
            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.assertEqual(trades_response.status_code, status.HTTP_200_OK)
        self.assertEqual(
            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.assertEqual(trades_response.status_code, status.HTTP_200_OK)
        self.assertEqual(
            len(json.loads(trades_response.content).get('results')), 1)