Beispiel #1
0
    def _handle_transaction_receipt(
            self, ledger_api_msg: LedgerApiMessage,
            ledger_api_dialogue: LedgerApiDialogue) -> None:
        """
        Handle a message of transaction_receipt performative.

        :param ledger_api_message: the ledger api message
        """
        is_transaction_successful = LedgerApis.is_transaction_settled(
            ledger_api_msg.transaction_receipt.ledger_id,
            ledger_api_msg.transaction_receipt.receipt,
        )
        if is_transaction_successful:
            self.context.logger.info(
                "transaction was successfully settled. Transaction receipt={}".
                format(ledger_api_msg.transaction_receipt))
            strategy = cast(Strategy, self.context.strategy)

            contract_api_dialogue = (
                ledger_api_dialogue.associated_signing_dialogue.
                associated_contract_api_dialogue)

            transaction_label = contract_api_dialogue.terms.kwargs.get(
                "label", "None")

            if not strategy.is_contract_deployed and transaction_label == "deploy":
                contract_address = cast(
                    Optional[str],
                    ledger_api_msg.transaction_receipt.receipt.get(
                        "contractAddress", None),
                )
                if contract_address is None:
                    raise ValueError(
                        "No contract address found.")  # pragma: nocover
                strategy.contract_address = contract_address
                strategy.is_contract_deployed = is_transaction_successful
                strategy.is_behaviour_active = is_transaction_successful
                self.context.logger.info(
                    "Oracle contract successfully deployed!")
            elif (not strategy.is_oracle_role_granted
                  and transaction_label == "grant_role"):
                strategy.is_oracle_role_granted = is_transaction_successful
                if is_transaction_successful:
                    self.context.logger.info(
                        "Oracle role successfully granted!")
                else:  # pragma: nocover
                    self.context.logger.info("Failed to grant oracle role")
            elif transaction_label == "update":
                self.context.logger.info("Oracle value successfully updated!")
                if self.context.prometheus_dialogues.enabled:
                    metric_name = "num_oracle_updates"
                    self.context.behaviours.simple_oracle_behaviour.update_prometheus_metric(
                        metric_name, "inc", 1.0, {})
            else:  # pragma: nocover
                self.context.logger.error("unexpected transaction receipt!")
        else:
            self.context.logger.error(
                "transaction failed. Transaction receipt={}".format(
                    ledger_api_msg.transaction_receipt))
Beispiel #2
0
    def _handle_transaction_receipt(
            self, ledger_api_msg: LedgerApiMessage,
            ledger_api_dialogue: LedgerApiDialogue) -> None:
        """
        Handle a message of transaction_receipt performative.

        :param ledger_api_message: the ledger api message
        """
        is_transaction_successful = LedgerApis.is_transaction_settled(
            ledger_api_msg.transaction_receipt.ledger_id,
            ledger_api_msg.transaction_receipt.receipt,
        )
        if is_transaction_successful:
            self.context.logger.info(
                "transaction was successfully settled. Transaction receipt={}".
                format(ledger_api_msg.transaction_receipt))
            strategy = cast(Strategy, self.context.strategy)

            contract_api_dialogue = (
                ledger_api_dialogue.associated_signing_dialogue.
                associated_contract_api_dialogue)

            transaction_label = contract_api_dialogue.terms.kwargs.get(
                "label", "None")

            if (not strategy.is_client_contract_deployed
                    and transaction_label == "deploy"):
                client_contract_address = cast(
                    str,
                    ledger_api_msg.transaction_receipt.receipt.get(
                        "contractAddress", None),
                )
                strategy.client_contract_address = client_contract_address
                strategy.is_client_contract_deployed = is_transaction_successful
                strategy.is_behaviour_active = is_transaction_successful
                self.context.logger.info(
                    "Oracle client contract successfully deployed!")
            elif (not strategy.is_oracle_transaction_approved
                  and transaction_label == "approve"):
                strategy.is_oracle_transaction_approved = is_transaction_successful
                if is_transaction_successful:
                    self.context.logger.info(
                        "Oracle client transactions approved!")
                else:  # pragma: nocover
                    self.context.logger.info(
                        "Failed to approve oracle client transactions")
            elif transaction_label == "query":
                self.context.logger.info(
                    "Oracle value successfully requested!")
            else:  # pragma nocover
                self.context.logger.error("unexpected transaction receipt!")
        else:
            self.context.logger.error(
                "transaction failed. Transaction receipt={}".format(
                    ledger_api_msg.transaction_receipt))
