Esempio n. 1
0
    def test_ipfs(self):
        json_data = {"name": "giacomo"}
        ipfs = Ipfs()
        # create an ipfs object
        ipfs_hash = ipfs.post(json_data)
        # retrieve ipfs object
        ipfs_json_data = ipfs.get(ipfs_hash)
        self.assertEquals(json_data.get("name"), ipfs_json_data.get("name"))

        with self.assertRaises(ErrorResponse):
            ipfs.get("invalidhash")
Esempio n. 2
0
class TestEventReceiver(TestCase):

    def setUp(self):
        self.ipfs_api = Ipfs()

    def to_timestamp(self, datetime_instance):
        return mktime(datetime_instance.timetuple())

    def test_centralized_oracle_receiver(self):
        oracle = CentralizedOracleFactory()
        # saving event_description to IPFS
        event_description_json = {
            'title': oracle.event_description.title,
            'description': oracle.event_description.description,
            'resolutionDate': oracle.event_description.resolution_date.isoformat(),
            'outcomes': oracle.event_description.outcomes
        }

        ipfs_hash = self.ipfs_api.post(event_description_json)

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

        oracle_address = oracle.address
        oracle_event = {
            'name': 'CentralizedOracleCreation',
            'address': oracle.factory,
            'params': [
                {
                    'name': 'creator',
                    'value': oracle.creator
                },
                {
                    'name': 'centralizedOracle',
                    'value': oracle_address,
                },
                {
                    'name': 'ipfsHash',
                    'value': ipfs_hash
                }
            ]
        }
        oracle.delete()
        CentralizedOracleFactoryReceiver().save(oracle_event, block)
        saved_oracle1 = CentralizedOracle.objects.get(address=oracle_address)
        self.assertIsNotNone(saved_oracle1.pk)

        # Cannot save twice
        oracle2 = CentralizedOracleFactory()
        oracle_event.get('params')[0].update({'value': oracle2.creator})
        oracle_event.get('params')[2].update({'value': oracle2.event_description.ipfs_hash})
        instance = CentralizedOracleFactoryReceiver().save(oracle_event, block)
        self.assertIsNone(instance)
        saved_oracle2 = CentralizedOracle.objects.get(address=oracle_address)
        self.assertEqual(saved_oracle1.event_description.ipfs_hash, saved_oracle2.event_description.ipfs_hash)
        self.assertEqual(saved_oracle1.creator, saved_oracle2.creator)

    def test_scalar_event_receiver(self):
        oracle = OracleFactory()
        event = ScalarEventFactory()
        event_address = event.address

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

        scalar_event = {
            'address': event.factory,
            'name': 'ScalarEventCreation',
            '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)
        self.assertIsNotNone(event.pk)

    def test_categorical_event_receiver(self):
        event = CategoricalEventFactory()
        oracle = OracleFactory()
        event_address = event.address

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

        categorical_event = {
            'address': event.factory,
            'name': 'CategoricalEventCreation',
            'params': [
                {
                    'name': 'creator',
                    'value': event.creator
                },
                {
                    'name': 'collateralToken',
                    'value': event.collateral_token
                },
                {
                    'name': 'oracle',
                    'value': oracle.address
                },
                {
                    'name': 'outcomeCount',
                    'value': 2
                },
                {
                    'name': 'categoricalEvent',
                    'value': event_address
                }
            ]
        }
        event.delete()

        EventFactoryReceiver().save(categorical_event, block)
        event = CategoricalEvent.objects.get(address=event_address)
        self.assertIsNotNone(event.pk)

    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.assertEqual(len(market.net_outcome_tokens_sold), 2)
        self.assertEqual(len(saved_market.net_outcome_tokens_sold), 3)

    #
    # contract instances
    #
    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))

    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)

    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)

    def test_event_instance_outcome_assignment_receiver(self):
        event = CategoricalEventFactory()
        assignment_event = {
            'name': 'OutcomeAssignment',
            'address': event.address,
            'params': [{
                'name': 'outcome',
                'value': 1,
            }]
        }

        EventInstanceReceiver().save(assignment_event)
        saved_event = Event.objects.get(address=event.address)
        self.assertTrue(saved_event.is_winning_outcome_set)

    def test_event_instance_winnings_redemption_receiver(self):
        event = CategoricalEventFactory()
        redemption_event = {
            'name': 'WinningsRedemption',
            'address': event.address,
            'params': [
                {
                    'name': 'receiver',
                    'value': event.creator,
                },
                {
                    'name': 'winnings',
                    'value': 1
                }
            ]
        }

        EventInstanceReceiver().save(redemption_event)
        saved_event = Event.objects.get(address=event.address)
        self.assertEqual(saved_event.redeemed_winnings, event.redeemed_winnings + 1)

    def test_centralized_oracle_instance_owner_replacement_receiver(self):
        oracle0 = CentralizedOracleFactory()
        oracle1 = CentralizedOracleFactory()
        new_owner = oracle1.address
        change_owner_event = {
            'name': 'OwnerReplacement',
            'address': oracle0.address,
            'params': [
                {
                    'name': 'newOwner',
                    'value': new_owner
                }
            ]
        }

        CentralizedOracleInstanceReceiver().save(change_owner_event)
        saved_oracle = CentralizedOracle.objects.get(address=oracle0.address)
        self.assertEqual(saved_oracle.owner, new_owner)

    def test_centralized_oracle_instance_outcome_assignment_receiver(self):
        oracle = CentralizedOracleFactory()
        assignment_event = {
            'name': 'OutcomeAssignment',
            'address': oracle.address,
            'params': [{
                'name': 'outcome',
                'value': 1,
            }]
        }

        CentralizedOracleInstanceReceiver().save(assignment_event)
        saved_oracle = CentralizedOracle.objects.get(address=oracle.address)
        self.assertTrue(saved_oracle.is_outcome_set)
        self.assertEqual(saved_oracle.outcome, 1)

    def test_market_funding_receiver(self):
        market = MarketFactory()
        funding_event = {
            'name': 'MarketFunding',
            'address': market.address,
            'params': [
                {
                    'name': 'funding',
                    'value': 100
                }
            ]
        }

        MarketInstanceReceiver().save(funding_event)
        saved_market = Market.objects.get(address=market.address)
        self.assertEqual(saved_market.stage, 1)
        self.assertEqual(saved_market.funding, 100)

    def test_market_closing_receiver(self):
        market = MarketFactory()
        closing_event = {
            'name': 'MarketClosing',
            'address': market.address,
            'params': []
        }

        MarketInstanceReceiver().save(closing_event)
        saved_market = Market.objects.get(address=market.address)
        self.assertEqual(saved_market.stage, 2)

    def test_market_fee_withdrawal_receiver(self):
        market = MarketFactory()
        withdraw_event = {
            'name': 'FeeWithdrawal',
            'address': market.address,
            'params': [
                {
                    'name': 'fees',
                    'value': 10
                }
            ]
        }

        MarketInstanceReceiver().save(withdraw_event)
        saved_market = Market.objects.get(address=market.address)
        # self.assertEqual(market.stage, 3)
        self.assertEqual(saved_market.withdrawn_fees, market.withdrawn_fees+10)

    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.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.assertEqual(buy_orders[0].cost, 110) # outcomeTokenCost+fee

    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

    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

    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)

    def test_create_tournament_participant(self):
        identity = 'ebe4dd7a4a9e712e742862719aa04709cc6d80a6'
        participant_event = {
            'name': 'IdentityCreated',
            'address': 'abbcd5b340c80b5f1c0545c04c987b87310296ae',
            'params': [
                {
                    'name': 'identity',
                    'value': identity
                },
                {
                    'name': 'creator',
                    'value': '50858f2c7873fac9398ed9c195d185089caa7967'
                },
                {
                    'name': 'owner',
                    'value': '8f357b2c8071c2254afbc65907997f9adea6cc78',
                },
                {
                    'name': 'recoveryKey',
                    'value': 'b67c2d2fcfa3e918e3f9a5218025ebdd12d26212'
                }
            ]
        }

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

        self.assertEqual(TournamentParticipant.objects.all().count(), 0)
        # Save event
        UportIdentityManagerReceiver().save(participant_event, block)
        # Check that collected fees was incremented
        self.assertEqual(TournamentParticipant.objects.all().count(), 1)

    def test_issue_tournament_tokens(self):
        participant_balance = TournamentParticipantBalanceFactory()
        participant = participant_balance.participant
        amount_to_add = 150
        participant_event = {
            'name': 'Issuance',
            'address': 'not needed',
            'params': [
                {
                    'name': 'owner',
                    'value': participant.address
                },
                {
                    'name': 'amount',
                    'value': amount_to_add
                }
            ]
        }

        self.assertEqual(TournamentParticipantBalance.objects.get(participant=participant.address).balance, participant_balance.balance)
        # Save event
        TournamentTokenReceiver().save(participant_event)
        self.assertEqual(TournamentParticipantBalance.objects.get(participant=participant.address).balance, participant_balance.balance+amount_to_add)

    def test_issue_non_participant(self):
        # should not break, just don't save anything
        participant_balance = TournamentParticipantBalanceFactory()
        participant = participant_balance.participant
        participant_event = {
            'name': 'Issuance',
            'address': 'not needed',
            'params': [
                {
                    'name': 'owner',
                    'value': participant.address
                },
                {
                    'name': 'amount',
                    'value': 123
                }
            ]
        }

        participant.delete()
        # Save event
        TournamentTokenReceiver().save(participant_event)
        self.assertEqual(TournamentParticipant.objects.all().count(), 0)
        self.assertIsNone(participant.pk)

    def test_transfer_tournament_tokens(self):
        participant_balance1 = TournamentParticipantBalanceFactory()
        participant1 = participant_balance1.participant
        participant_balance2 = TournamentParticipantBalanceFactory()
        participant2 = participant_balance2.participant

        participant1_issuance_event = {
            'name': 'Issuance',
            'address': 'not needed',
            'params': [
                {
                    'name': 'owner',
                    'value': participant1.address
                },
                {
                    'name': 'amount',
                    'value': 150
                }
            ]
        }

        transfer_event = {
            'name': 'Transfer',
            'address': 'not needed',
            'params': [
                {
                    'name': 'from',
                    'value': participant1.address
                },
                {
                    'name': 'to',
                    'value': participant2.address
                },
                {
                    'name': 'value',
                    'value': 15
                }
            ]
        }

        # Save event
        TournamentTokenReceiver().save(participant1_issuance_event)
        TournamentTokenReceiver().save(transfer_event)
        self.assertEqual(TournamentParticipantBalance.objects.get(participant=participant1.address).balance.__float__(), float(participant_balance1.balance+150-15))
        self.assertEqual(TournamentParticipantBalance.objects.get(participant=participant2.address).balance.__float__(), float(participant_balance2.balance+15))

    def test_transfer_tournament_tokens_non_to_participants(self):
        participant_balance1 = TournamentParticipantBalanceFactory()
        participant1 = participant_balance1.participant
        participant_balance2 = TournamentParticipantBalanceFactory()
        participant2 = participant_balance2.participant
        participant1_issuance_event = {
            'name': 'Issuance',
            'address': 'not needed',
            'params': [
                {
                    'name': 'owner',
                    'value': participant1.address
                },
                {
                    'name': 'amount',
                    'value': 150
                }
            ]
        }

        transfer_event = {
            'name': 'Transfer',
            'address': 'not needed',
            'params': [
                {
                    'name': 'from',
                    'value': participant1.address
                },
                {
                    'name': 'to',
                    'value': participant2.address
                },
                {
                    'name': 'value',
                    'value': 15
                }
            ]
        }

        participant2.delete()

        # Save event
        TournamentTokenReceiver().save(participant1_issuance_event)
        TournamentTokenReceiver().save(transfer_event)
        self.assertEqual(TournamentParticipantBalance.objects.get(participant=participant1.address).balance.__float__(), float(participant_balance1.balance+150-15))
        self.assertEqual(TournamentParticipant.objects.filter(address=participant2.address).count(), 0)

    def test_transfer_tournament_tokens_non_from_participant(self):
        participant1 = TournamentParticipantBalanceFactory().participant
        participant_balance2 = TournamentParticipantBalanceFactory()
        participant2 = participant_balance2.participant

        transfer_event = {
            'name': 'Transfer',
            'address': 'not needed',
            'params': [
                {
                    'name': 'from',
                    'value': participant1.address
                },
                {
                    'name': 'to',
                    'value': participant2.address
                },
                {
                    'name': 'value',
                    'value': 15
                }
            ]
        }

        participant1.delete()

        # Save event
        TournamentTokenReceiver().save(transfer_event)
        self.assertEqual(TournamentParticipant.objects.filter(address=participant1.address).count(), 0)
        self.assertEqual(TournamentParticipantBalance.objects.get(participant=participant2.address).balance.__float__(), float(participant_balance2.balance+15))
