예제 #1
0
 def _set_game(self, parameters: Parameters, ledger_api: LedgerApi,
               contract: ERC1155Contract) -> None:
     """Set the contract and configuration based on provided parameters."""
     game = cast(Game, self.context.game)
     game.phase = Phase.CONTRACT_DEPLOYED
     self.context.logger.info("Setting up the game")
     configuration = Configuration(
         parameters.version_id,
         parameters.tx_fee,
     )
     configuration.good_id_to_name = generate_good_id_to_name(
         parameters.good_ids)
     configuration.currency_id_to_name = generate_currency_id_to_name(
         parameters.currency_ids)
     configuration.contract_address = parameters.contract_address
     game.conf = configuration
예제 #2
0
    def act(self) -> None:
        """
        Implement the act.

        :return: None
        """
        game = cast(Game, self.context.game)
        parameters = cast(Parameters, self.context.parameters)
        contract = cast(ERC1155Contract, self.context.contracts.erc1155)
        ledger_api = self.context.ledger_apis.get_api(parameters.ledger)
        if game.phase.value == Phase.CONTRACT_DEPLOYING.value:
            tx_receipt = ledger_api.get_transaction_receipt(
                tx_digest=game.contract_manager.deploy_tx_digest
            )
            if tx_receipt is None:
                self.context.logger.info(
                    "[{}]: Cannot verify whether contract deployment was successful. Retrying...".format(
                        self.context.agent_name
                    )
                )
            elif tx_receipt.status != 1:
                self.context.is_active = False
                self.context.warning(
                    "[{}]: The contract did not deployed successfully. Transaction hash: {}. Aborting!".format(
                        self.context.agent_name, tx_receipt.transactionHash.hex()
                    )
                )
            else:
                self.context.logger.info(
                    "[{}]: The contract was successfully deployed. Contract address: {}. Transaction hash: {}".format(
                        self.context.agent_name,
                        tx_receipt.contractAddress,
                        tx_receipt.transactionHash.hex(),
                    )
                )
                contract.set_address(ledger_api, tx_receipt.contractAddress)
                configuration = Configuration(parameters.version_id, parameters.tx_fee,)
                currency_ids = generate_currency_ids(parameters.nb_currencies, contract)
                configuration.currency_id_to_name = generate_currency_id_to_name(
                    currency_ids
                )
                good_ids = generate_good_ids(parameters.nb_goods, contract)
                configuration.good_id_to_name = generate_good_id_to_name(good_ids)
                configuration.contract_address = tx_receipt.contractAddress
                game.conf = configuration
                game.phase = Phase.CONTRACT_DEPLOYED
        elif game.phase.value == Phase.TOKENS_CREATING.value:
            tx_receipt = ledger_api.get_transaction_receipt(
                tx_digest=game.contract_manager.create_tokens_tx_digest
            )
            if tx_receipt is None:
                self.context.logger.info(
                    "[{}]: Cannot verify whether token creation was successful. Retrying...".format(
                        self.context.agent_name
                    )
                )
            elif tx_receipt.status != 1:
                self.context.is_active = False
                self.context.warning(
                    "[{}]: The token creation wasn't successful. Transaction hash: {}. Aborting!".format(
                        self.context.agent_name, tx_receipt.transactionHash.hex()
                    )
                )
            else:
                self.context.logger.info(
                    "[{}]: Successfully created the tokens. Transaction hash: {}".format(
                        self.context.agent_name, tx_receipt.transactionHash.hex()
                    )
                )
                game.phase = Phase.TOKENS_CREATED
        elif game.phase.value == Phase.TOKENS_MINTING.value:
            for (
                agent_addr,
                tx_digest,
            ) in game.contract_manager.mint_tokens_tx_digests.items():
                if agent_addr in game.contract_manager.confirmed_mint_tokens_agents:
                    continue
                tx_receipt = ledger_api.get_transaction_receipt(tx_digest=tx_digest)
                if tx_receipt is None:
                    self.context.logger.info(
                        "[{}]: Cannot verify whether token minting for agent_addr={} was successful. Retrying...".format(
                            self.context.agent_name, agent_addr
                        )
                    )
                elif tx_receipt.status != 1:
                    self.context.is_active = False
                    self.context.logger.warning(
                        "[{}]: The token minting for agent_addr={} wasn't successful. Transaction hash: {}. Aborting!".format(
                            self.context.agent_name,
                            agent_addr,
                            tx_receipt.transactionHash.hex(),
                        )
                    )
                else:
                    self.context.logger.info(
                        "[{}]: Successfully minted the tokens for agent_addr={}. Transaction hash: {}".format(
                            self.context.agent_name,
                            agent_addr,
                            tx_receipt.transactionHash.hex(),
                        )
                    )
                    game.contract_manager.add_confirmed_mint_tokens_agents(agent_addr)
                    if len(game.contract_manager.confirmed_mint_tokens_agents) == len(
                        game.initial_agent_states
                    ):
                        self.context.logger.info("All tokens minted!")
                        game.phase = Phase.TOKENS_MINTED