Beispiel #3
0
    def _handle_transaction_receipt(
            self, ledger_api_msg: LedgerApiMessage,
            ledger_api_dialogue: LedgerApiDialogue) -> None:
        """
        Handle a message of balance performative.

        :param ledger_api_message: the ledger api message
        :param ledger_api_dialogue: the ledger api dialogue
        """
        fipa_dialogue = ledger_api_dialogue.associated_fipa_dialogue
        is_settled = LedgerApis.is_transaction_settled(
            fipa_dialogue.terms.ledger_id,
            ledger_api_msg.transaction_receipt.receipt)
        is_valid = LedgerApis.is_transaction_valid(
            fipa_dialogue.terms.ledger_id,
            ledger_api_msg.transaction_receipt.transaction,
            fipa_dialogue.terms.sender_address,
            fipa_dialogue.terms.counterparty_address,
            fipa_dialogue.terms.nonce,
            fipa_dialogue.terms.counterparty_payable_amount,
        )
        if is_settled and is_valid:
            last_message = cast(Optional[FipaMessage],
                                fipa_dialogue.last_incoming_message)
            assert last_message is not None, "Cannot retrieve last fipa message."
            inform_msg = FipaMessage(
                message_id=last_message.message_id + 1,
                dialogue_reference=fipa_dialogue.dialogue_label.
                dialogue_reference,
                target=last_message.message_id,
                performative=FipaMessage.Performative.INFORM,
                info=fipa_dialogue.data_for_sale,
            )
            inform_msg.counterparty = last_message.counterparty
            fipa_dialogue.update(inform_msg)
            self.context.outbox.put_message(message=inform_msg)
            fipa_dialogues = cast(FipaDialogues, self.context.fipa_dialogues)
            fipa_dialogues.dialogue_stats.add_dialogue_endstate(
                FipaDialogue.EndState.SUCCESSFUL,
                fipa_dialogue.is_self_initiated)
            self.context.logger.info(
                "[{}]: transaction confirmed, sending data={} to buyer={}.".
                format(
                    self.context.agent_name,
                    fipa_dialogue.data_for_sale,
                    last_message.counterparty[-5:],
                ))
        else:
            self.context.logger.info(
                "[{}]: transaction_receipt={} not settled or not valid, aborting"
                .format(self.context.agent_name,
                        ledger_api_msg.transaction_receipt))
    def _handle_transaction_receipt(
        self, ledger_api_msg: LedgerApiMessage, ledger_api_dialogue: LedgerApiDialogue
    ) -> None:
        """
        Handle a message of transaction_receipt performative.

        :param ledger_api_message: the ledger api message
        """
        strategy = cast(Strategy, self.context.strategy)
        is_transaction_successful = LedgerApis.is_transaction_settled(
            ledger_api_msg.transaction_receipt.ledger_id,
            ledger_api_msg.transaction_receipt.receipt,
        )
        contract_reference = ledger_api_dialogue._associated_signing_dialogue._associated_contract_api_dialogue.dialogue_label.dialogue_reference[
            0
        ]
        for contract, status in strategy._deployment_status.items():
            if status[0] is None:
                continue
            elif status[1] == contract_reference:
                self.context.logger.info(
                    "retrieved deployment {contract}".format(contract=contract)
                )
                strategy.deployment_status[contract] = (
                    "deployed",
                    ledger_api_msg.transaction_receipt.receipt["contractAddress"],
                )
                self.context.logger.info(
                    f"** {ledger_api_msg.transaction_receipt.receipt['contractAddress']}  Retireved and stored)"
                )
                #              if contract in ["ethoptions_create_option", "btcoptions_create_option"]:
                #                  strategy.update_option(
                #                     strategy.current_order_id, {"status_code_id": 3})
                strategy.deployment_status["status"] = "pending"
        if is_transaction_successful:
            self.context.logger.info(
                "transaction was successfully settled. Transaction receipt={}".format(
                    "ledger_api_msg.transaction_receipt"
                )
            )
        else:
            self.context.logger.error(
                "transaction failed. Transaction receipt={}".format(
                    ledger_api_msg.transaction_receipt
                )
            )
            raise ValueError("Ledger message failed!")