Esempio n. 3
0
class TestRollback(TestCase):
    def setUp(self):
        self.ipfs_api = Ipfs()

    def to_timestamp(self, datetime_instance):
        return mktime(datetime_instance.timetuple())

    def test_centralized_oracle_factory_rollback(self):
        oracle = CentralizedOracleFactory()

        # saving event_description to IPFS
        event_description_json = {
            'title': oracle.event_description.title,
            'description': oracle.event_description.description,
            'resolutionDate':
            oracle.event_description.resolution_date.isoformat(),
            'outcomes': oracle.event_description.outcomes
        }

        ipfs_hash = self.ipfs_api.post(event_description_json)

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

        oracle_address = oracle.address

        oracle_event = {
            'name':
            'CentralizedOracleCreation',
            'address':
            oracle.factory,
            'params': [{
                'name': 'creator',
                'value': oracle.creator
            }, {
                'name': 'centralizedOracle',
                'value': oracle_address,
            }, {
                'name': 'ipfsHash',
                'value': ipfs_hash
            }]
        }
        oracle.delete()

        CentralizedOracleFactoryReceiver().save(oracle_event, block)
        created_oracle = CentralizedOracle.objects.get(address=oracle_address)
        self.assertIsNotNone(created_oracle.pk)
        # Rollback
        CentralizedOracleFactoryReceiver().rollback(oracle_event, block)
        with self.assertRaises(CentralizedOracle.DoesNotExist):
            CentralizedOracle.objects.get(address=oracle_address)

        # Rollback over nonexistent centralized oracle should fail
        self.assertRaises(Exception,
                          CentralizedOracleFactoryReceiver().rollback,
                          oracle_event, block)

    def test_oracle_owner_replacement_rollback(self):
        # Create the oracle
        oracle = CentralizedOracleFactory()
        oracle2 = CentralizedOracleFactory()
        new_owner_address = oracle2.creator
        block = {'number': 1, 'timestamp': self.to_timestamp(timezone.now())}
        change_owner_event = {
            'name': 'OwnerReplacement',
            'address': oracle.address,
            'params': [{
                'name': 'newOwner',
                'value': new_owner_address
            }]
        }

        centralized_oracle_without_owner_replacement = CentralizedOracle.objects.get(
            address=oracle.address)
        # Change owner
        CentralizedOracleInstanceReceiver().save(change_owner_event)
        centralized_oracle_with_owner_replacement = CentralizedOracle.objects.get(
            address=oracle.address)
        self.assertEqual(centralized_oracle_with_owner_replacement.owner,
                         new_owner_address)
        # Rollback
        CentralizedOracleInstanceReceiver().rollback(change_owner_event, block)
        centralized_oracle_with_owner_rollback = CentralizedOracle.objects.get(
            address=oracle.address)
        self.assertEqual(centralized_oracle_with_owner_rollback.owner,
                         centralized_oracle_without_owner_replacement.owner)

    def test_oracle_outcome_assignment_rollback(self):
        # Create the oracle
        oracle_factory = CentralizedOracleFactory()
        block = {'number': 1, 'timestamp': self.to_timestamp(timezone.now())}
        outcome_assignment_event = {
            'name': 'OutcomeAssignment',
            'address': oracle_factory.address,
            'params': [{
                'name': 'outcome',
                'value': 1,
            }]
        }

        CentralizedOracleInstanceReceiver().save(outcome_assignment_event)
        centralized_oracle_with_outcome_assignment = CentralizedOracle.objects.get(
            address=oracle_factory.address)
        self.assertTrue(
            centralized_oracle_with_outcome_assignment.is_outcome_set)
        self.assertEqual(centralized_oracle_with_outcome_assignment.outcome, 1)
        CentralizedOracleInstanceReceiver().rollback(outcome_assignment_event,
                                                     block)
        centralized_oracle_with_outcome_assignment_rollback = CentralizedOracle.objects.get(
            address=oracle_factory.address)
        self.assertFalse(
            centralized_oracle_with_outcome_assignment_rollback.is_outcome_set)
        self.assertIsNone(
            centralized_oracle_with_outcome_assignment_rollback.outcome)

    def test_scalar_event_factory_rollback(self):
        oracle = OracleFactory()
        event = ScalarEventFactory()
        event_address = event.address

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

        scalar_event = {
            'address':
            event.factory,
            'name':
            'ScalarEventCreation',
            '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)
        self.assertIsNotNone(event.pk)
        EventFactoryReceiver().rollback(scalar_event, block)
        with self.assertRaises(ScalarEvent.DoesNotExist):
            ScalarEvent.objects.get(address=event_address)

        # Rollback over an nonexistent event should fail
        self.assertRaises(Exception,
                          EventFactoryReceiver().rollback, scalar_event, block)

    def test_categorical_event_factory_rollback(self):
        event = CategoricalEventFactory()
        oracle = OracleFactory()
        event_address = event.address

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

        categorical_event = {
            'address':
            event.factory,
            'name':
            'CategoricalEventCreation',
            'params': [{
                'name': 'creator',
                'value': event.creator
            }, {
                'name': 'collateralToken',
                'value': event.collateral_token
            }, {
                'name': 'oracle',
                'value': oracle.address
            }, {
                'name': 'outcomeCount',
                'value': 2
            }, {
                'name': 'categoricalEvent',
                'value': event_address
            }]
        }

        EventFactoryReceiver().save(categorical_event, block)
        event = CategoricalEvent.objects.get(address=event_address)
        self.assertIsNotNone(event.pk)
        EventFactoryReceiver().rollback(categorical_event, block)
        with self.assertRaises(CategoricalEvent.DoesNotExist):
            CategoricalEvent.objects.get(address=event_address)

        # Rollback over an nonexistent event shoul fail
        self.assertRaises(Exception,
                          EventFactoryReceiver().rollback, categorical_event,
                          block)

    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':
                normalize_address_without_0x(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)

    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,
            'transaction_hash':
            generate_transaction_hash(),
            '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)

        # Also double-check by querying with transaction_hash
        orders_before_rollback = BuyOrder.objects.filter(
            transaction_hash=outcome_token_purchase_event['transaction_hash'])
        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)

        # Also double-check by querying with transaction_hash
        orders_after_rollback = BuyOrder.objects.filter(
            transaction_hash=outcome_token_purchase_event['transaction_hash'])
        self.assertEqual(len(orders_after_rollback), 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 = generate_eth_account(only_address=True)

        block = {'number': 1, 'timestamp': self.to_timestamp(timezone.now())}
        outcome_token_sell_event = {
            'name':
            'OutcomeTokenSale',
            'address':
            market.address,
            'transaction_hash':
            generate_transaction_hash(),
            '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)

        # Also double-check by querying with transaction hash
        orders_before_rollback = SellOrder.objects.filter(
            transaction_hash=outcome_token_sell_event['transaction_hash'])
        self.assertEqual(len(orders_before_rollback), 1)

        # Outcome token sell rollback
        MarketInstanceReceiver().rollback(outcome_token_sell_event, block)
        orders_after_rollback = SellOrder.objects.filter(
            creation_block=block.get('number'), sender=seller_address)
        self.assertEqual(len(orders_after_rollback), 0)

        # Also double-check by querying with transaction hash
        orders_after_rollback = SellOrder.objects.filter(
            transaction_hash=outcome_token_sell_event['transaction_hash'])
        self.assertEqual(len(orders_after_rollback), 0)

    def test_market_outcome_token_shortsale_rollback(self):
        pass

    def test_market_funding_rollback(self):
        market_factory = MarketFactory()
        block = {'number': 1, 'timestamp': self.to_timestamp(timezone.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.assertEqual(market_without_rollback.stage, 1)
        self.assertEqual(market_without_rollback.funding, 100)
        # Rollback
        MarketInstanceReceiver().rollback(market_funding_event, block)
        market_with_rollback = Market.objects.get(
            address=market_factory.address)
        self.assertEqual(market_with_rollback.stage, 0)
        self.assertIsNone(market_with_rollback.funding)

    def test_market_closing_rollback(self):
        market_factory = MarketFactory()
        block = {'number': 1, 'timestamp': self.to_timestamp(timezone.now())}
        market_closing_event = {
            'name': 'MarketClosing',
            'address': market_factory.address,
            'params': []
        }

        MarketInstanceReceiver().save(market_closing_event)
        market_without_rollback = Market.objects.get(
            address=market_factory.address)
        self.assertEqual(market_without_rollback.stage, 2)
        # Rollback
        MarketInstanceReceiver().rollback(market_closing_event, block)
        market_with_rollback = Market.objects.get(
            address=market_factory.address)
        self.assertEqual(market_with_rollback.stage, 1)

    def test_market_fee_withdrawal_rollback(self):
        market_factory = MarketFactory()
        block = {'number': 1, 'timestamp': self.to_timestamp(timezone.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.assertEqual(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.assertEqual(market_with_rollback.withdrawn_fees,
                         market_factory.withdrawn_fees)

    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(timezone.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)

    def test_tournament_participant_rollback(self):
        identity = 'ebe4dd7a4a9e712e742862719aa04709cc6d80a6'
        participant_event = {
            'name':
            'IdentityCreated',
            'address':
            'abbcd5b340c80b5f1c0545c04c987b87310296ae',
            'params': [{
                'name': 'identity',
                'value': identity
            }, {
                'name': 'creator',
                'value': '50858f2c7873fac9398ed9c195d185089caa7967'
            }, {
                'name': 'owner',
                'value': '8f357b2c8071c2254afbc65907997f9adea6cc78',
            }, {
                'name': 'recoveryKey',
                'value': 'b67c2d2fcfa3e918e3f9a5218025ebdd12d26212'
            }]
        }

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

        self.assertEqual(TournamentParticipant.objects.all().count(), 0)
        # Save event
        UportIdentityManagerReceiver().save(participant_event, block)
        # Check that collected fees was incremented
        self.assertEqual(TournamentParticipant.objects.all().count(), 1)
        # Rollback
        UportIdentityManagerReceiver().rollback(participant_event, block)
        self.assertEqual(TournamentParticipant.objects.all().count(), 0)
        self.assertRaises(Exception,
                          UportIdentityManagerReceiver().rollback,
                          participant_event, block)

    def test_tournament_participant_issuance_rollback(self):
        amount = 123
        participant_balance = TournamentParticipantBalanceFactory()
        participant = participant_balance.participant
        participant_event = {
            'name':
            'Issuance',
            'address':
            'not needed',
            'params': [{
                'name': 'owner',
                'value': participant.address
            }, {
                'name': 'amount',
                'value': amount
            }]
        }

        self.assertEqual(
            TournamentParticipantBalance.objects.get(
                participant=participant.address).balance,
            participant_balance.balance)
        # Save event
        TournamentTokenReceiver().save(participant_event)
        self.assertEqual(
            TournamentParticipantBalance.objects.get(
                participant=participant.address).balance,
            participant_balance.balance + amount)

        # Rollback
        TournamentTokenReceiver().rollback(participant_event)
        self.assertEqual(
            TournamentParticipantBalance.objects.get(
                participant=participant.address).balance,
            participant_balance.balance)

    def test_transfer_tournament_tokens_rollback(self):
        participant_balance1 = TournamentParticipantBalanceFactory()
        participant1 = participant_balance1.participant
        participant_balance2 = TournamentParticipantBalanceFactory()
        participant2 = participant_balance2.participant
        participant1_issuance_event = {
            'name':
            'Issuance',
            'address':
            'not needed',
            'params': [{
                'name': 'owner',
                'value': participant1.address
            }, {
                'name': 'amount',
                'value': 150
            }]
        }

        transfer_event = {
            'name':
            'Transfer',
            'address':
            'not needed',
            'params': [{
                'name': 'from',
                'value': participant1.address
            }, {
                'name': 'to',
                'value': participant2.address
            }, {
                'name': 'value',
                'value': 15
            }]
        }

        # Save event
        TournamentTokenReceiver().save(participant1_issuance_event)
        TournamentTokenReceiver().save(transfer_event)
        self.assertEqual(
            TournamentParticipantBalance.objects.get(
                participant=participant1.address).balance.__float__(),
            float(participant_balance1.balance + 150 - 15))
        self.assertEqual(
            TournamentParticipantBalance.objects.get(
                participant=participant2.address).balance.__float__(),
            float(participant_balance2.balance + 15))

        TournamentTokenReceiver().rollback(transfer_event)
        self.assertEqual(
            TournamentParticipantBalance.objects.get(
                participant=participant1.address).balance.__float__(),
            float(participant_balance1.balance + 150))
        self.assertEqual(
            TournamentParticipantBalance.objects.get(
                participant=participant2.address).balance.__float__(),
            float(participant_balance2.balance))

        # Transfer with only one
        participant2.delete()
        instance = TournamentTokenReceiver().save(transfer_event)
        self.assertIsNotNone(instance)
        self.assertEqual(
            TournamentParticipantBalance.objects.get(
                participant=participant1.address).balance.__float__(),
            float(participant_balance1.balance + 150 - 15))

        TournamentTokenReceiver().rollback(transfer_event)
        self.assertEqual(
            TournamentParticipantBalance.objects.get(
                participant=participant1.address).balance.__float__(),
            float(participant_balance1.balance + 150))

        participant1.delete()
        TournamentTokenReceiver().rollback(transfer_event)

    def test_winnings_redemption_rollback(self):
        event = CategoricalEventFactory(redeemed_winnings=100)
        address = event.address[0:-4] + 'user'

        winnings_event = {
            'name':
            'WinningsRedemption',
            'address':
            event.address,
            'params': [{
                'name': 'receiver',
                'value': address
            }, {
                'name': 'winnings',
                'value': 10
            }]
        }

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

        EventInstanceReceiver().save(winnings_event, block)
        event_before_rollback = CategoricalEvent.objects.get(
            address=event.address)
        self.assertEqual(event_before_rollback.redeemed_winnings,
                         event.redeemed_winnings + 10)
        EventInstanceReceiver().rollback(winnings_event, block)
        event_after_rollback = CategoricalEvent.objects.get(
            address=event.address)
        self.assertEqual(event_after_rollback.redeemed_winnings,
                         event.redeemed_winnings)
Esempio n. 4
0
class TestSerializers(TestCase):
    def setUp(self):
        self.ipfs = Ipfs()

    def test_create_centralized_oracle(self):
        oracle = CentralizedOracleFactory()
        event_description_json = None

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

        oracle_event = {
            'address':
            oracle.factory[0:-7] + 'GIACOMO',
            'params': [{
                'name': 'creator',
                'value': oracle.creator
            }, {
                'name': 'centralizedOracle',
                'value': oracle.address[1:-7] + 'GIACOMO',
            }, {
                'name': 'ipfsHash',
                'value': oracle.event_description.ipfs_hash[1:-7] + ''
            }]
        }

        s = CentralizedOracleSerializer(data=oracle_event, block=block)
        # ipfs_hash not saved to IPFS
        self.assertFalse(s.is_valid(), s.errors)
        # oracle.event_description
        event_description_json = {
            'title': oracle.event_description.title,
            'description': oracle.event_description.description,
            'resolutionDate':
            oracle.event_description.resolution_date.isoformat(),
            'outcomes': ['Yes', 'No']
        }

        # save event_description to IPFS
        ipfs_hash = self.ipfs.post(event_description_json)
        oracle_event.get('params')[2]['value'] = ipfs_hash

        s = CentralizedOracleSerializer(data=oracle_event, block=block)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()
        self.assertIsNotNone(instance)

    def test_event_description_different_outcomes(self):

        oracle = CentralizedOracleFactory()

        oracle.event_description.outcomes = ['Yes', 'No', 'Third']
        oracle.event_description.save()

        # Categorical Event with different outcomes

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

        categorical_event = {
            'address':
            oracle.factory,
            'params': [{
                'name': 'creator',
                'value': oracle.creator
            }, {
                'name': 'collateralToken',
                'value': oracle.creator
            }, {
                'name': 'oracle',
                'value': oracle.address
            }, {
                'name': 'outcomeCount',
                'value': 2
            }, {
                'name': 'categoricalEvent',
                'value': oracle.factory[1:-11] + 'CATEGORICAL',
            }]
        }

        s = CategoricalEventSerializer(data=categorical_event, block=block)
        self.assertFalse(s.is_valid())
        categorical_event['params'][3]['value'] = 3
        s2 = CategoricalEventSerializer(data=categorical_event, block=block)
        self.assertTrue(s2.is_valid(), s.errors)
        instance = s2.save()
        self.assertIsNotNone(instance)

    def test_create_scalar_with_categorical_description(self):

        oracle = CentralizedOracleFactory()

        # Categorical Event with different outcomes

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

        scalar_event = {
            'address':
            oracle.factory,
            'params': [{
                'name': 'creator',
                'value': oracle.creator
            }, {
                'name': 'collateralToken',
                'value': oracle.creator
            }, {
                'name': 'oracle',
                'value': oracle.address
            }, {
                'name': 'upperBound',
                'value': 1
            }, {
                'name': 'lowerBound',
                'value': 0
            }, {
                'name': 'scalarEvent',
                'value': oracle.factory[1:-6] + 'SCALAR',
            }]
        }

        s = ScalarEventSerializer(data=scalar_event, block=block)
        self.assertFalse(s.is_valid())
        scalar_event['params'][3]['value'] = 3
        scalar_descripion = ScalarEventDescriptionFactory()
        oracle.event_description = scalar_descripion
        oracle.save()
        s2 = ScalarEventSerializer(data=scalar_event, block=block)
        self.assertTrue(s2.is_valid(), s.errors)
        instance = s2.save()
        self.assertIsNotNone(instance)

    def test_deserialize_ultimate_oracle(self):
        forwarded_oracle = CentralizedOracleFactory()
        ultimate_oracle = UltimateOracleFactory()

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

        oracle_event = {
            'address':
            ultimate_oracle.factory[0:-7] + 'GIACOMO',
            'params': [{
                'name': 'creator',
                'value': ultimate_oracle.creator
            }, {
                'name': 'ultimateOracle',
                'value': ultimate_oracle.address
            }, {
                'name': 'oracle',
                'value': forwarded_oracle.address
            }, {
                'name': 'collateralToken',
                'value': ultimate_oracle.collateral_token
            }, {
                'name': 'spreadMultiplier',
                'value': ultimate_oracle.spread_multiplier
            }, {
                'name': 'challengePeriod',
                'value': ultimate_oracle.challenge_period
            }, {
                'name': 'challengeAmount',
                'value': ultimate_oracle.challenge_amount
            }, {
                'name': 'frontRunnerPeriod',
                'value': ultimate_oracle.front_runner_period
            }]
        }

        s = UltimateOracleSerializer(data=oracle_event, block=block)
        self.assertTrue(s.is_valid(), s.errors)

    def test_create_ultimate_oracle(self):
        forwarded_oracle = CentralizedOracleFactory()
        ultimate_oracle = UltimateOracleFactory()

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

        oracle_event = {
            'address':
            ultimate_oracle.factory[0:7] + 'another',
            'params': [{
                'name': 'creator',
                'value': ultimate_oracle.creator
            }, {
                'name': 'ultimateOracle',
                'value': ultimate_oracle.address[0:7] + 'another',
            }, {
                'name': 'oracle',
                'value': forwarded_oracle.address
            }, {
                'name': 'collateralToken',
                'value': ultimate_oracle.collateral_token
            }, {
                'name': 'spreadMultiplier',
                'value': ultimate_oracle.spread_multiplier
            }, {
                'name': 'challengePeriod',
                'value': ultimate_oracle.challenge_period
            }, {
                'name': 'challengeAmount',
                'value': ultimate_oracle.challenge_amount
            }, {
                'name': 'frontRunnerPeriod',
                'value': ultimate_oracle.front_runner_period
            }]
        }

        s = UltimateOracleSerializer(data=oracle_event, block=block)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()
        self.assertIsNotNone(instance)
        self.assertIsNotNone(instance.pk)

    def test_create_ultimate_oracle_no_forwarded(self):
        forwarded_oracle = CentralizedOracleFactory()
        ultimate_oracle = UltimateOracleFactory()

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

        oracle_event = {
            'address':
            ultimate_oracle.factory[0:-8] + 'another',
            'params': [{
                'name': 'creator',
                'value': ultimate_oracle.creator
            }, {
                'name': 'ultimateOracle',
                'value': ultimate_oracle.address[0:-8] + 'another',
            }, {
                'name':
                'oracle',
                'value':
                ultimate_oracle.forwarded_oracle.address[0:-5] + 'wrong'
            }, {
                'name': 'collateralToken',
                'value': ultimate_oracle.collateral_token
            }, {
                'name': 'spreadMultiplier',
                'value': ultimate_oracle.spread_multiplier
            }, {
                'name': 'challengePeriod',
                'value': ultimate_oracle.challenge_period
            }, {
                'name': 'challengeAmount',
                'value': ultimate_oracle.challenge_amount
            }, {
                'name': 'frontRunnerPeriod',
                'value': ultimate_oracle.front_runner_period
            }]
        }

        s = UltimateOracleSerializer(data=oracle_event, block=block)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()
        self.assertIsNotNone(instance)
        self.assertIsNotNone(instance.pk)
        self.assertIsNone(instance.forwarded_oracle)

    def test_create_scalar_event(self):
        event = EventFactory()
        oracle = OracleFactory()

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

        scalar_event = {
            'address':
            oracle.factory[1:-8] + 'GIACOMO1',
            'params': [{
                'name': 'creator',
                'value': oracle.creator
            }, {
                'name': 'collateralToken',
                'value': event.collateral_token
            }, {
                'name': 'oracle',
                'value': oracle.address
            }, {
                'name': 'upperBound',
                'value': 1
            }, {
                'name': 'lowerBound',
                'value': 0
            }]
        }

        s = ScalarEventSerializer(data=scalar_event, block=block)
        self.assertFalse(s.is_valid(), s.errors)

        scalar_event.get('params').append({
            'name':
            'scalarEvent',
            'value':
            event.address[1:-8] + 'GIACOMO2'
        })

        s = ScalarEventSerializer(data=scalar_event, block=block)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()
        self.assertIsNotNone(instance)

    def test_create_categorical_event(self):
        event_factory = EventFactory()
        oracle = OracleFactory()

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

        categorical_event = {
            'address':
            oracle.factory[1:-7] + 'GIACOMO',
            'params': [{
                'name': 'creator',
                'value': oracle.creator
            }, {
                'name': 'collateralToken',
                'value': event_factory.collateral_token
            }, {
                'name': 'oracle',
                'value': oracle.address
            }, {
                'name': 'outcomeCount',
                'value': 1
            }]
        }

        s = CategoricalEventSerializer(data=categorical_event, block=block)
        self.assertFalse(s.is_valid(), s.errors)

        categorical_event.get('params').append({
            'name':
            'categoricalEvent',
            'value':
            event_factory.address[1:-7] + 'GIACOMO'
        })

        s = CategoricalEventSerializer(data=categorical_event, block=block)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()
        self.assertIsNotNone(instance)

    def test_create_market(self):
        oracle = CentralizedOracleFactory()
        event_factory = CategoricalEventFactory(oracle=oracle)
        market_factory = MarketFactory()

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

        market_dict = {
            'address':
            oracle.factory[1:-7] + 'GIACOMO',
            'params': [{
                'name': 'creator',
                'value': oracle.creator
            }, {
                'name': 'centralizedOracle',
                'value': oracle.address[1:-7] + 'GIACOMO',
            }, {
                'name': 'marketMaker',
                'value': market_factory.market_maker
            }, {
                'name': 'fee',
                'value': market_factory.fee
            }, {
                'name': 'market',
                'value': market_factory.address[0:-7] + 'MARKET'
            }]
        }

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

        market_dict.get('params').append({
            'name':
            'eventContract',
            'value':
            event_factory.address[1:-9] + 'xGIACOMOx'
        })

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

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

        market_dict.get('params')[-2]['value'] = event_factory.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)

    def test_create_categorical_event_description(self):
        event_description_factory = EventDescriptionFactory()
        categorical_event_description_json = {
            'title':
            ' '.join(event_description_factory.title),
            'description':
            ' '.join(event_description_factory.description),
            'resolution_date':
            event_description_factory.resolution_date.isoformat(),
            'outcomes': ['A', 'B', 'C']
        }
        ipfs_hash = self.ipfs.post(categorical_event_description_json)
        serializer = IPFSEventDescriptionDeserializer(
            data={'ipfs_hash': ipfs_hash})
        self.assertTrue(serializer.is_valid(), serializer.errors)
        self.assertIsNotNone(serializer.save())

    def test_create_scalar_event_description(self):
        event_description_factory = EventDescriptionFactory()
        scalar_event_description_json = {
            'title':
            ' '.join(event_description_factory.title),
            'description':
            ' '.join(event_description_factory.description),
            'resolution_date':
            event_description_factory.resolution_date.isoformat(),
            'unit':
            'X',
            'decimals':
            '4',
        }
        ipfs_hash = self.ipfs.post(scalar_event_description_json)
        serializer = IPFSEventDescriptionDeserializer(
            data={'ipfs_hash': ipfs_hash})
        self.assertTrue(serializer.is_valid(), serializer.errors)
        self.assertIsNotNone(serializer.save())

    def test_create_centralized_oracle_instance(self):
        oracle = CentralizedOracleFactory()
        # oracle.event_description
        event_description_json = {
            'title': oracle.event_description.title,
            'description': oracle.event_description.description,
            'resolutionDate':
            oracle.event_description.resolution_date.isoformat(),
            'outcomes': ['Yes', 'No']
        }

        # save event_description to IPFS
        ipfs_hash = self.ipfs.post(event_description_json)

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

        oracle_event = {
            'address':
            oracle.factory[0:-7] + 'GIACOMO',
            'params': [{
                'name': 'creator',
                'value': oracle.address
            }, {
                'name': 'centralizedOracle',
                'value': oracle.address[1:-8] + 'INSTANCE',
            }, {
                'name': 'ipfsHash',
                'value': ipfs_hash
            }]
        }

        s = CentralizedOracleInstanceSerializer(data=oracle_event, block=block)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()
        self.assertIsNotNone(instance)

    def test_create_outcome_token_instance(self):
        outcome_token_factory = OutcomeTokenFactory()
        oracle_factory = OracleFactory()
        event_factory = EventFactory()
        event = None

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

        scalar_event = {
            'address':
            oracle_factory.factory[1:-12] + 'TESTINSTANCE',
            'params': [{
                'name': 'creator',
                'value': oracle_factory.creator
            }, {
                'name': 'collateralToken',
                'value': event_factory.collateral_token
            }, {
                'name': 'oracle',
                'value': oracle_factory.address
            }, {
                'name': 'outcomeCount',
                'value': 1
            }, {
                'name': 'upperBound',
                'value': 1
            }, {
                'name': 'lowerBound',
                'value': 0
            }, {
                'name': 'scalarEvent',
                'value': event_factory.address[1:-12] + 'TESTINSTANCE'
            }]
        }

        s = ScalarEventSerializer(data=scalar_event, block=block)
        s.is_valid()
        event = s.save()

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

        oracle_event = {
            'address':
            oracle_factory.factory[0:-7] + 'GIACOMO',
            'params': [{
                'name': 'creator',
                'value': event.creator
            }, {
                'name': 'address',
                'value': event.address
            }, {
                'name': 'outcomeToken',
                'value': oracle_factory.address[1:-8] + 'INSTANCE',
            }, {
                'name': 'index',
                'value': outcome_token_factory.index
            }]
        }

        s = OutcomeTokenInstanceSerializer(data=oracle_event)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()
        self.assertIsNotNone(instance)

    def test_issuance_outcome_token(self):
        outcome_token = OutcomeTokenFactory()
        event = EventFactory()

        issuance_event = {
            'name':
            'Issuance',
            'address':
            outcome_token.address,
            'params': [{
                'name': 'owner',
                'value': event.address
            }, {
                'name': 'amount',
                'value': 20,
            }]
        }

        s = OutcomeTokenIssuanceSerializer(data=issuance_event)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()

        balance = OutcomeTokenBalance.objects.get(owner=event.address)
        self.assertEqual(balance.balance, 20)
        self.assertIsNotNone(instance)

        self.assertEqual(
            OutcomeToken.objects.get(
                address=outcome_token.address).total_supply,
            outcome_token.total_supply + 20)

    def test_revocation_outcome_token(self):
        balance = OutcomeTokenBalanceFactory()
        balance.balance = 20
        balance.save()

        issuance_event = {
            'name':
            'Revocation',
            'address':
            balance.outcome_token.address,
            'params': [{
                'name': 'owner',
                'value': balance.owner
            }, {
                'name': 'amount',
                'value': 20,
            }]
        }

        s = OutcomeTokenRevocationSerializer(data=issuance_event)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()

        self.assertEqual(
            OutcomeTokenBalance.objects.get(owner=balance.owner).balance, 0)
        self.assertIsNotNone(instance)

        self.assertEqual(
            OutcomeToken.objects.get(
                address=balance.outcome_token.address).total_supply,
            balance.outcome_token.total_supply - 20)

    def test_transfer_outcome_token(self):
        outcome_token_balance = OutcomeTokenBalanceFactory()
        event = EventFactory()
        outcome_token_balance.balance = 20
        outcome_token_balance.save()

        transfer_event = {
            'name':
            'Transfer',
            'address':
            outcome_token_balance.outcome_token.address,
            'params': [{
                'name': 'from',
                'value': outcome_token_balance.owner
            }, {
                'name': 'to',
                'value': event.address
            }, {
                'name': 'value',
                'value': outcome_token_balance.balance,
            }]
        }

        s = OutcomeTokenTransferSerializer(data=transfer_event)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()

        self.assertEqual(
            OutcomeTokenBalance.objects.get(
                owner=outcome_token_balance.owner).balance, 0)
        self.assertIsNotNone(instance)
        self.assertEqual(instance.owner, event.address)
        self.assertEqual(instance.balance, 20)
Esempio n. 5
0
class TestRollabck(TestCase):
    def setUp(self):
        self.ipfs_api = Ipfs()

    def to_timestamp(self, datetime_instance):
        return mktime(datetime_instance.timetuple())

    def test_centralized_oracle_factory_rollback(self):
        oracle = CentralizedOracleFactory()

        # saving event_description to IPFS
        event_description_json = {
            'title': oracle.event_description.title,
            'description': oracle.event_description.description,
            'resolutionDate':
            oracle.event_description.resolution_date.isoformat(),
            'outcomes': oracle.event_description.outcomes
        }

        ipfs_hash = self.ipfs_api.post(event_description_json)

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

        oracle_address = oracle.address

        oracle_event = {
            'name':
            'CentralizedOracleCreation',
            'address':
            oracle.factory,
            'params': [{
                'name': 'creator',
                'value': oracle.creator
            }, {
                'name': 'centralizedOracle',
                'value': oracle_address,
            }, {
                'name': 'ipfsHash',
                'value': ipfs_hash
            }]
        }
        oracle.delete()

        CentralizedOracleFactoryReceiver().save(oracle_event, block)
        created_oracle = CentralizedOracle.objects.get(address=oracle_address)
        self.assertIsNotNone(created_oracle.pk)
        # Rollback
        CentralizedOracleFactoryReceiver().rollback(oracle_event, block)
        with self.assertRaises(CentralizedOracle.DoesNotExist):
            CentralizedOracle.objects.get(address=oracle_address)

        # Rollback over nonexistent centralized oracle should fail
        self.assertRaises(Exception,
                          CentralizedOracleFactoryReceiver().rollback,
                          oracle_event, block)

    def test_oracle_owner_replacement_rollback(self):
        # Create the oracle
        oracle = CentralizedOracleFactory()
        oracle2 = CentralizedOracleFactory()
        new_owner_address = oracle2.creator
        block = {'number': 1, 'timestamp': self.to_timestamp(datetime.now())}
        change_owner_event = {
            'name': 'OwnerReplacement',
            'address': oracle.address,
            'params': [{
                'name': 'newOwner',
                'value': new_owner_address
            }]
        }

        centralized_oracle_without_owner_replacement = CentralizedOracle.objects.get(
            address=oracle.address)
        # Change owner
        CentralizedOracleInstanceReceiver().save(change_owner_event)
        centralized_oracle_with_owner_replacement = CentralizedOracle.objects.get(
            address=oracle.address)
        self.assertEquals(centralized_oracle_with_owner_replacement.owner,
                          new_owner_address)
        # Rollback
        CentralizedOracleInstanceReceiver().rollback(change_owner_event, block)
        centralized_oracle_with_owner_rollback = CentralizedOracle.objects.get(
            address=oracle.address)
        self.assertEquals(centralized_oracle_with_owner_rollback.owner,
                          centralized_oracle_without_owner_replacement.owner)

    def test_oracle_outcome_assignment_rollback(self):
        # Create the oracle
        oracle_factory = CentralizedOracleFactory()
        block = {'number': 1, 'timestamp': self.to_timestamp(datetime.now())}
        outcome_assignment_event = {
            'name': 'OutcomeAssignment',
            'address': oracle_factory.address,
            'params': [{
                'name': 'outcome',
                'value': 1,
            }]
        }

        CentralizedOracleInstanceReceiver().save(outcome_assignment_event)
        centralized_oracle_with_outcome_assignment = CentralizedOracle.objects.get(
            address=oracle_factory.address)
        self.assertTrue(
            centralized_oracle_with_outcome_assignment.is_outcome_set)
        self.assertEqual(centralized_oracle_with_outcome_assignment.outcome, 1)
        CentralizedOracleInstanceReceiver().rollback(outcome_assignment_event,
                                                     block)
        centralized_oracle_with_outcome_assignment_rollback = CentralizedOracle.objects.get(
            address=oracle_factory.address)
        self.assertFalse(
            centralized_oracle_with_outcome_assignment_rollback.is_outcome_set)
        self.assertIsNone(
            centralized_oracle_with_outcome_assignment_rollback.outcome)

    def test_scalar_event_factory_rollback(self):
        oracle = OracleFactory()
        event = ScalarEventFactory()
        event_address = event.address

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

        scalar_event = {
            'address':
            event.factory,
            'name':
            'ScalarEventCreation',
            '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)
        self.assertIsNotNone(event.pk)
        EventFactoryReceiver().rollback(scalar_event, block)
        with self.assertRaises(ScalarEvent.DoesNotExist):
            ScalarEvent.objects.get(address=event_address)

        # Rollback over an nonexistent event should fail
        self.assertRaises(Exception,
                          EventFactoryReceiver().rollback, scalar_event, block)

    def test_categorical_event_factory_rollback(self):
        event = CategoricalEventFactory()
        oracle = OracleFactory()
        event_address = event.address

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

        categorical_event = {
            'address':
            event.factory,
            'name':
            'CategoricalEventCreation',
            'params': [{
                'name': 'creator',
                'value': event.creator
            }, {
                'name': 'collateralToken',
                'value': event.collateral_token
            }, {
                'name': 'oracle',
                'value': oracle.address
            }, {
                'name': 'outcomeCount',
                'value': 2
            }, {
                'name': 'categoricalEvent',
                'value': event_address
            }]
        }

        EventFactoryReceiver().save(categorical_event, block)
        event = CategoricalEvent.objects.get(address=event_address)
        self.assertIsNotNone(event.pk)
        EventFactoryReceiver().rollback(categorical_event, block)
        with self.assertRaises(CategoricalEvent.DoesNotExist):
            CategoricalEvent.objects.get(address=event_address)

        # Rollback over an nonexistent event shoul fail
        self.assertRaises(Exception,
                          EventFactoryReceiver().rollback, categorical_event,
                          block)

    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)

    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)

    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)

    def test_market_outcome_token_shortsale_rollback(self):
        pass

    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)

    def test_market_closing_rollback(self):
        market_factory = MarketFactory()
        block = {'number': 1, 'timestamp': self.to_timestamp(datetime.now())}
        market_closing_event = {
            'name': 'MarketClosing',
            'address': market_factory.address,
            'params': []
        }

        MarketInstanceReceiver().save(market_closing_event)
        market_without_rollback = Market.objects.get(
            address=market_factory.address)
        self.assertEquals(market_without_rollback.stage, 2)
        # Rollback
        MarketInstanceReceiver().rollback(market_closing_event, block)
        market_with_rollback = Market.objects.get(
            address=market_factory.address)
        self.assertEquals(market_with_rollback.stage, 1)

    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)

    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.assertEquals(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.assertEquals(owner_two_token_balance.balance, 1000)
Esempio n. 6
0
class TestEventReceiver(TestCase):
    def setUp(self):
        self.ipfs_api = Ipfs()

    def to_timestamp(self, datetime_instance):
        return mktime(datetime_instance.timetuple())

    def test_centralized_oracle_receiver(self):
        oracle = CentralizedOracleFactory()
        # saving event_description to IPFS
        event_description_json = {
            'title': 'Test title',
            'description': 'test long description',
            'resolutionDate': datetime.now().isoformat(),
            'outcomes': ['YES', 'NO']
        }

        ipfs_hash = self.ipfs_api.post(event_description_json)

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

        oracle_address = oracle.address[1:-7] + 'GIACOMO'

        oracle_event = {
            'address':
            oracle.factory[1:-7] + 'GIACOMO',
            'params': [{
                'name': 'creator',
                'value': oracle.creator
            }, {
                'name': 'centralizedOracle',
                'value': oracle_address,
            }, {
                'name': 'ipfsHash',
                'value': ipfs_hash
            }]
        }

        CentralizedOracleFactoryReceiver().save(oracle_event, block)
        created_oracle = CentralizedOracle.objects.get(address=oracle_address)
        self.assertIsNotNone(created_oracle.pk)

    def test_ultimate_oracle_receiver(self):
        forwarded_oracle = CentralizedOracleFactory()
        ultimate_oracle = UltimateOracleFactory()

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

        oracle_address = ultimate_oracle.address[0:7] + 'another'

        oracle_event = {
            'address':
            ultimate_oracle.factory[0:7] + 'another',
            'params': [{
                'name': 'creator',
                'value': ultimate_oracle.creator
            }, {
                'name': 'ultimateOracle',
                'value': oracle_address,
            }, {
                'name': 'oracle',
                'value': forwarded_oracle.address
            }, {
                'name': 'collateralToken',
                'value': ultimate_oracle.collateral_token
            }, {
                'name': 'spreadMultiplier',
                'value': ultimate_oracle.spread_multiplier
            }, {
                'name': 'challengePeriod',
                'value': ultimate_oracle.challenge_period
            }, {
                'name': 'challengeAmount',
                'value': ultimate_oracle.challenge_amount
            }, {
                'name': 'frontRunnerPeriod',
                'value': ultimate_oracle.front_runner_period
            }]
        }

        UltimateOracleFactoryReceiver().save(oracle_event, block)
        created_oracle = UltimateOracle.objects.get(address=oracle_address)
        self.assertIsNotNone(created_oracle.pk)

    def test_scalar_event_receiver(self):
        oracle = OracleFactory()
        event = EventFactory()
        event_address = event.address[0:33] + 'GIACOMO'

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

        scalar_event = {
            'address':
            oracle.factory[0:33] + 'GIACOMO',
            'name':
            'ScalarEventCreation',
            'params': [{
                'name': 'creator',
                'value': oracle.creator
            }, {
                'name': 'collateralToken',
                'value': event.collateral_token
            }, {
                'name': 'oracle',
                'value': oracle.address
            }, {
                'name': 'outcomeCount',
                'value': 1
            }, {
                'name': 'upperBound',
                'value': 1
            }, {
                'name': 'lowerBound',
                'value': 0
            }, {
                'name': 'scalarEvent',
                'value': event_address
            }]
        }

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

    def test_categorical_event_receiver(self):
        event = EventFactory()
        oracle = OracleFactory()
        event_address = event.address[0:33] + 'GIACOMO'

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

        categorical_event = {
            'address':
            oracle.factory[0:33] + 'GIACOMO',
            'name':
            'CategoricalEventCreation',
            'params': [{
                'name': 'creator',
                'value': oracle.creator
            }, {
                'name': 'collateralToken',
                'value': event.collateral_token
            }, {
                'name': 'oracle',
                'value': oracle.address
            }, {
                'name': 'outcomeCount',
                'value': 1
            }, {
                'name': 'categoricalEvent',
                'value': event_address
            }]
        }

        EventFactoryReceiver().save(categorical_event, block)
        event = CategoricalEvent.objects.get(address=event_address)
        self.assertIsNotNone(event.pk)

    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': oracle.creation_block,
            'timestamp': self.to_timestamp(oracle.creation_date_time)
        }

        market_dict = {
            'address':
            oracle.factory[1:-7] + 'GIACOMO',
            'params': [{
                'name': 'creator',
                'value': oracle.creator
            }, {
                'name': 'centralizedOracle',
                'value': oracle.address[1:-7] + 'GIACOMO',
            }, {
                '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[0:7] + 'another'
            }]
        }

        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)
        market = Market.objects.get(event=event_address)
        self.assertIsNotNone(market.pk)
        self.assertEquals(len(market.net_outcome_tokens_sold), 3)

    #
    # contract instances
    #
    def test_event_instance_receiver(self):
        outcome_token_factory = OutcomeTokenFactory()
        oracle_factory = OracleFactory()
        event_factory = EventFactory()
        event_address = event_factory.address[0:-7] + 'GIACOMO'

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

        scalar_event = {
            'name':
            'ScalarEventCreation',
            'address':
            oracle_factory.factory[1:-12] + 'TESTINSTANCE',
            'params': [{
                'name': 'creator',
                'value': oracle_factory.creator
            }, {
                'name': 'collateralToken',
                'value': event_factory.collateral_token
            }, {
                'name': 'oracle',
                'value': oracle_factory.address
            }, {
                'name': 'outcomeCount',
                'value': 1
            }, {
                'name': 'upperBound',
                'value': 1
            }, {
                'name': 'lowerBound',
                'value': 0
            }, {
                'name': 'scalarEvent',
                'value': event_address
            }]
        }

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

        block = {
            'number': oracle_factory.creation_block,
            'timestamp': mktime(oracle_factory.creation_date_time.timetuple())
        }
        outcome_token_address = oracle_factory.address[1:-8] + 'INSTANCE'
        outcome_event = {
            'name':
            'OutcomeTokenCreation',
            'address':
            oracle_factory.factory[0:-7] + 'GIACOMO',
            'params': [{
                'name': 'creator',
                'value': event.creator
            }, {
                'name': 'address',
                'value': event.address
            }, {
                'name': 'outcomeToken',
                'value': outcome_token_address,
            }, {
                'name': 'index',
                'value': outcome_token_factory.index
            }]
        }
        EventInstanceReceiver().save(outcome_event, block)
        self.assertIsNotNone(
            OutcomeToken.objects.get(address=outcome_token_address))

    def test_event_instance_issuance_receiver(self):
        outcome_token_factory = OutcomeTokenFactory()
        event = {
            'name':
            'Issuance',
            'address':
            outcome_token_factory.address,
            'params': [{
                'name': 'owner',
                'value': outcome_token_factory.address[0:-7] + 'GIACOMO'
            }, {
                'name': 'amount',
                'value': 1000,
            }]
        }

        OutcomeTokenInstanceReceiver().save(event)
        outcome_token = OutcomeToken.objects.get(
            address=outcome_token_factory.address)
        self.assertIsNotNone(outcome_token.pk)
        self.assertEquals(outcome_token_factory.total_supply + 1000,
                          outcome_token.total_supply)

    def test_event_instance_revocation_receiver(self):
        outcome_token_factory = OutcomeTokenFactory()
        revocation_event = {
            'name':
            'Revocation',
            'address':
            outcome_token_factory.address,
            'params': [{
                'name': 'owner',
                'value': outcome_token_factory.address[0:-7] + 'GIACOMO'
            }, {
                '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 = OutcomeToken.objects.get(
            address=outcome_token_factory.address)
        self.assertIsNotNone(outcome_token.pk)
        self.assertEquals(outcome_token_factory.total_supply,
                          outcome_token.total_supply)

    def test_event_instance_outcome_assignment_receiver(self):
        event_factory = EventFactory()
        assignment_event = {
            'name': 'OutcomeAssignment',
            'address': event_factory.address,
            'params': [{
                'name': 'outcome',
                'value': 1,
            }]
        }

        EventInstanceReceiver().save(assignment_event)
        event = Event.objects.get(address=event_factory.address)
        self.assertTrue(event.is_winning_outcome_set)

    def test_event_instance_winnings_redemption_receiver(self):
        event_factory = EventFactory()
        redemption_event = {
            'name':
            'WinningsRedemption',
            'address':
            event_factory.address,
            'params': [{
                'name': 'receiver',
                'value': event_factory.creator[0:-7] + 'GIACOMO',
            }, {
                'name': 'winnings',
                'value': 1
            }]
        }

        EventInstanceReceiver().save(redemption_event)
        event = Event.objects.get(address=event_factory.address)
        self.assertEquals(event.redeemed_winnings,
                          event_factory.redeemed_winnings + 1)

    def test_centralized_oracle_instance_owner_replacement_receiver(self):
        oracle_factory = CentralizedOracleFactory()
        new_owner = oracle_factory.address[0:-7] + 'GIACOMO'
        change_owner_event = {
            'name': 'OwnerReplacement',
            'address': oracle_factory.address,
            'params': [{
                'name': 'newOwner',
                'value': new_owner
            }]
        }

        CentralizedOracleInstanceReceiver().save(change_owner_event)
        centralized_oracle = CentralizedOracle.objects.get(
            address=oracle_factory.address)
        self.assertEquals(centralized_oracle.owner, new_owner)

    def test_centralized_oracle_instance_outcome_assignment_receiver(self):
        oracle_factory = CentralizedOracleFactory()
        assignment_event = {
            'name': 'OutcomeAssignment',
            'address': oracle_factory.address,
            'params': [{
                'name': 'outcome',
                'value': 1,
            }]
        }

        CentralizedOracleInstanceReceiver().save(assignment_event)
        centralized_oracle = CentralizedOracle.objects.get(
            address=oracle_factory.address)
        self.assertTrue(centralized_oracle.is_outcome_set)
        self.assertEqual(centralized_oracle.outcome, 1)

    def test_ultimate_oracle_instance_outcome_assignment_receiver(self):
        oracle_factory = UltimateOracleFactory()
        assignment_event = {
            'name': 'ForwardedOracleOutcomeAssignment',
            'address': oracle_factory.address,
            'params': [{
                'name': 'outcome',
                'value': 1,
            }]
        }

        UltimateOracleInstanceReceiver().save(assignment_event)
        ultimate_oracle = UltimateOracle.objects.get(
            address=oracle_factory.address)
        self.assertTrue(ultimate_oracle.is_outcome_set)
        self.assertEqual(ultimate_oracle.forwarded_outcome, 1)

    def test_ultimate_oracle_instance_outcome_challenge_receiver(self):
        oracle = UltimateOracleFactory()
        assignment_event = {
            'name':
            'OutcomeChallenge',
            'address':
            oracle.address,
            'params': [{
                'name': 'sender',
                'value': oracle.creator
            }, {
                'name': 'outcome',
                'value': 1
            }]
        }

        UltimateOracleInstanceReceiver().save(assignment_event)
        ultimate_oracle = UltimateOracle.objects.get(address=oracle.address)
        self.assertEqual(ultimate_oracle.total_amount, oracle.challenge_amount)
        self.assertEqual(ultimate_oracle.front_runner, 1)

    def test_ultimate_oracle_instance_outcome_vote_receiver(self):
        balance_factory = OutcomeVoteBalanceFactory()
        assignment_event = {
            'name':
            'OutcomeVote',
            'address':
            balance_factory.ultimate_oracle.address,
            'params': [
                {
                    'name': 'outcome',
                    'value': balance_factory.ultimate_oracle.front_runner + 1,
                },
                {
                    'name': 'amount',
                    'value': 1,
                },
                {
                    'name': 'sender',
                    'value': balance_factory.address,
                },
            ]
        }

        UltimateOracleInstanceReceiver().save(assignment_event)
        ultimate_oracle = UltimateOracle.objects.get(
            address=balance_factory.ultimate_oracle.address)
        outcome_vote_balance = OutcomeVoteBalance.objects.get(
            address=balance_factory.address)
        self.assertEquals(ultimate_oracle.total_amount,
                          balance_factory.ultimate_oracle.total_amount + 1)
        self.assertEquals(ultimate_oracle.front_runner,
                          balance_factory.ultimate_oracle.front_runner + 1)
        self.assertEquals(outcome_vote_balance.balance, 1)

    def test_ultimate_oracle_instance_withdrawal_receiver(self):
        balance_factory = OutcomeVoteBalanceFactory()
        assignment_event = {
            'name':
            'Withdrawal',
            'address':
            balance_factory.ultimate_oracle.address,
            'params': [
                {
                    'name': 'amount',
                    'value': 1,
                },
                {
                    'name': 'sender',
                    'value': balance_factory.address,
                },
            ]
        }

        UltimateOracleInstanceReceiver().save(assignment_event)
        outcome_vote_balance = OutcomeVoteBalance.objects.get(
            address=balance_factory.address)
        self.assertEquals(outcome_vote_balance.balance,
                          balance_factory.balance - 1)

    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)

    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)

    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)