예제 #3
0
    def act(self) -> None:
        """
        Implement the act.

        :return: None
        """
        game = cast(Game, self.context.game)
        parameters = cast(Parameters, self.context.parameters)
        now = datetime.datetime.now()
        contract = cast(Contract, self.context.contracts.erc1155)

        if (contract.is_deployed and not self.is_items_created
                and game.phase.value == Phase.PRE_GAME.value):
            self.context.configuration = Configuration(  # type: ignore
                parameters.version_id,
                parameters.tx_fee,
            )
            self.context.configuration.set_good_id_to_name(
                parameters.nb_goods, contract)
            token_ids_dictionary = cast(
                Dict[str, str], self.context.configuration.good_id_to_name)
            self._token_ids = [
                int(token_id) for token_id in token_ids_dictionary.keys()
            ]
            self.context.logger.info("Creating the items.")
            self._currency_id = self.token_ids[0]
            self._token_ids = self.token_ids[1:11]
            transaction_message = self._create_items(self.token_ids)
            self.context.decision_maker_message_queue.put_nowait(
                transaction_message)

            transaction_message = self._create_items(self.currency_id)
            self.context.decision_maker_message_queue.put_nowait(
                transaction_message)
            time.sleep(10)
        if (game.phase.value == Phase.PRE_GAME.value
                and parameters.registration_start_time < now <
                parameters.start_time):

            game.phase = Phase.GAME_REGISTRATION
            self._register_tac()
            self.context.logger.info(
                "[{}]: TAC open for registration until: {}".format(
                    self.context.agent_name, parameters.start_time))
        elif (game.phase.value == Phase.GAME_REGISTRATION.value
              and parameters.start_time < now < parameters.end_time):
            if game.registration.nb_agents < parameters.min_nb_agents:
                self._cancel_tac()
                game.phase = Phase.POST_GAME
                self._unregister_tac()
            else:
                self.context.logger.info("Setting Up the TAC game.")
                game.phase = Phase.GAME_SETUP
                # self._start_tac()
                game.create()
                self._unregister_tac()
                self.context.logger.info("Mint objects after registration.")
                for agent in self.context.configuration.agent_addr_to_name.keys(
                ):
                    self._mint_objects(
                        is_batch=True,
                        address=agent,
                    )
                    # Mint the game currency.
                    self._mint_objects(
                        is_batch=False,
                        address=agent,
                    )
                    self.agent_counter += 1
                game.phase = Phase.GAME
        elif (game.phase.value == Phase.GAME.value
              and parameters.start_time < now < parameters.end_time
              and self.can_start):
            self.context.logger.info("Starting the TAC game.")
            self._start_tac()
        elif game.phase.value == Phase.GAME.value and now > parameters.end_time:
            self._cancel_tac()
            game.phase = Phase.POST_GAME
예제 #4
0
    def test_act_iv(self):
        """Test the act method of the tac behaviour where phase is GAME_SETUP and reg_end_time < now < start_time."""
        # setup
        self.game._phase = Phase.GAME_SETUP

        mocked_now = self._mock_time("00:05")

        self.parameters._min_nb_agents = 2
        self.game._registration.register_agent(self.agent_1_address, self.agent_1_name)
        self.game._registration.register_agent(self.agent_2_address, self.agent_2_name)

        self.game._conf = Configuration(
            "v1",
            1,
            self.game.registration.agent_addr_to_name,
            {"1": "currency_name"},
            {"2": "good_1", "3": "good_2"},
        )

        self.parameters._contract_address = "some_contract_address"

        # operation
        with patch("datetime.datetime", new=mocked_now):
            with patch.object(self.logger, "log") as mock_logger:
                self.tac_behaviour.act()

        # after
        assert self.game.phase == Phase.TOKENS_CREATION_PROPOSAL

        # _request_create_items_transaction
        self.assert_quantity_in_outbox(1)
        message = self.get_message_from_outbox()
        has_attributes, error_str = self.message_has_attributes(
            actual_message=message,
            message_type=ContractApiMessage,
            performative=ContractApiMessage.Performative.GET_RAW_TRANSACTION,
            to=LEDGER_API_ADDRESS,
            sender=self.skill.skill_context.agent_address,
            ledger_id=self.parameters.ledger_id,
            contract_id=self.parameters.contract_id,
            contract_address=self.parameters.contract_address,
            callable=ContractApiDialogue.Callable.GET_CREATE_BATCH_TRANSACTION.value,
            kwargs=ContractApiMessage.Kwargs(
                {
                    "deployer_address": self.skill.skill_context.agent_address,
                    "token_ids": [2, 3, 1],
                }
            ),
        )
        assert has_attributes, error_str
        assert (
            cast(
                ContractApiDialogue, self.contract_api_dialogues.get_dialogue(message)
            ).terms
            == self.parameters.get_create_token_terms()
        )
        assert (
            cast(
                ContractApiDialogue, self.contract_api_dialogues.get_dialogue(message)
            ).callable
            == ContractApiDialogue.Callable.GET_CREATE_BATCH_TRANSACTION
        )
        mock_logger.assert_any_call(
            logging.INFO, "requesting create items transaction..."
        )