Beispiel #5
0
    def _handle_transaction_receipt(self, ledger_api_msg: LedgerApiMessage) -> None:
        """
        Handle a message of transaction_receipt performative.

        :param ledger_api_message: the ledger api message
        """
        is_transaction_successful = LedgerApis.is_transaction_settled(
            ledger_api_msg.transaction_receipt.ledger_id,
            ledger_api_msg.transaction_receipt.receipt,
        )
        if is_transaction_successful:
            self.context.logger.info(
                "transaction was successfully settled. Transaction receipt={}".format(
                    ledger_api_msg.transaction_receipt
                )
            )
            strategy = cast(Strategy, self.context.strategy)
            if not strategy.is_contract_deployed:
                contract_address = cast(
                    Optional[str],
                    ledger_api_msg.transaction_receipt.receipt.get(
                        "contractAddress", None
                    ),
                )
                if contract_address is None:
                    raise ValueError("No contract address found.")  # pragma: nocover
                strategy.contract_address = contract_address
                strategy.is_contract_deployed = is_transaction_successful
                strategy.is_behaviour_active = is_transaction_successful
            elif not strategy.is_tokens_created:
                strategy.is_tokens_created = is_transaction_successful
                strategy.is_behaviour_active = is_transaction_successful
            elif not strategy.is_tokens_minted:
                strategy.is_tokens_minted = is_transaction_successful
                strategy.is_behaviour_active = is_transaction_successful
            elif strategy.is_tokens_minted:
                self.context.is_active = False
                self.context.logger.info("demo finished!")
            else:
                self.context.logger.error("unexpected transaction receipt!")
        else:
            self.context.logger.error(
                "transaction failed. Transaction receipt={}".format(
                    ledger_api_msg.transaction_receipt
                )
            )
Beispiel #6
0
    def _handle_transaction_receipt(
            self, ledger_api_msg: LedgerApiMessage,
            ledger_api_dialogue: LedgerApiDialogue) -> None:
        """
        Handle a message of transaction_receipt performative.

        :param ledger_api_message: the ledger api message
        :param ledger_api_dialogue: the ledger api dialogue
        """
        is_transaction_successful = LedgerApis.is_transaction_settled(
            ledger_api_msg.transaction_receipt.ledger_id,
            ledger_api_msg.transaction_receipt.receipt,
        )
        signing_dialogue = ledger_api_dialogue.associated_signing_dialogue
        contract_api_dialogue = signing_dialogue.associated_contract_api_dialogue
        if is_transaction_successful:
            self.context.logger.info(
                "transaction was successfully settled. Transaction receipt={}".
                format(ledger_api_msg.transaction_receipt))
            parameters = cast(Parameters, self.context.parameters)
            game = cast(Game, self.context.game)
            if (contract_api_dialogue.callable ==
                    ContractApiDialogue.Callable.GET_DEPLOY_TRANSACTION):
                contract_address = ledger_api_msg.transaction_receipt.receipt.get(
                    "contractAddress", None)
                parameters.contract_address = contract_address
                game.phase = Phase.CONTRACT_DEPLOYED
                self.context.logger.info("contract deployed.")
            elif (contract_api_dialogue.callable ==
                  ContractApiDialogue.Callable.GET_CREATE_BATCH_TRANSACTION):
                game.phase = Phase.TOKENS_CREATED
                self.context.logger.info("tokens created.")
            elif (contract_api_dialogue.callable ==
                  ContractApiDialogue.Callable.GET_MINT_BATCH_TRANSACTION):
                self.context.logger.info("tokens minted.")
                parameters.nb_completed_minting += 1
                game.is_allowed_to_mint = True
                if game.registration.nb_agents == parameters.nb_completed_minting:
                    game.phase = Phase.TOKENS_MINTED
                    self.context.logger.info("all tokens minted.")
            else:
                self.context.logger.error("unexpected transaction receipt!")
        else:
            self.context.logger.error(
                "transaction failed. Transaction receipt={}".format(
                    ledger_api_msg.transaction_receipt))