Esempio n. 7
0
class TestSerializers(TestCase):
    def setUp(self):
        self.ipfs = Ipfs()

    def test_create_centralized_oracle(self):
        oracle = CentralizedOracleFactory()

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

        oracle_event = {
            'address':
            oracle.factory,
            'params': [{
                'name': 'creator',
                'value': oracle.creator
            }, {
                'name': 'centralizedOracle',
                'value': oracle.address,
            }, {
                'name': 'ipfsHash',
                'value': oracle.event_description.ipfs_hash[1:-7] + ''
            }]
        }
        oracle.delete()
        s = CentralizedOracleSerializer(data=oracle_event, block=block)
        # ipfs_hash not saved to IPFS
        self.assertFalse(s.is_valid(), s.errors)
        # oracle.event_description
        event_description_json = {
            'title': oracle.event_description.title,
            'description': oracle.event_description.description,
            'resolutionDate':
            oracle.event_description.resolution_date.isoformat(),
            'outcomes': ['Yes', 'No']
        }

        # save event_description to IPFS
        ipfs_hash = self.ipfs.post(event_description_json)
        oracle_event.get('params')[2]['value'] = ipfs_hash

        s = CentralizedOracleSerializer(data=oracle_event, block=block)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()
        self.assertIsNotNone(instance)

    def test_create_centralized_oracle_scalar_event_with_outcomes(self):
        oracle = CentralizedOracleFactory()

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

        oracle_event = {
            'address':
            oracle.factory,
            'params': [{
                'name': 'creator',
                'value': oracle.creator
            }, {
                'name': 'centralizedOracle',
                'value': oracle.address,
            }, {
                'name': 'ipfsHash',
                'value': 'something unknown'
            }]
        }
        # remove test oracle before creating it again
        oracle.delete()
        s = CentralizedOracleSerializer(data=oracle_event, block=block)
        # ipfs_hash not saved to IPFS
        self.assertFalse(s.is_valid(), s.errors)
        # oracle.event_description
        event_description_json = {
            'title': oracle.event_description.title,
            'description': oracle.event_description.description,
            'resolutionDate':
            oracle.event_description.resolution_date.isoformat(),
            'outcomes': [],
            'unit': 'unit',
            'decimals': 2
        }

        # save event_description to IPFS
        ipfs_hash = self.ipfs.post(event_description_json)
        oracle_event.get('params')[2]['value'] = ipfs_hash

        s = CentralizedOracleSerializer(data=oracle_event, block=block)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()
        self.assertIsNotNone(instance)

        self.assertEqual(
            ScalarEventDescription.objects.filter(
                ipfs_hash=instance.event_description.ipfs_hash).count(), 1)

    def test_event_description_different_outcomes(self):

        oracle = CentralizedOracleFactory()

        oracle.event_description.outcomes = ['Yes', 'No', 'Third']
        oracle.event_description.save()

        event = CategoricalEventFactory(oracle=oracle)

        # Categorical Event with different outcomes

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

        categorical_event = {
            'address':
            event.factory,
            'params': [{
                'name': 'creator',
                'value': event.creator
            }, {
                'name': 'collateralToken',
                'value': event.creator
            }, {
                'name': 'oracle',
                'value': oracle.address
            }, {
                'name': 'outcomeCount',
                'value': 2
            }, {
                'name': 'categoricalEvent',
                'value': event.address,
            }]
        }

        event.delete()

        s = CategoricalEventSerializer(data=categorical_event, block=block)
        self.assertFalse(s.is_valid())
        categorical_event['params'][3]['value'] = 3
        s2 = CategoricalEventSerializer(data=categorical_event, block=block)
        self.assertTrue(s2.is_valid(), s.errors)
        instance = s2.save()
        self.assertIsNotNone(instance)

    def test_create_scalar_with_categorical_description(self):

        event_description = CategoricalEventDescriptionFactory()
        oracle = CentralizedOracleFactory(event_description=event_description)

        # Scalar Event with different outcomes
        event = ScalarEventFactory()

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

        scalar_event = {
            'address':
            event.factory,
            'params': [{
                'name': 'creator',
                'value': event.creator
            }, {
                'name': 'collateralToken',
                'value': event.creator
            }, {
                'name': 'oracle',
                'value': oracle.address
            }, {
                'name': 'upperBound',
                'value': event.upper_bound
            }, {
                'name': 'lowerBound',
                'value': event.lower_bound
            }, {
                'name': 'scalarEvent',
                'value': event.address,
            }]
        }

        event.delete()
        s = ScalarEventSerializer(data=scalar_event, block=block)
        self.assertFalse(s.is_valid())
        scalar_event['params'][3]['value'] = 3
        scalar_descripion = ScalarEventDescriptionFactory()
        oracle.event_description = scalar_descripion
        oracle.save()
        s2 = ScalarEventSerializer(data=scalar_event, block=block)
        self.assertTrue(s2.is_valid(), s.errors)
        instance = s2.save()
        self.assertIsNotNone(instance)

    def test_create_scalar_event(self):
        event = ScalarEventFactory()
        event_description = ScalarEventDescriptionFactory()
        oracle = CentralizedOracleFactory(event_description=event_description)

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

        scalar_event = {
            'address':
            event.factory,
            'params': [{
                'name': 'creator',
                'value': event.creator
            }, {
                'name': 'collateralToken',
                'value': event.collateral_token
            }, {
                'name': 'oracle',
                'value': oracle.address
            }, {
                'name': 'upperBound',
                'value': 1
            }, {
                'name': 'lowerBound',
                'value': 0
            }]
        }
        event.delete()
        s = ScalarEventSerializer(data=scalar_event, block=block)
        self.assertFalse(s.is_valid(), s.errors)

        scalar_event.get('params').append({
            'name': 'scalarEvent',
            'value': event.address
        })

        s = ScalarEventSerializer(data=scalar_event, block=block)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()
        self.assertIsNotNone(instance)

    def test_create_categorical_event(self):
        event = CategoricalEventFactory()
        oracle = CentralizedOracleFactory()

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

        categorical_event = {
            'address':
            event.factory,
            'params': [{
                'name': 'creator',
                'value': event.creator
            }, {
                'name': 'collateralToken',
                'value': event.collateral_token
            }, {
                'name': 'oracle',
                'value': oracle.address
            }, {
                'name': 'outcomeCount',
                'value': 2
            }]
        }
        event.delete()
        s = CategoricalEventSerializer(data=categorical_event, block=block)
        self.assertFalse(s.is_valid(), s.errors)

        categorical_event.get('params').append({
            'name': 'categoricalEvent',
            'value': event.address
        })

        s = CategoricalEventSerializer(data=categorical_event, block=block)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()
        self.assertIsNotNone(instance)

    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 = MarketSerializerTimestamped(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 = MarketSerializerTimestamped(data=market_dict, block=block)
        self.assertFalse(s.is_valid(), s.errors)

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

        s = MarketSerializerTimestamped(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':
            normalize_address_without_0x(settings.LMSR_MARKET_MAKER)
        })

        s = MarketSerializerTimestamped(data=market_dict, block=block)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()
        self.assertIsNotNone(instance)

    def test_create_market_with_multiple_addresses(self):
        oracle = CentralizedOracleFactory()
        event = CategoricalEventFactory(oracle=oracle)
        market = MarketFactory()

        # Run in updated settings context
        with self.settings(LMSR_MARKET_MAKER="0x{},0x{}".format(
                market.market_maker, generate_eth_account(only_address=True))):

            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
                }, {
                    'name': 'eventContract',
                    'value': event.address
                }, {
                    'name': 'fee',
                    'value': market.fee
                }]
            }
            market.delete()
            s = MarketSerializerTimestamped(data=market_dict, block=block)
            self.assertTrue(s.is_valid(), s.errors)
            instance = s.save()
            self.assertIsNotNone(instance)

            # Test lmsr market marker address doesn't exists
            market_dict['params'][2]['value'] = generate_eth_account(
                only_address=True)
            s = MarketSerializerTimestamped(data=market_dict, block=block)
            self.assertFalse(s.is_valid())

    def test_create_categorical_event_description(self):
        event_description = CategoricalEventDescriptionFactory()
        event_description.delete()
        categorical_event_description_json = {
            'title': event_description.title,
            'description': event_description.description,
            'resolution_date': event_description.resolution_date.isoformat(),
            'outcomes': event_description.outcomes
        }
        ipfs_hash = self.ipfs.post(categorical_event_description_json)
        serializer = IPFSEventDescriptionDeserializer(
            data={'ipfs_hash': ipfs_hash})
        self.assertTrue(serializer.is_valid(), serializer.errors)
        self.assertIsNotNone(serializer.save())

    def test_create_scalar_event_description(self):
        event_description = ScalarEventDescriptionFactory()
        event_description.delete()
        scalar_event_description_json = {
            'title': event_description.title,
            'description': event_description.description,
            'resolution_date': event_description.resolution_date.isoformat(),
            'unit': event_description.unit,
            'decimals': event_description.decimals,
        }
        ipfs_hash = self.ipfs.post(scalar_event_description_json)
        serializer = IPFSEventDescriptionDeserializer(
            data={'ipfs_hash': ipfs_hash})
        self.assertTrue(serializer.is_valid(), serializer.errors)
        self.assertIsNotNone(serializer.save())

    def test_create_centralized_oracle_instance(self):
        oracle = CentralizedOracleFactory()
        oracle.delete()
        # oracle.event_description
        event_description_json = {
            'title': oracle.event_description.title,
            'description': oracle.event_description.description,
            'resolutionDate':
            oracle.event_description.resolution_date.isoformat(),
            'outcomes': oracle.event_description.outcomes
        }

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

        oracle_event = {
            'address':
            oracle.factory,
            'params': [{
                'name': 'creator',
                'value': oracle.creator
            }, {
                'name': 'centralizedOracle',
                'value': oracle.address,
            }, {
                'name': 'ipfsHash',
                'value': oracle.event_description.ipfs_hash
            }]
        }

        s = CentralizedOracleInstanceSerializer(data=oracle_event, block=block)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()
        self.assertIsNotNone(instance)

    def test_create_outcome_token_instance(self):
        outcome_token = OutcomeTokenFactory()
        event = ScalarEventFactory()

        outcome_token_event = {
            'address':
            event.address,
            'params': [{
                'name': 'outcomeToken',
                'value': outcome_token.address,
            }, {
                'name': 'index',
                'value': outcome_token.index
            }]
        }
        outcome_token.delete()

        s = OutcomeTokenInstanceSerializer(data=outcome_token_event)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()
        self.assertIsNotNone(instance)

    def test_issuance_outcome_token(self):
        outcome_token = OutcomeTokenFactory()
        event = EventFactory()

        issuance_event = {
            'name':
            'Issuance',
            'address':
            outcome_token.address,
            'params': [{
                'name': 'owner',
                'value': event.address
            }, {
                'name': 'amount',
                'value': 20,
            }]
        }

        s = OutcomeTokenIssuanceSerializer(data=issuance_event)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()

        balance = OutcomeTokenBalance.objects.get(owner=event.address)
        self.assertEqual(balance.balance, 20)
        self.assertIsNotNone(instance)

        self.assertEqual(
            OutcomeToken.objects.get(
                address=outcome_token.address).total_supply,
            outcome_token.total_supply + 20)

    def test_revocation_outcome_token(self):
        balance = OutcomeTokenBalanceFactory()
        balance.balance = 20
        balance.save()

        issuance_event = {
            'name':
            'Revocation',
            'address':
            balance.outcome_token.address,
            'params': [{
                'name': 'owner',
                'value': balance.owner
            }, {
                'name': 'amount',
                'value': 20,
            }]
        }

        s = OutcomeTokenRevocationSerializer(data=issuance_event)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()

        self.assertEqual(
            OutcomeTokenBalance.objects.get(owner=balance.owner).balance, 0)
        self.assertIsNotNone(instance)

        self.assertEqual(
            OutcomeToken.objects.get(
                address=balance.outcome_token.address).total_supply,
            balance.outcome_token.total_supply - 20)

    def test_transfer_outcome_token(self):
        outcome_token_balance = OutcomeTokenBalanceFactory()
        event = EventFactory()
        outcome_token_balance.balance = 20
        outcome_token_balance.save()

        transfer_event = {
            'name':
            'Transfer',
            'address':
            outcome_token_balance.outcome_token.address,
            'params': [{
                'name': 'from',
                'value': outcome_token_balance.owner
            }, {
                'name': 'to',
                'value': event.address
            }, {
                'name': 'value',
                'value': outcome_token_balance.balance,
            }]
        }

        s = OutcomeTokenTransferSerializer(data=transfer_event)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()

        self.assertEqual(
            OutcomeTokenBalance.objects.get(
                owner=outcome_token_balance.owner).balance, 0)
        self.assertIsNotNone(instance)
        self.assertEqual(instance.owner, event.address)
        self.assertEqual(instance.balance, 20)

    def test_save_generic_tournament_participant(self):
        oracle = CentralizedOracleFactory()
        block = {
            'number': oracle.creation_block,
            'timestamp': mktime(oracle.creation_date_time.timetuple())
        }

        contract_address = "d833215cbcc3f914bd1c9ece3ee7bf8b14f841bb"
        registrant_address = "90f8bf6a479f320ead074411a4b0e7944ea8c9c1"
        registrant_address2 = "80f8bf6a479f320ead074411a4b0e7944ea8c9c2"
        registered_mainnet_address = "ffcf8fdee72ac11b5c542428b35eef5769c409f0"

        participant_event = {
            "address":
            contract_address,
            "name":
            "AddressRegistration",
            "params": [{
                "name": "registrant",
                "value": registrant_address,
            }, {
                "name": "registeredMainnetAddress",
                "value": registered_mainnet_address,
            }]
        }
        s = GenericTournamentParticipantEventSerializerTimestamped(
            data=participant_event, block=block)
        self.assertTrue(s.is_valid(), s.errors)
        self.assertEqual(TournamentParticipant.objects.all().count(), 0)
        instance = s.save()

        self.assertEqual(TournamentParticipant.objects.all().count(), 1)
        self.assertEqual(
            TournamentParticipant.objects.first().tournament_balance.balance,
            0)
        self.assertIsNotNone(instance)
        self.assertEqual(instance.address, registrant_address)
        self.assertEqual(instance.mainnet_address, registered_mainnet_address)

        web3_service = Web3Service(
            provider=EthereumTesterProvider(EthereumTester()))
        web3 = web3_service.web3
        checksumed_registrant_address2 = web3.toChecksumAddress(
            '0x' + registrant_address2)
        tournament_token_abi = load_json_file(
            abi_file_path('TournamentToken.json'))

        # create tournament token
        tournament_token = web3.eth.contract(
            abi=tournament_token_abi, bytecode=tournament_token_bytecode)
        tx_hash = tournament_token.constructor().transact()
        tournament_token_address = web3.eth.getTransactionReceipt(tx_hash).get(
            'contractAddress')
        self.assertIsNotNone(tournament_token_address)
        # Get token instance
        token_contract = web3.eth.contract(abi=tournament_token_abi,
                                           address=tournament_token_address)
        # Issue tokens
        tokens_amount = 100
        tx_hash = token_contract.functions.issue(
            [checksumed_registrant_address2],
            tokens_amount).transact({'from': web3.eth.coinbase})
        blockchain_balance = token_contract.functions.balanceOf(
            checksumed_registrant_address2).call()
        self.assertEqual(blockchain_balance, tokens_amount)

        # Save participant 2
        oracle = CentralizedOracleFactory()
        block = {
            'number': oracle.creation_block,
            'timestamp': mktime(oracle.creation_date_time.timetuple())
        }

        participant_with_tokens_event = {
            "address":
            contract_address,
            "name":
            "AddressRegistration",
            "params": [{
                "name": "registrant",
                "value": checksumed_registrant_address2[2:],
            }, {
                "name": "registeredMainnetAddress",
                "value": registered_mainnet_address,
            }]
        }

        # Mocks
        with self.settings(TOURNAMENT_TOKEN=tournament_token_address):
            # Mock Web3Service __new__ method to retrieve the same web3 instance used to deploy the contract
            Web3ServiceProvider.instance = web3_service
            s = GenericTournamentParticipantEventSerializerTimestamped(
                data=participant_with_tokens_event, block=block)
            self.assertTrue(s.is_valid(), s.errors)
            instance = s.save()
            self.assertEqual(TournamentParticipant.objects.all().count(), 2)
            self.assertEqual(
                TournamentParticipant.objects.first().tournament_balance.
                balance, tokens_amount)

    def test_save_uport_tournament_participant(self):
        oracle = CentralizedOracleFactory()
        block = {
            'number': oracle.creation_block,
            'timestamp': mktime(oracle.creation_date_time.timetuple())
        }

        identity = 'ebe4dd7a4a9e712e742862719aa04709cc6d80a6'

        participant_event = {
            'name':
            'IdentityCreated',
            'address':
            'abbcd5b340c80b5f1c0545c04c987b87310296ae',
            'params': [{
                'name': 'identity',
                'value': identity
            }, {
                'name': 'creator',
                'value': '50858f2c7873fac9398ed9c195d185089caa7967'
            }, {
                'name': 'owner',
                'value': '8f357b2c8071c2254afbc65907997f9adea6cc78',
            }, {
                'name': 'recoveryKey',
                'value': 'b67c2d2fcfa3e918e3f9a5218025ebdd12d26212'
            }]
        }

        s = UportTournamentParticipantSerializerEventSerializerTimestamped(
            data=participant_event, block=block)
        self.assertTrue(s.is_valid(), s.errors)
        self.assertEqual(TournamentParticipant.objects.all().count(), 0)
        instance = s.save()

        self.assertEqual(TournamentParticipant.objects.all().count(), 1)
        self.assertIsNotNone(instance)
        self.assertEqual(instance.address, identity)

    def test_tournament_issuance(self):
        participant_balance = TournamentParticipantBalanceFactory()
        participant = participant_balance.participant
        participant_event = {
            'name':
            'Issuance',
            'address':
            'not needed',
            'params': [{
                'name': 'owner',
                'value': participant.address
            }, {
                'name': 'amount',
                'value': 123
            }]
        }
        self.assertEqual(
            TournamentParticipantBalance.objects.get(
                participant=participant.address).balance,
            participant_balance.balance)
        s = TournamentTokenIssuanceSerializer(data=participant_event)
        self.assertTrue(s.is_valid(), s.errors)
        self.assertEqual(
            TournamentParticipantBalance.objects.get(
                participant=participant.address).balance,
            participant_balance.balance)
        instance = s.save()

        self.assertIsNotNone(instance)
        self.assertEqual(instance.participant.address, participant.address)
        self.assertEqual(instance.balance, participant_balance.balance + 123)

    def test_tournament_token_transfer(self):
        # Test the token transfer serializer
        participant_balance1 = TournamentParticipantBalanceFactory()
        participant1 = participant_balance1.participant
        participant_balance2 = TournamentParticipantBalanceFactory()
        participant2 = participant_balance2.participant

        transfer_event = {
            'name':
            'Transfer',
            'address':
            'not needed',
            'params': [{
                'name': 'from',
                'value': participant1.address
            }, {
                'name': 'to',
                'value': participant2.address
            }, {
                'name': 'value',
                'value': 150,
            }]
        }

        transfer_serializer = TournamentTokenTransferSerializer(
            data=transfer_event)
        self.assertTrue(transfer_serializer.is_valid(),
                        transfer_serializer.errors)
        instance = transfer_serializer.save()
        self.assertEqual(
            TournamentParticipantBalance.objects.get(
                participant=participant2.address).balance.__float__(),
            float(participant_balance2.balance + 150))
        self.assertEqual(
            TournamentParticipantBalance.objects.get(
                participant=participant1.address).balance.__float__(),
            float(participant_balance1.balance - 150))
