From bcc7ebe2109ef3948e65c81989348284d7755dac Mon Sep 17 00:00:00 2001 From: Matt Date: Mon, 25 Mar 2024 07:25:21 -0700 Subject: [PATCH] Add @tx_out_cmd decorator --- chia/_tests/cmds/wallet/test_tx_decorators.py | 27 +++++++++++++++++++ chia/cmds/cmds_util.py | 27 +++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 chia/_tests/cmds/wallet/test_tx_decorators.py diff --git a/chia/_tests/cmds/wallet/test_tx_decorators.py b/chia/_tests/cmds/wallet/test_tx_decorators.py new file mode 100644 index 000000000000..8a79e9507828 --- /dev/null +++ b/chia/_tests/cmds/wallet/test_tx_decorators.py @@ -0,0 +1,27 @@ +from __future__ import annotations + +from typing import Any, List + +import click +from click.testing import CliRunner + +from chia._tests.cmds.wallet.test_consts import STD_TX +from chia.cmds.cmds_util import TransactionBundle, tx_out_cmd +from chia.wallet.transaction_record import TransactionRecord + + +def test_tx_out_cmd() -> None: + @click.command() + @tx_out_cmd + def test_cmd(**kwargs: Any) -> List[TransactionRecord]: + with open("./temp.push", "w") as file: + file.write(str(kwargs["push"])) + return [STD_TX, STD_TX] + + runner: CliRunner = CliRunner() + with runner.isolated_filesystem(): + runner.invoke(test_cmd, ["--transaction-file", "./temp.transaction"]) + with open("./temp.transaction", "rb") as file: + assert TransactionBundle.from_bytes(file.read()) == TransactionBundle([STD_TX, STD_TX]) + with open("./temp.push") as file2: + assert file2.read() == "True" diff --git a/chia/cmds/cmds_util.py b/chia/cmds/cmds_util.py index 2badd8d8d1ef..a3fe1625239b 100644 --- a/chia/cmds/cmds_util.py +++ b/chia/cmds/cmds_util.py @@ -327,6 +327,33 @@ def timelock_args(func: Callable[..., None]) -> Callable[..., None]: ) +@streamable +@dataclasses.dataclass(frozen=True) +class TransactionBundle(Streamable): + txs: List[TransactionRecord] + + +def tx_out_cmd(func: Callable[..., List[TransactionRecord]]) -> Callable[..., None]: + def original_cmd(transaction_file: Optional[str] = None, **kwargs: Any) -> None: + txs: List[TransactionRecord] = func(**kwargs) + if transaction_file is not None: + print(f"Writing transactions to file {transaction_file}:") + with open(Path(transaction_file), "wb") as file: + file.write(bytes(TransactionBundle(txs))) + + return click.option( + "--push/--no-push", help="Push the transaction to the network", type=bool, is_flag=True, default=True + )( + click.option( + "--transaction-file", + help="A file to write relevant transactions to", + type=str, + required=False, + default=None, + )(original_cmd) + ) + + @streamable @dataclasses.dataclass(frozen=True) class CMDCoinSelectionConfigLoader(Streamable):