Beispiel #7
0
    def _handle_transaction_receipt(
            self, ledger_api_msg: LedgerApiMessage,
            ledger_api_dialogue: LedgerApiDialogue) -> None:
        """
        Handle a message of balance performative.

        :param ledger_api_message: the ledger api message
        :param ledger_api_dialogue: the ledger api dialogue
        """
        fipa_dialogue = ledger_api_dialogue.associated_fipa_dialogue
        is_settled = LedgerApis.is_transaction_settled(
            fipa_dialogue.terms.ledger_id,
            ledger_api_msg.transaction_receipt.receipt)
        tx_behaviour = cast(GenericTransactionBehaviour,
                            self.context.behaviours.transaction)
        if is_settled:
            tx_behaviour.finish_processing(ledger_api_dialogue)
            ledger_api_msg_ = cast(Optional[LedgerApiMessage],
                                   ledger_api_dialogue.last_outgoing_message)
            if ledger_api_msg_ is None:
                raise ValueError(  # pragma: nocover
                    "Could not retrieve last ledger_api message")
            fipa_msg = cast(Optional[FipaMessage],
                            fipa_dialogue.last_incoming_message)
            if fipa_msg is None:
                raise ValueError("Could not retrieve last fipa message")
            inform_msg = fipa_dialogue.reply(
                performative=FipaMessage.Performative.INFORM,
                target_message=fipa_msg,
                info={
                    "transaction_digest":
                    ledger_api_msg_.transaction_digest.body
                },
            )
            self.context.outbox.put_message(message=inform_msg)
            self.context.logger.info(
                "transaction confirmed, informing counterparty={} of transaction digest."
                .format(
                    fipa_dialogue.dialogue_label.dialogue_opponent_addr[-5:],
                ))
        else:
            tx_behaviour.failed_processing(ledger_api_dialogue)
            self.context.logger.info(
                "transaction_receipt={} not settled or not valid, aborting".
                format(ledger_api_msg.transaction_receipt))
Beispiel #8
0
    def _handle_transaction_receipt(
            self, ledger_api_msg: LedgerApiMessage,
            ledger_api_dialogue: LedgerApiDialogue) -> None:
        """
        Handle a message of balance performative.

        :param ledger_api_message: the ledger api message
        :param ledger_api_dialogue: the ledger api dialogue
        """
        ml_trade_dialogue = ledger_api_dialogue.associated_ml_trade_dialogue
        is_settled = LedgerApis.is_transaction_settled(
            ml_trade_dialogue.terms.ledger_id,
            ledger_api_msg.transaction_receipt.receipt,
        )
        tx_behaviour = cast(TransactionBehaviour,
                            self.context.behaviours.transaction)
        if is_settled:
            tx_behaviour.finish_processing(ledger_api_dialogue)
            ledger_api_msg_ = cast(Optional[LedgerApiMessage],
                                   ledger_api_dialogue.last_outgoing_message)
            if ledger_api_msg_ is None:
                raise ValueError(  # pragma: nocover
                    "Could not retrieve last ledger_api message")
            ml_trade_msg = cast(Optional[MlTradeMessage],
                                ml_trade_dialogue.last_incoming_message)
            if ml_trade_msg is None:
                raise ValueError("Could not retrieve last ml_trade message")
            ml_accept = ml_trade_dialogue.reply(
                performative=MlTradeMessage.Performative.ACCEPT,
                target_message=ml_trade_msg,
                tx_digest=ledger_api_msg_.transaction_digest.body,
                terms=ml_trade_msg.terms,
            )
            self.context.outbox.put_message(message=ml_accept)
            self.context.logger.info(
                "informing counterparty={} of transaction digest={}.".format(
                    ml_trade_msg.sender[-5:],
                    ledger_api_msg_.transaction_digest,
                ))
        else:
            tx_behaviour.failed_processing(ledger_api_dialogue)
            self.context.logger.info(
                "transaction_receipt={} not settled or not valid, aborting".
                format(ledger_api_msg.transaction_receipt))