class TestDaemonExec(TestCase):
    def setUp(self):
        self.web3 = Web3Service(
            provider=EthereumTesterProvider(EthereumTester())).web3
        self.provider = self.web3.providers[0]
        self.web3.eth.defaultAccount = self.web3.eth.coinbase

        # Mock web3
        self.daemon = DaemonFactory()
        self.ipfs = Ipfs()

        self.tx_data = {'from': self.web3.eth.accounts[0], 'gas': 1000000}

        # create oracles
        centralized_contract_factory = self.web3.eth.contract(
            abi=load_json_file(abi_file_path('CentralizedOracleFactory.json')),
            bytecode=centralized_oracle_bytecode)
        tx_hash = centralized_contract_factory.constructor().transact()
        self.centralized_oracle_factory_address = self.web3.eth.getTransactionReceipt(
            tx_hash).get('contractAddress')
        self.centralized_oracle_factory = self.web3.eth.contract(
            self.centralized_oracle_factory_address,
            abi=load_json_file(abi_file_path('CentralizedOracleFactory.json')))

        self.contracts = [{
            'NAME':
            'Centralized Oracle Factory',
            'EVENT_ABI':
            load_json_file(abi_file_path('CentralizedOracleFactory.json')),
            'EVENT_DATA_RECEIVER':
            'chainevents.event_receivers.CentralizedOracleFactoryReceiver',
            'ADDRESSES': [self.centralized_oracle_factory_address[2::]]
        }]

        self.listener_under_test = EventListener(contract_map=self.contracts,
                                                 provider=self.provider)

    def tearDown(self):
        self.provider.ethereum_tester.reset_to_genesis()
        self.assertEqual(0, self.web3.eth.blockNumber)

    def create_event_description(self):
        # Create event description
        event_description_factory = EventDescriptionFactory()
        categorical_event_description_json = {
            'title': ' '.join(event_description_factory.title),
            'description': ' '.join(event_description_factory.description),
            'resolutionDate':
            event_description_factory.resolution_date.isoformat(),
            'outcomes': ['A', 'B', 'C']
        }
        ipfs_hash = self.ipfs.post(categorical_event_description_json)
        return ipfs_hash

    def test_create_centralized_oracle(self):
        n_oracles = models.CentralizedOracle.objects.all().count()
        self.assertEqual(n_oracles, 0)
        ipfs_hash = self.create_event_description().encode()
        # Create centralized oracle
        tx_hash = self.centralized_oracle_factory.functions.createCentralizedOracle(
            ipfs_hash).transact(self.tx_data)
        self.assertIsNotNone(tx_hash)
        self.listener_under_test.execute()
        self.assertEqual(len(models.CentralizedOracle.objects.all()), 1)
Esempio n. 9
0
class TestEventReceiver(TestCase):
    def setUp(self):
        self.ipfs_api = Ipfs()

    def to_timestamp(self, datetime_instance):
        return mktime(datetime_instance.timetuple())

    def test_centralized_oracle_receiver(self):
        oracle = CentralizedOracleFactory()
        # saving event_description to IPFS
        event_description_json = {
            'title': oracle.event_description.title,
            'description': oracle.event_description.description,
            'resolutionDate':
            oracle.event_description.resolution_date.isoformat(),
            'outcomes': oracle.event_description.outcomes
        }

        ipfs_hash = self.ipfs_api.post(event_description_json)

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

        oracle_address = oracle.address
        oracle_event = {
            'name':
            'CentralizedOracleCreation',
            'address':
            oracle.factory,
            'params': [{
                'name': 'creator',
                'value': oracle.creator
            }, {
                'name': 'centralizedOracle',
                'value': oracle_address,
            }, {
                'name': 'ipfsHash',
                'value': ipfs_hash
            }]
        }
        oracle.delete()
        CentralizedOracleFactoryReceiver().save(oracle_event, block)
        saved_oracle1 = CentralizedOracle.objects.get(address=oracle_address)
        self.assertIsNotNone(saved_oracle1.pk)

        # Cannot save twice
        oracle2 = CentralizedOracleFactory()
        oracle_event.get('params')[0].update({'value': oracle2.creator})
        oracle_event.get('params')[2].update(
            {'value': oracle2.event_description.ipfs_hash})
        instance = CentralizedOracleFactoryReceiver().save(oracle_event, block)
        self.assertIsNone(instance)
        saved_oracle2 = CentralizedOracle.objects.get(address=oracle_address)
        self.assertEqual(saved_oracle1.event_description.ipfs_hash,
                         saved_oracle2.event_description.ipfs_hash)
        self.assertEqual(saved_oracle1.creator, saved_oracle2.creator)

    def test_scalar_event_receiver(self):
        oracle = OracleFactory()
        event = ScalarEventFactory()
        event_address = event.address

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

        scalar_event = {
            'address':
            event.factory,
            'name':
            'ScalarEventCreation',
            '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)
        self.assertIsNotNone(event.pk)

    def test_categorical_event_receiver(self):
        event = CategoricalEventFactory()
        oracle = OracleFactory()
        event_address = event.address

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

        categorical_event = {
            'address':
            event.factory,
            'name':
            'CategoricalEventCreation',
            'params': [{
                'name': 'creator',
                'value': event.creator
            }, {
                'name': 'collateralToken',
                'value': event.collateral_token
            }, {
                'name': 'oracle',
                'value': oracle.address
            }, {
                'name': 'outcomeCount',
                'value': 2
            }, {
                'name': 'categoricalEvent',
                'value': event_address
            }]
        }
        event.delete()

        EventFactoryReceiver().save(categorical_event, block)
        event = CategoricalEvent.objects.get(address=event_address)
        self.assertIsNotNone(event.pk)

    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)

    #
    # contract instances
    #
    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))

    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.assertEquals(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)

    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.assertEquals(outcome_token.total_supply,
                          outcome_token_saved.total_supply)

    def test_event_instance_outcome_assignment_receiver(self):
        event = CategoricalEventFactory()
        assignment_event = {
            'name': 'OutcomeAssignment',
            'address': event.address,
            'params': [{
                'name': 'outcome',
                'value': 1,
            }]
        }

        EventInstanceReceiver().save(assignment_event)
        saved_event = Event.objects.get(address=event.address)
        self.assertTrue(saved_event.is_winning_outcome_set)

    def test_event_instance_winnings_redemption_receiver(self):
        event = CategoricalEventFactory()
        redemption_event = {
            'name':
            'WinningsRedemption',
            'address':
            event.address,
            'params': [{
                'name': 'receiver',
                'value': event.creator,
            }, {
                'name': 'winnings',
                'value': 1
            }]
        }

        EventInstanceReceiver().save(redemption_event)
        saved_event = Event.objects.get(address=event.address)
        self.assertEquals(saved_event.redeemed_winnings,
                          event.redeemed_winnings + 1)

    def test_centralized_oracle_instance_owner_replacement_receiver(self):
        oracle0 = CentralizedOracleFactory()
        oracle1 = CentralizedOracleFactory()
        new_owner = oracle1.address
        change_owner_event = {
            'name': 'OwnerReplacement',
            'address': oracle0.address,
            'params': [{
                'name': 'newOwner',
                'value': new_owner
            }]
        }

        CentralizedOracleInstanceReceiver().save(change_owner_event)
        saved_oracle = CentralizedOracle.objects.get(address=oracle0.address)
        self.assertEquals(saved_oracle.owner, new_owner)

    def test_centralized_oracle_instance_outcome_assignment_receiver(self):
        oracle = CentralizedOracleFactory()
        assignment_event = {
            'name': 'OutcomeAssignment',
            'address': oracle.address,
            'params': [{
                'name': 'outcome',
                'value': 1,
            }]
        }

        CentralizedOracleInstanceReceiver().save(assignment_event)
        saved_oracle = CentralizedOracle.objects.get(address=oracle.address)
        self.assertTrue(saved_oracle.is_outcome_set)
        self.assertEqual(saved_oracle.outcome, 1)

    def test_market_funding_receiver(self):
        market = MarketFactory()
        funding_event = {
            'name': 'MarketFunding',
            'address': market.address,
            'params': [{
                'name': 'funding',
                'value': 100
            }]
        }

        MarketInstanceReceiver().save(funding_event)
        saved_market = Market.objects.get(address=market.address)
        self.assertEquals(saved_market.stage, 1)
        self.assertEquals(saved_market.funding, 100)

    def test_market_closing_receiver(self):
        market = MarketFactory()
        closing_event = {
            'name': 'MarketClosing',
            'address': market.address,
            'params': []
        }

        MarketInstanceReceiver().save(closing_event)
        saved_market = Market.objects.get(address=market.address)
        self.assertEquals(saved_market.stage, 2)

    def test_market_fee_withdrawal_receiver(self):
        market = MarketFactory()
        withdraw_event = {
            'name': 'FeeWithdrawal',
            'address': market.address,
            'params': [{
                'name': 'fees',
                'value': 10
            }]
        }

        MarketInstanceReceiver().save(withdraw_event)
        saved_market = Market.objects.get(address=market.address)
        # self.assertEquals(market.stage, 3)
        self.assertEquals(saved_market.withdrawn_fees,
                          market.withdrawn_fees + 10)

    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

    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

    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

    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)