Beispiel #9
0
    def _handle_transaction_receipt(self,
                                    ledger_api_msg: LedgerApiMessage) -> None:
        """
        Handle a message of transaction_receipt performative.

        :param ledger_api_message: the ledger api message
        """
        is_transaction_successful = LedgerApis.is_transaction_settled(
            ledger_api_msg.transaction_receipt.ledger_id,
            ledger_api_msg.transaction_receipt.receipt,
        )
        if is_transaction_successful:
            self.context.logger.info(
                "transaction was successfully settled. Transaction receipt={}".
                format(ledger_api_msg.transaction_receipt))
        else:
            self.context.logger.error(
                "transaction failed. Transaction receipt={}".format(
                    ledger_api_msg.transaction_receipt))
Beispiel #10
0
def wait_tx_settled(identifier: str,
                    tx_digest: str,
                    timeout: float = DEFAULT_SETTLE_TIMEOUT) -> None:
    """
    Wait transaction is settled succesfuly.

    :param identifier: str, ledger id
    :param tx_digest: str, transaction digest
    :param timeout: int, timeout in seconds efore timeout error raised

    :return: None
    raises TimeoutError on timeout
    """
    t = time.time()
    while True:
        if time.time() - t > timeout:
            raise TimeoutError()
        if LedgerApis.is_transaction_settled(identifier, tx_digest):
            return
        time.sleep(1)
Beispiel #11
0
async def test_send_signed_transaction_ethereum(
        ledger_apis_connection: Connection):
    """Test send signed transaction with Ethereum APIs."""
    import aea  # noqa # to load registries

    crypto1 = make_crypto(ETHEREUM, private_key_path=ETHEREUM_PRIVATE_KEY_PATH)
    crypto2 = make_crypto(ETHEREUM)
    ledger_api_dialogues = LedgerApiDialogues(crypto1.address)

    amount = 40000
    fee = 30000

    request, ledger_api_dialogue = ledger_api_dialogues.create(
        counterparty=str(ledger_apis_connection.connection_id),
        performative=LedgerApiMessage.Performative.GET_RAW_TRANSACTION,
        terms=Terms(
            ledger_id=ETHEREUM,
            sender_address=crypto1.address,
            counterparty_address=crypto2.address,
            amount_by_currency_id={"ETH": -amount},
            quantities_by_good_id={"some_service_id": 1},
            is_sender_payable_tx_fee=True,
            nonce="",
            fee_by_currency_id={"ETH": fee},
            chain_id=3,
        ),
    )
    request = cast(LedgerApiMessage, request)
    envelope = Envelope(
        to=request.to,
        sender=request.sender,
        protocol_id=request.protocol_id,
        message=request,
    )
    await ledger_apis_connection.send(envelope)
    await asyncio.sleep(0.01)
    response = await ledger_apis_connection.receive()

    assert response is not None
    assert type(response.message) == LedgerApiMessage
    response_message = cast(LedgerApiMessage, response.message)
    assert (response_message.performative ==
            LedgerApiMessage.Performative.RAW_TRANSACTION)
    response_dialogue = ledger_api_dialogues.update(response_message)
    assert response_dialogue == ledger_api_dialogue
    assert type(response_message.raw_transaction) == RawTransaction
    assert response_message.raw_transaction.ledger_id == request.terms.ledger_id

    signed_transaction = crypto1.sign_transaction(
        response_message.raw_transaction.body)
    request = cast(
        LedgerApiMessage,
        ledger_api_dialogue.reply(
            performative=LedgerApiMessage.Performative.SEND_SIGNED_TRANSACTION,
            target_message=response_message,
            signed_transaction=SignedTransaction(ETHEREUM, signed_transaction),
        ),
    )
    envelope = Envelope(
        to=request.to,
        sender=request.sender,
        protocol_id=request.protocol_id,
        message=request,
    )
    await ledger_apis_connection.send(envelope)
    await asyncio.sleep(0.01)
    response = await ledger_apis_connection.receive()

    assert response is not None
    assert type(response.message) == LedgerApiMessage
    response_message = cast(LedgerApiMessage, response.message)
    assert (response_message.performative !=
            LedgerApiMessage.Performative.ERROR
            ), f"Received error: {response_message.message}"
    assert (response_message.performative ==
            LedgerApiMessage.Performative.TRANSACTION_DIGEST)
    response_dialogue = ledger_api_dialogues.update(response_message)
    assert response_dialogue == ledger_api_dialogue
    assert type(response_message.transaction_digest) == TransactionDigest
    assert type(response_message.transaction_digest.body) == str
    assert (response_message.transaction_digest.ledger_id ==
            request.signed_transaction.ledger_id)
    assert type(response_message.transaction_digest.body.startswith("0x"))

    request = cast(
        LedgerApiMessage,
        ledger_api_dialogue.reply(
            performative=LedgerApiMessage.Performative.GET_TRANSACTION_RECEIPT,
            target_message=response_message,
            transaction_digest=response_message.transaction_digest,
        ),
    )
    envelope = Envelope(
        to=request.to,
        sender=request.sender,
        protocol_id=request.protocol_id,
        message=request,
    )
    await ledger_apis_connection.send(envelope)
    await asyncio.sleep(0.01)
    response = await ledger_apis_connection.receive()

    assert response is not None
    assert type(response.message) == LedgerApiMessage
    response_message = cast(LedgerApiMessage, response.message)
    assert (response_message.performative ==
            LedgerApiMessage.Performative.TRANSACTION_RECEIPT)
    response_dialogue = ledger_api_dialogues.update(response_message)
    assert response_dialogue == ledger_api_dialogue
    assert type(response_message.transaction_receipt) == TransactionReceipt
    assert response_message.transaction_receipt.receipt is not None
    assert response_message.transaction_receipt.transaction is not None
    assert (response_message.transaction_receipt.ledger_id ==
            request.transaction_digest.ledger_id)
    assert LedgerApis.is_transaction_settled(
        response_message.transaction_receipt.ledger_id,
        response_message.transaction_receipt.receipt,
    ), "Transaction not settled."