Esempio n. 10
0
class TestSerializers(TestCase):
    def setUp(self):
        self.ipfs = Ipfs()

    def test_create_centralized_oracle(self):
        oracle = CentralizedOracleFactory()

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

        oracle_event = {
            'address':
            oracle.factory,
            'params': [{
                'name': 'creator',
                'value': oracle.creator
            }, {
                'name': 'centralizedOracle',
                'value': oracle.address,
            }, {
                'name': 'ipfsHash',
                'value': oracle.event_description.ipfs_hash[1:-7] + ''
            }]
        }
        oracle.delete()
        s = CentralizedOracleSerializer(data=oracle_event, block=block)
        # ipfs_hash not saved to IPFS
        self.assertFalse(s.is_valid(), s.errors)
        # oracle.event_description
        event_description_json = {
            'title': oracle.event_description.title,
            'description': oracle.event_description.description,
            'resolutionDate':
            oracle.event_description.resolution_date.isoformat(),
            'outcomes': ['Yes', 'No']
        }

        # save event_description to IPFS
        ipfs_hash = self.ipfs.post(event_description_json)
        oracle_event.get('params')[2]['value'] = ipfs_hash

        s = CentralizedOracleSerializer(data=oracle_event, block=block)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()
        self.assertIsNotNone(instance)

    def test_create_centralized_oracle_scalar_event_with_outcomes(self):
        oracle = CentralizedOracleFactory()

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

        oracle_event = {
            'address':
            oracle.factory,
            'params': [{
                'name': 'creator',
                'value': oracle.creator
            }, {
                'name': 'centralizedOracle',
                'value': oracle.address,
            }, {
                'name': 'ipfsHash',
                'value': 'something unknown'
            }]
        }
        # remove test oracle before creating it again
        oracle.delete()
        s = CentralizedOracleSerializer(data=oracle_event, block=block)
        # ipfs_hash not saved to IPFS
        self.assertFalse(s.is_valid(), s.errors)
        # oracle.event_description
        event_description_json = {
            'title': oracle.event_description.title,
            'description': oracle.event_description.description,
            'resolutionDate':
            oracle.event_description.resolution_date.isoformat(),
            'outcomes': [],
            'unit': 'unit',
            'decimals': 2
        }

        # save event_description to IPFS
        ipfs_hash = self.ipfs.post(event_description_json)
        oracle_event.get('params')[2]['value'] = ipfs_hash

        s = CentralizedOracleSerializer(data=oracle_event, block=block)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()
        self.assertIsNotNone(instance)

        self.assertEqual(
            ScalarEventDescription.objects.filter(
                ipfs_hash=instance.event_description.ipfs_hash).count(), 1)

    def test_event_description_different_outcomes(self):

        oracle = CentralizedOracleFactory()

        oracle.event_description.outcomes = ['Yes', 'No', 'Third']
        oracle.event_description.save()

        event = CategoricalEventFactory(oracle=oracle)

        # Categorical Event with different outcomes

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

        categorical_event = {
            'address':
            event.factory,
            'params': [{
                'name': 'creator',
                'value': event.creator
            }, {
                'name': 'collateralToken',
                'value': event.creator
            }, {
                'name': 'oracle',
                'value': oracle.address
            }, {
                'name': 'outcomeCount',
                'value': 2
            }, {
                'name': 'categoricalEvent',
                'value': event.address,
            }]
        }

        event.delete()

        s = CategoricalEventSerializer(data=categorical_event, block=block)
        self.assertFalse(s.is_valid())
        categorical_event['params'][3]['value'] = 3
        s2 = CategoricalEventSerializer(data=categorical_event, block=block)
        self.assertTrue(s2.is_valid(), s.errors)
        instance = s2.save()
        self.assertIsNotNone(instance)

    def test_create_scalar_with_categorical_description(self):

        event_description = CategoricalEventDescriptionFactory()
        oracle = CentralizedOracleFactory(event_description=event_description)

        # Scalar Event with different outcomes
        event = ScalarEventFactory()

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

        scalar_event = {
            'address':
            event.factory,
            'params': [{
                'name': 'creator',
                'value': event.creator
            }, {
                'name': 'collateralToken',
                'value': event.creator
            }, {
                'name': 'oracle',
                'value': oracle.address
            }, {
                'name': 'upperBound',
                'value': event.upper_bound
            }, {
                'name': 'lowerBound',
                'value': event.lower_bound
            }, {
                'name': 'scalarEvent',
                'value': event.address,
            }]
        }

        event.delete()
        s = ScalarEventSerializer(data=scalar_event, block=block)
        self.assertFalse(s.is_valid())
        scalar_event['params'][3]['value'] = 3
        scalar_descripion = ScalarEventDescriptionFactory()
        oracle.event_description = scalar_descripion
        oracle.save()
        s2 = ScalarEventSerializer(data=scalar_event, block=block)
        self.assertTrue(s2.is_valid(), s.errors)
        instance = s2.save()
        self.assertIsNotNone(instance)

    def test_create_scalar_event(self):
        event = ScalarEventFactory()
        event_description = ScalarEventDescriptionFactory()
        oracle = CentralizedOracleFactory(event_description=event_description)

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

        scalar_event = {
            'address':
            event.factory,
            'params': [{
                'name': 'creator',
                'value': event.creator
            }, {
                'name': 'collateralToken',
                'value': event.collateral_token
            }, {
                'name': 'oracle',
                'value': oracle.address
            }, {
                'name': 'upperBound',
                'value': 1
            }, {
                'name': 'lowerBound',
                'value': 0
            }]
        }
        event.delete()
        s = ScalarEventSerializer(data=scalar_event, block=block)
        self.assertFalse(s.is_valid(), s.errors)

        scalar_event.get('params').append({
            'name': 'scalarEvent',
            'value': event.address
        })

        s = ScalarEventSerializer(data=scalar_event, block=block)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()
        self.assertIsNotNone(instance)

    def test_create_categorical_event(self):
        event = CategoricalEventFactory()
        oracle = CentralizedOracleFactory()

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

        categorical_event = {
            'address':
            event.factory,
            'params': [{
                'name': 'creator',
                'value': event.creator
            }, {
                'name': 'collateralToken',
                'value': event.collateral_token
            }, {
                'name': 'oracle',
                'value': oracle.address
            }, {
                'name': 'outcomeCount',
                'value': 2
            }]
        }
        event.delete()
        s = CategoricalEventSerializer(data=categorical_event, block=block)
        self.assertFalse(s.is_valid(), s.errors)

        categorical_event.get('params').append({
            'name': 'categoricalEvent',
            'value': event.address
        })

        s = CategoricalEventSerializer(data=categorical_event, block=block)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()
        self.assertIsNotNone(instance)

    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)

    def test_create_categorical_event_description(self):
        event_description = CategoricalEventDescriptionFactory()
        event_description.delete()
        categorical_event_description_json = {
            'title': event_description.title,
            'description': event_description.description,
            'resolution_date': event_description.resolution_date.isoformat(),
            'outcomes': event_description.outcomes
        }
        ipfs_hash = self.ipfs.post(categorical_event_description_json)
        serializer = IPFSEventDescriptionDeserializer(
            data={'ipfs_hash': ipfs_hash})
        self.assertTrue(serializer.is_valid(), serializer.errors)
        self.assertIsNotNone(serializer.save())

    def test_create_scalar_event_description(self):
        event_description = ScalarEventDescriptionFactory()
        event_description.delete()
        scalar_event_description_json = {
            'title': event_description.title,
            'description': event_description.description,
            'resolution_date': event_description.resolution_date.isoformat(),
            'unit': event_description.unit,
            'decimals': event_description.decimals,
        }
        ipfs_hash = self.ipfs.post(scalar_event_description_json)
        serializer = IPFSEventDescriptionDeserializer(
            data={'ipfs_hash': ipfs_hash})
        self.assertTrue(serializer.is_valid(), serializer.errors)
        self.assertIsNotNone(serializer.save())

    def test_create_centralized_oracle_instance(self):
        oracle = CentralizedOracleFactory()
        oracle.delete()
        # oracle.event_description
        event_description_json = {
            'title': oracle.event_description.title,
            'description': oracle.event_description.description,
            'resolutionDate':
            oracle.event_description.resolution_date.isoformat(),
            'outcomes': oracle.event_description.outcomes
        }

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

        oracle_event = {
            'address':
            oracle.factory,
            'params': [{
                'name': 'creator',
                'value': oracle.creator
            }, {
                'name': 'centralizedOracle',
                'value': oracle.address,
            }, {
                'name': 'ipfsHash',
                'value': oracle.event_description.ipfs_hash
            }]
        }

        s = CentralizedOracleInstanceSerializer(data=oracle_event, block=block)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()
        self.assertIsNotNone(instance)

    def test_create_outcome_token_instance(self):
        outcome_token = OutcomeTokenFactory()
        event = ScalarEventFactory()

        outcome_token_event = {
            'address':
            event.address,
            'params': [{
                'name': 'outcomeToken',
                'value': outcome_token.address,
            }, {
                'name': 'index',
                'value': outcome_token.index
            }]
        }
        outcome_token.delete()

        s = OutcomeTokenInstanceSerializer(data=outcome_token_event)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()
        self.assertIsNotNone(instance)

    def test_issuance_outcome_token(self):
        outcome_token = OutcomeTokenFactory()
        event = EventFactory()

        issuance_event = {
            'name':
            'Issuance',
            'address':
            outcome_token.address,
            'params': [{
                'name': 'owner',
                'value': event.address
            }, {
                'name': 'amount',
                'value': 20,
            }]
        }

        s = OutcomeTokenIssuanceSerializer(data=issuance_event)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()

        balance = OutcomeTokenBalance.objects.get(owner=event.address)
        self.assertEqual(balance.balance, 20)
        self.assertIsNotNone(instance)

        self.assertEqual(
            OutcomeToken.objects.get(
                address=outcome_token.address).total_supply,
            outcome_token.total_supply + 20)

    def test_revocation_outcome_token(self):
        balance = OutcomeTokenBalanceFactory()
        balance.balance = 20
        balance.save()

        issuance_event = {
            'name':
            'Revocation',
            'address':
            balance.outcome_token.address,
            'params': [{
                'name': 'owner',
                'value': balance.owner
            }, {
                'name': 'amount',
                'value': 20,
            }]
        }

        s = OutcomeTokenRevocationSerializer(data=issuance_event)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()

        self.assertEqual(
            OutcomeTokenBalance.objects.get(owner=balance.owner).balance, 0)
        self.assertIsNotNone(instance)

        self.assertEqual(
            OutcomeToken.objects.get(
                address=balance.outcome_token.address).total_supply,
            balance.outcome_token.total_supply - 20)

    def test_transfer_outcome_token(self):
        outcome_token_balance = OutcomeTokenBalanceFactory()
        event = EventFactory()
        outcome_token_balance.balance = 20
        outcome_token_balance.save()

        transfer_event = {
            'name':
            'Transfer',
            'address':
            outcome_token_balance.outcome_token.address,
            'params': [{
                'name': 'from',
                'value': outcome_token_balance.owner
            }, {
                'name': 'to',
                'value': event.address
            }, {
                'name': 'value',
                'value': outcome_token_balance.balance,
            }]
        }

        s = OutcomeTokenTransferSerializer(data=transfer_event)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()

        self.assertEqual(
            OutcomeTokenBalance.objects.get(
                owner=outcome_token_balance.owner).balance, 0)
        self.assertIsNotNone(instance)
        self.assertEqual(instance.owner, event.address)
        self.assertEqual(instance.balance, 20)

    def test_save_tournament_participant(self):
        identity = 'ebe4dd7a4a9e712e742862719aa04709cc6d80a6'
        oracle = CentralizedOracleFactory()
        block = {
            'number': oracle.creation_block,
            'timestamp': mktime(oracle.creation_date_time.timetuple())
        }

        participant_event = {
            'name':
            'IdentityCreated',
            'address':
            'abbcd5b340c80b5f1c0545c04c987b87310296ae',
            'params': [{
                'name': 'identity',
                'value': identity
            }, {
                'name': 'creator',
                'value': '50858f2c7873fac9398ed9c195d185089caa7967'
            }, {
                'name': 'owner',
                'value': '8f357b2c8071c2254afbc65907997f9adea6cc78',
            }, {
                'name': 'recoveryKey',
                'value': 'b67c2d2fcfa3e918e3f9a5218025ebdd12d26212'
            }]
        }

        s = TournamentParticipantSerializer(data=participant_event,
                                            block=block)
        self.assertTrue(s.is_valid(), s.errors)
        self.assertEqual(TournamentParticipant.objects.all().count(), 0)
        instance = s.save()

        self.assertEqual(TournamentParticipant.objects.all().count(), 1)
        self.assertIsNotNone(instance)
        self.assertEqual(instance.address, identity)

    def test_tournament_issuance(self):
        participant_balance = TournamentParticipantBalanceFactory()
        participant = participant_balance.participant
        participant_event = {
            'name':
            'Issuance',
            'address':
            'not needed',
            'params': [{
                'name': 'owner',
                'value': participant.address
            }, {
                'name': 'amount',
                'value': 123
            }]
        }
        self.assertEqual(
            TournamentParticipantBalance.objects.get(
                participant=participant.address).balance,
            participant_balance.balance)
        s = TournamentTokenIssuanceSerializer(data=participant_event)
        self.assertTrue(s.is_valid(), s.errors)
        self.assertEqual(
            TournamentParticipantBalance.objects.get(
                participant=participant.address).balance,
            participant_balance.balance)
        instance = s.save()

        self.assertIsNotNone(instance)
        self.assertEqual(instance.participant.address, participant.address)
        self.assertEqual(instance.balance, participant_balance.balance + 123)

    def test_tournament_token_transfer(self):
        # Test the token transfer serializer
        participant_balance1 = TournamentParticipantBalanceFactory()
        participant1 = participant_balance1.participant
        participant_balance2 = TournamentParticipantBalanceFactory()
        participant2 = participant_balance2.participant

        transfer_event = {
            'name':
            'Transfer',
            'address':
            'not needed',
            'params': [{
                'name': 'from',
                'value': participant1.address
            }, {
                'name': 'to',
                'value': participant2.address
            }, {
                'name': 'value',
                'value': 150,
            }]
        }

        transfer_serializer = TournamentTokenTransferSerializer(
            data=transfer_event)
        self.assertTrue(transfer_serializer.is_valid(),
                        transfer_serializer.errors)
        instance = transfer_serializer.save()
        self.assertEqual(
            TournamentParticipantBalance.objects.get(
                participant=participant2.address).balance.__float__(),
            float(participant_balance2.balance + 150))
        self.assertEqual(
            TournamentParticipantBalance.objects.get(
                participant=participant1.address).balance.__float__(),
            float(participant_balance1.balance - 150))
Esempio n. 11
0
class TestSerializers(TestCase):
    def setUp(self):
        self.ipfs = Ipfs()

    def test_create_centralized_oracle(self):
        oracle = CentralizedOracleFactory()

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

        oracle_event = {
            'address':
            oracle.factory,
            'params': [{
                'name': 'creator',
                'value': oracle.creator
            }, {
                'name': 'centralizedOracle',
                'value': oracle.address,
            }, {
                'name': 'ipfsHash',
                'value': oracle.event_description.ipfs_hash[1:-7] + ''
            }]
        }
        oracle.delete()
        s = CentralizedOracleSerializer(data=oracle_event, block=block)
        # ipfs_hash not saved to IPFS
        self.assertFalse(s.is_valid(), s.errors)
        # oracle.event_description
        event_description_json = {
            'title': oracle.event_description.title,
            'description': oracle.event_description.description,
            'resolutionDate':
            oracle.event_description.resolution_date.isoformat(),
            'outcomes': ['Yes', 'No']
        }

        # save event_description to IPFS
        ipfs_hash = self.ipfs.post(event_description_json)
        oracle_event.get('params')[2]['value'] = ipfs_hash

        s = CentralizedOracleSerializer(data=oracle_event, block=block)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()
        self.assertIsNotNone(instance)

    def test_create_centralized_oracle_scalar_event_with_outcomes(self):
        oracle = CentralizedOracleFactory()

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

        oracle_event = {
            'address':
            oracle.factory,
            'params': [{
                'name': 'creator',
                'value': oracle.creator
            }, {
                'name': 'centralizedOracle',
                'value': oracle.address,
            }, {
                'name': 'ipfsHash',
                'value': 'something unknown'
            }]
        }
        # remove test oracle before creating it again
        oracle.delete()
        s = CentralizedOracleSerializer(data=oracle_event, block=block)
        # ipfs_hash not saved to IPFS
        self.assertFalse(s.is_valid(), s.errors)
        # oracle.event_description
        event_description_json = {
            'title': oracle.event_description.title,
            'description': oracle.event_description.description,
            'resolutionDate':
            oracle.event_description.resolution_date.isoformat(),
            'outcomes': [],
            'unit': 'unit',
            'decimals': 2
        }

        # save event_description to IPFS
        ipfs_hash = self.ipfs.post(event_description_json)
        oracle_event.get('params')[2]['value'] = ipfs_hash

        s = CentralizedOracleSerializer(data=oracle_event, block=block)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()
        self.assertIsNotNone(instance)

        self.assertEqual(
            ScalarEventDescription.objects.filter(
                ipfs_hash=instance.event_description.ipfs_hash).count(), 1)

    def test_event_description_different_outcomes(self):

        oracle = CentralizedOracleFactory()

        oracle.event_description.outcomes = ['Yes', 'No', 'Third']
        oracle.event_description.save()

        event = CategoricalEventFactory(oracle=oracle)

        # Categorical Event with different outcomes

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

        categorical_event = {
            'address':
            event.factory,
            'params': [{
                'name': 'creator',
                'value': event.creator
            }, {
                'name': 'collateralToken',
                'value': event.creator
            }, {
                'name': 'oracle',
                'value': oracle.address
            }, {
                'name': 'outcomeCount',
                'value': 2
            }, {
                'name': 'categoricalEvent',
                'value': event.address,
            }]
        }

        event.delete()

        s = CategoricalEventSerializer(data=categorical_event, block=block)
        self.assertFalse(s.is_valid())
        categorical_event['params'][3]['value'] = 3
        s2 = CategoricalEventSerializer(data=categorical_event, block=block)
        self.assertTrue(s2.is_valid(), s.errors)
        instance = s2.save()
        self.assertIsNotNone(instance)

    def test_create_scalar_with_categorical_description(self):

        event_description = CategoricalEventDescriptionFactory()
        oracle = CentralizedOracleFactory(event_description=event_description)

        # Scalar Event with different outcomes
        event = ScalarEventFactory()

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

        scalar_event = {
            'address':
            event.factory,
            'params': [{
                'name': 'creator',
                'value': event.creator
            }, {
                'name': 'collateralToken',
                'value': event.creator
            }, {
                'name': 'oracle',
                'value': oracle.address
            }, {
                'name': 'upperBound',
                'value': event.upper_bound
            }, {
                'name': 'lowerBound',
                'value': event.lower_bound
            }, {
                'name': 'scalarEvent',
                'value': event.address,
            }]
        }

        event.delete()
        s = ScalarEventSerializer(data=scalar_event, block=block)
        self.assertFalse(s.is_valid())
        scalar_event['params'][3]['value'] = 3
        scalar_descripion = ScalarEventDescriptionFactory()
        oracle.event_description = scalar_descripion
        oracle.save()
        s2 = ScalarEventSerializer(data=scalar_event, block=block)
        self.assertTrue(s2.is_valid(), s.errors)
        instance = s2.save()
        self.assertIsNotNone(instance)

    def test_create_scalar_event(self):
        event = ScalarEventFactory()
        event_description = ScalarEventDescriptionFactory()
        oracle = CentralizedOracleFactory(event_description=event_description)

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

        scalar_event = {
            'address':
            event.factory,
            'params': [{
                'name': 'creator',
                'value': event.creator
            }, {
                'name': 'collateralToken',
                'value': event.collateral_token
            }, {
                'name': 'oracle',
                'value': oracle.address
            }, {
                'name': 'upperBound',
                'value': 1
            }, {
                'name': 'lowerBound',
                'value': 0
            }]
        }
        event.delete()
        s = ScalarEventSerializer(data=scalar_event, block=block)
        self.assertFalse(s.is_valid(), s.errors)

        scalar_event.get('params').append({
            'name': 'scalarEvent',
            'value': event.address
        })

        s = ScalarEventSerializer(data=scalar_event, block=block)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()
        self.assertIsNotNone(instance)

    def test_create_categorical_event(self):
        event = CategoricalEventFactory()
        oracle = CentralizedOracleFactory()

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

        categorical_event = {
            'address':
            event.factory,
            'params': [{
                'name': 'creator',
                'value': event.creator
            }, {
                'name': 'collateralToken',
                'value': event.collateral_token
            }, {
                'name': 'oracle',
                'value': oracle.address
            }, {
                'name': 'outcomeCount',
                'value': 2
            }]
        }
        event.delete()
        s = CategoricalEventSerializer(data=categorical_event, block=block)
        self.assertFalse(s.is_valid(), s.errors)

        categorical_event.get('params').append({
            'name': 'categoricalEvent',
            'value': event.address
        })

        s = CategoricalEventSerializer(data=categorical_event, block=block)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()
        self.assertIsNotNone(instance)

    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)

    def test_create_categorical_event_description(self):
        event_description = CategoricalEventDescriptionFactory()
        event_description.delete()
        categorical_event_description_json = {
            'title': event_description.title,
            'description': event_description.description,
            'resolution_date': event_description.resolution_date.isoformat(),
            'outcomes': event_description.outcomes
        }
        ipfs_hash = self.ipfs.post(categorical_event_description_json)
        serializer = IPFSEventDescriptionDeserializer(
            data={'ipfs_hash': ipfs_hash})
        self.assertTrue(serializer.is_valid(), serializer.errors)
        self.assertIsNotNone(serializer.save())

    def test_create_scalar_event_description(self):
        event_description = ScalarEventDescriptionFactory()
        event_description.delete()
        scalar_event_description_json = {
            'title': event_description.title,
            'description': event_description.description,
            'resolution_date': event_description.resolution_date.isoformat(),
            'unit': event_description.unit,
            'decimals': event_description.decimals,
        }
        ipfs_hash = self.ipfs.post(scalar_event_description_json)
        serializer = IPFSEventDescriptionDeserializer(
            data={'ipfs_hash': ipfs_hash})
        self.assertTrue(serializer.is_valid(), serializer.errors)
        self.assertIsNotNone(serializer.save())

    def test_create_centralized_oracle_instance(self):
        oracle = CentralizedOracleFactory()
        oracle.delete()
        # oracle.event_description
        event_description_json = {
            'title': oracle.event_description.title,
            'description': oracle.event_description.description,
            'resolutionDate':
            oracle.event_description.resolution_date.isoformat(),
            'outcomes': oracle.event_description.outcomes
        }

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

        oracle_event = {
            'address':
            oracle.factory,
            'params': [{
                'name': 'creator',
                'value': oracle.creator
            }, {
                'name': 'centralizedOracle',
                'value': oracle.address,
            }, {
                'name': 'ipfsHash',
                'value': oracle.event_description.ipfs_hash
            }]
        }

        s = CentralizedOracleInstanceSerializer(data=oracle_event, block=block)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()
        self.assertIsNotNone(instance)

    def test_create_outcome_token_instance(self):
        outcome_token = OutcomeTokenFactory()
        event = ScalarEventFactory()

        outcome_token_event = {
            'address':
            event.address,
            'params': [{
                'name': 'outcomeToken',
                'value': outcome_token.address,
            }, {
                'name': 'index',
                'value': outcome_token.index
            }]
        }
        outcome_token.delete()

        s = OutcomeTokenInstanceSerializer(data=outcome_token_event)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()
        self.assertIsNotNone(instance)

    def test_issuance_outcome_token(self):
        outcome_token = OutcomeTokenFactory()
        event = EventFactory()

        issuance_event = {
            'name':
            'Issuance',
            'address':
            outcome_token.address,
            'params': [{
                'name': 'owner',
                'value': event.address
            }, {
                'name': 'amount',
                'value': 20,
            }]
        }

        s = OutcomeTokenIssuanceSerializer(data=issuance_event)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()

        balance = OutcomeTokenBalance.objects.get(owner=event.address)
        self.assertEqual(balance.balance, 20)
        self.assertIsNotNone(instance)

        self.assertEqual(
            OutcomeToken.objects.get(
                address=outcome_token.address).total_supply,
            outcome_token.total_supply + 20)

    def test_revocation_outcome_token(self):
        balance = OutcomeTokenBalanceFactory()
        balance.balance = 20
        balance.save()

        issuance_event = {
            'name':
            'Revocation',
            'address':
            balance.outcome_token.address,
            'params': [{
                'name': 'owner',
                'value': balance.owner
            }, {
                'name': 'amount',
                'value': 20,
            }]
        }

        s = OutcomeTokenRevocationSerializer(data=issuance_event)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()

        self.assertEqual(
            OutcomeTokenBalance.objects.get(owner=balance.owner).balance, 0)
        self.assertIsNotNone(instance)

        self.assertEqual(
            OutcomeToken.objects.get(
                address=balance.outcome_token.address).total_supply,
            balance.outcome_token.total_supply - 20)

    def test_transfer_outcome_token(self):
        outcome_token_balance = OutcomeTokenBalanceFactory()
        event = EventFactory()
        outcome_token_balance.balance = 20
        outcome_token_balance.save()

        transfer_event = {
            'name':
            'Transfer',
            'address':
            outcome_token_balance.outcome_token.address,
            'params': [{
                'name': 'from',
                'value': outcome_token_balance.owner
            }, {
                'name': 'to',
                'value': event.address
            }, {
                'name': 'value',
                'value': outcome_token_balance.balance,
            }]
        }

        s = OutcomeTokenTransferSerializer(data=transfer_event)
        self.assertTrue(s.is_valid(), s.errors)
        instance = s.save()

        self.assertEqual(
            OutcomeTokenBalance.objects.get(
                owner=outcome_token_balance.owner).balance, 0)
        self.assertIsNotNone(instance)
        self.assertEqual(instance.owner, event.address)
        self.assertEqual(instance.balance, 20)