Beispiel #12
0
    def _handle_transaction_receipt(
            self, ledger_api_msg: LedgerApiMessage,
            ledger_api_dialogue: LedgerApiDialogue) -> None:
        """
        Handle a message of transaction_receipt performative.

        :param ledger_api_message: the ledger api message
        """
        strategy = cast(Strategy, self.context.strategy)
        is_transaction_successful = LedgerApis.is_transaction_settled(
            ledger_api_msg.transaction_receipt.ledger_id,
            ledger_api_msg.transaction_receipt.receipt,
        )
        contract_reference = ledger_api_dialogue._associated_signing_dialogue._associated_contract_api_dialogue.dialogue_label.dialogue_reference[
            0]
        for contract, status in strategy.contract_status.items():
            if status[0] is None:
                continue
            elif status[1] == contract_reference:
                self.context.logger.info(f"retrieved deployment {contract}")
                strategy.contract_status[contract] = (
                    "deployed",
                    ledger_api_msg.transaction_receipt.
                    receipt["contractAddress"],
                )
                self.context.logger.info(
                    f"** {ledger_api_msg.transaction_receipt.receipt['contractAddress']}  Retireved and stored)"
                )
        order = strategy.get_order(strategy.current_order.id)
        if is_transaction_successful:
            if order.status_code_id == PLACING:  # we have created our order
                strategy.update_current_order(
                    order,
                    {
                        "status_code_id":
                        OPEN,
                        "tx_hash":
                        ledger_api_msg.transaction_receipt.transaction["hash"].
                        hex(),
                    },
                )  # now we mark for placement
            elif order.status_code_id == OPEN:  # we have  excercised
                strategy.update_current_order(
                    order,
                    {
                        "status_code_id":
                        CLOSED,
                        "tx_hash":
                        ledger_api_msg.transaction_receipt.transaction["hash"].
                        hex(),
                    },
                )  # now we mark for placement
            self.context.logger.info(
                "transaction was successfully settled. Transaction receipt={}".
                format("ledger_api_msg.transaction_receipt"))
        else:
            strategy.update_current_order(
                order,
                {
                    "status_code_id":
                    FAILED,
                    "tx_hash":
                    ledger_api_msg.transaction_receipt.transaction["hash"].hex(
                    ),
                },
            )  # now we mark for placement
            self.context.logger.error(
                "transaction failed. Transaction receipt={}".format(
                    ledger_api_msg.transaction_receipt))

        strategy.is_order_behaviour_active = False
        strategy.is_price_behaviour_active = True