Esempio n. 12
0
class TestDaemonExec(TestCase):
    def setUp(self):
        os.environ.update({'TESTRPC_GAS_LIMIT': '10000000000'})
        self.rpc = TestRPCProvider()
        web3_service = Web3Service(self.rpc)
        self.web3 = web3_service.web3
        # Mock web3
        self.daemon = DaemonFactory()
        self.ipfs = Ipfs()

        self.tx_data = {'from': self.web3.eth.accounts[0], 'gas': 100000000}

        # create oracles
        centralized_contract_factory = self.web3.eth.contract(
            abi=load_json_file(abi_file_path('CentralizedOracleFactory.json')),
            bytecode=centralized_oracle_bytecode)
        tx_hash = centralized_contract_factory.deploy()
        self.centralized_oracle_factory_address = self.web3.eth.getTransactionReceipt(
            tx_hash).get('contractAddress')
        self.centralized_oracle_factory = self.web3.eth.contract(
            self.centralized_oracle_factory_address,
            abi=load_json_file(abi_file_path('CentralizedOracleFactory.json')))

        self.contracts = [{
            'NAME':
            'Centralized Oracle Factory',
            'EVENT_ABI':
            load_json_file(abi_file_path('CentralizedOracleFactory.json')),
            'EVENT_DATA_RECEIVER':
            'chainevents.event_receivers.CentralizedOracleFactoryReceiver',
            'ADDRESSES': [self.centralized_oracle_factory_address[2::]]
        }]

        self.listener_under_test = EventListener(self.contracts)

    def tearDown(self):
        self.rpc.server.shutdown()
        self.rpc.server.server_close()
        self.rpc = None

    def create_event_description(self):
        # Create event description
        event_description_factory = EventDescriptionFactory()
        categorical_event_description_json = {
            'title': ' '.join(event_description_factory.title),
            'description': ' '.join(event_description_factory.description),
            'resolutionDate':
            event_description_factory.resolution_date.isoformat(),
            'outcomes': ['A', 'B', 'C']
        }
        ipfs_hash = self.ipfs.post(categorical_event_description_json)
        return ipfs_hash

    def test_create_centralized_oracle(self):
        n_oracles = models.CentralizedOracle.objects.all().count()
        self.assertEqual(n_oracles, 0)
        ipfs_hash = self.create_event_description()
        # Create centralized oracle
        tx_hash = self.centralized_oracle_factory.transact(
            self.tx_data).createCentralizedOracle(ipfs_hash)
        self.assertIsNotNone(tx_hash)
        self.listener_under_test.execute()
        self.assertEqual(len(models.CentralizedOracle.objects.all()), 1)