Coverage for tests/utils/to_multiple_tx_sender.py: 99%
157 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 19:49 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 19:49 +0000
1import logging
3from typing import Optional
4from monero import (
5 MoneroWallet, MoneroAccount, MoneroSubaddress, MoneroTxConfig,
6 MoneroTxPriority, MoneroDestination, MoneroTxWallet
7)
9from .assert_utils import AssertUtils
10from .context import TxContext
11from .tx_wallet_utils import TxWalletUtils
12from .transfer_utils import TransferUtils
13from .test_utils import TestUtils
15logger: logging.Logger = logging.getLogger("ToMultipleTxSender")
18class ToMultipleTxSender:
19 """Sends funds from the first unlocked account to multiple accounts and subaddresses."""
21 SEND_DIVISOR: int = 10
22 """Transaction amount send divisor."""
23 SEND_MAX_DIFF: int = 60
25 _wallet: MoneroWallet
26 """Wallet test instance."""
27 _num_accounts: int
28 """Number of account to receive funds."""
29 _num_subaddresses_per_account: int
30 """Number of subaddresses per account to receive funds."""
31 _can_split: bool
32 """Split into multiple transactions."""
33 _send_amount_per_subaddress: Optional[int]
34 """Amount to send to each subaddress."""
35 _subtract_fee_from_destinations: bool
36 """Subtract the from destination addresses."""
38 @property
39 def total_subaddresses(self) -> int:
40 """Total num of subaddresses to send txs to.
42 :returns int: total number of subaddresses to send txs to.
43 """
44 return self._num_accounts * self._num_subaddresses_per_account
46 @property
47 def min_account_amount(self) -> int:
48 """Minimum account unlocked balance needed.
50 :returns int: minimum account unlocked balance needed to fulfill the send configuration.
51 """
52 fee: int = TxWalletUtils.MAX_FEE # 75000000000
53 # compute the minimum account unlocked balance needed in order to fulfill the config
54 if self._send_amount_per_subaddress is not None:
55 # min account amount must cover the total amount being sent plus the tx fee = num_addresses * (amount_per_subaddress + fee)
56 return self.total_subaddresses * (self._send_amount_per_subaddress + fee)
58 # account balance must be more than fee * num_addresses * divisor + fee so each destination amount is at least a fee's worth (so dust is not sent)
59 return ((fee * self.total_subaddresses) * self.SEND_DIVISOR) + fee
61 def __init__(
62 self,
63 wallet: MoneroWallet,
64 num_accounts: int,
65 num_subaddresses_per_account: int,
66 can_split: bool,
67 send_amount_per_subaddress: Optional[int],
68 subtract_fee_from_destinations: bool
69 ) -> None:
70 """Initialize a new multiple tx sender.
72 :param MoneroWallet wallet: wallet to send txs from.
73 :param int num_accounts: is the number of accounts to receive funds.
74 :param int num_subaddresses_per_account: is the number of subaddresses per account to receive funds.
75 :param bool can_split: specifies if the operation can be split into multiple transactions.
76 :param int | None send_amount_per_subaddress: is the amount to send to each subaddress (optional, computed if not given).
77 :param bool subtract_fee_from_destinations: specifies to subtract the fee from destination addresses.
78 """
79 self._wallet = wallet
80 self._num_accounts = num_accounts
81 self._num_subaddresses_per_account = num_subaddresses_per_account
82 self._can_split = can_split
83 self._send_amount_per_subaddress = send_amount_per_subaddress
84 self._subtract_fee_from_destinations = subtract_fee_from_destinations
86 #region Private Methods
88 def _get_source_account(self) -> MoneroAccount:
89 """Get wallet account to send funds from.
91 :returns MoneroAccount: account to send funds from.
92 """
93 min_account_amount: int = self.min_account_amount
94 src_account: Optional[MoneroAccount] = None
95 has_balance: bool = False
96 # get first account with sufficient unlocked funds
97 for account in self._wallet.get_accounts():
98 assert account.balance is not None
99 assert account.unlocked_balance is not None
100 if account.balance > min_account_amount:
101 has_balance = True
102 if account.unlocked_balance > min_account_amount:
103 src_account = account
104 break
106 assert has_balance, f"Wallet does not have enough balance; load '{TestUtils.WALLET_NAME}' with XMR in order to test sending"
107 assert src_account is not None, "Wallet is waiting on unlocked funds"
108 return src_account
110 def _create_accounts(self) -> int:
111 """Creates minimum number of accounts.
113 :returns int: number of accounts created.
114 """
115 num_accounts: int = len(self._wallet.get_accounts())
116 logger.debug(f"Wallet has already {num_accounts} accounts")
117 num_accounts_to_create: int = self._num_accounts - num_accounts if num_accounts <= self._num_accounts else 0
118 for i in range(num_accounts_to_create):
119 self._wallet.create_account()
120 logger.debug(f"Created account {i + 1}")
121 return num_accounts_to_create
123 def _create_subaddresses(self) -> list[str]:
124 """Creates minimum number of subaddress per account.
126 :returns list[str]: destinations addresses.
127 """
128 destination_addresses: list[str] = []
130 for i in range(self._num_accounts):
131 subaddresses: list[MoneroSubaddress] = self._wallet.get_subaddresses(i)
132 for j in range(self._num_subaddresses_per_account - len(subaddresses)):
133 self._wallet.create_subaddress(i)
134 logger.debug(f"Created subaddress {i},{j}")
136 subaddresses = self._wallet.get_subaddresses(i)
137 assert len(subaddresses) >= self._num_subaddresses_per_account
138 for j in range(self._num_subaddresses_per_account):
139 subaddress: MoneroSubaddress = subaddresses[j]
140 assert subaddress.address is not None
141 destination_addresses.append(subaddress.address)
143 return destination_addresses
145 def _build_tx_config(self, src_account: MoneroAccount, send_amount_per_subaddress: int, destination_addresses: list[str]) -> MoneroTxConfig:
146 """Build tx configuration.
148 :param MoneroAccount src_account: account to send funds from.
149 :param int send_amount_per_subaddress: amount to send for each subaddress.
150 :param list[str] destination_addresses: addresses to send funds to.
151 :returns MoneroTxConfig: transaction configuration.
152 """
153 config: MoneroTxConfig = MoneroTxConfig()
154 config.account_index = src_account.index
155 config.relay = True
156 config.can_split = self._can_split
157 config.priority = MoneroTxPriority.NORMAL
159 subtract_fee_from: list[int] = []
160 for i, address in enumerate(destination_addresses):
161 destination: MoneroDestination = MoneroDestination()
162 destination.address = address
163 destination.amount = send_amount_per_subaddress
164 config.destinations.append(destination)
165 subtract_fee_from.append(i)
167 if self._subtract_fee_from_destinations:
168 config.subtract_fee_from = subtract_fee_from
170 return config
172 #endregion
174 def send(self) -> None:
175 """Send multiple txs from wallet."""
177 TestUtils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(self._wallet)
179 # send funds from first account with sufficient unlocked funds
180 src_account: MoneroAccount = self._get_source_account()
181 assert src_account.index is not None
182 assert src_account.balance is not None
183 assert src_account.unlocked_balance is not None
184 balance: int = src_account.balance
185 unlocked_balance: int = src_account.unlocked_balance
187 # get amount to send total and per subaddress
188 total_subaddresses: int = self.total_subaddresses
189 send_amount: Optional[int] = None
190 send_amount_per_subaddress: Optional[int] = self._send_amount_per_subaddress
192 if send_amount_per_subaddress is None:
193 send_amount = TxWalletUtils.MAX_FEE * 5 * total_subaddresses
194 send_amount_per_subaddress = int(send_amount / total_subaddresses)
195 else:
196 send_amount = send_amount_per_subaddress * total_subaddresses
198 # create minimum number of accounts
199 created_accounts: int = self._create_accounts()
200 logger.debug(f"Created {created_accounts} accounts")
202 # create minimum number of subaddresses per account and collect destination addresses
203 destination_addresses: list[str] = self._create_subaddresses()
204 config: MoneroTxConfig = self._build_tx_config(src_account, send_amount_per_subaddress, destination_addresses)
205 config_copy: MoneroTxConfig = config.copy()
207 # send tx(s) with config
208 txs: list[MoneroTxWallet] = []
209 try:
210 txs = self._wallet.create_txs(config)
211 except Exception as e:
212 # test error applying subtractFromFee with split txs
213 if self._subtract_fee_from_destinations and len(txs) == 0:
214 if str(e) == "subtractfeefrom transfers cannot be split over multiple transactions yet":
215 logger.debug(str(e))
216 return
217 raise
219 if not self._can_split:
220 assert len(txs) == 1
222 # test that config is unchanged
223 assert config_copy != config
224 AssertUtils.assert_equals(config_copy, config)
226 # test that wallet balance decreased
227 account: MoneroAccount = self._wallet.get_account(src_account.index)
228 assert account.balance is not None
229 assert account.unlocked_balance is not None
230 assert account.balance < balance, "Balance did not decrease"
231 assert account.unlocked_balance < unlocked_balance, "Unlocked balance did not decrease"
233 # build test context
234 config.can_split = self._can_split
235 ctx: TxContext = TxContext()
236 ctx.wallet = self._wallet
237 ctx.config = config
238 ctx.is_send_response = True
240 # test each transaction
241 assert len(txs) > 0
242 fee_sum: int = 0
243 outgoing_sum: int = 0
244 TxWalletUtils.test_txs_wallet(txs, ctx)
245 for tx in txs:
246 assert tx.fee is not None
247 fee_sum += tx.fee
248 outgoing_sum += tx.get_outgoing_amount()
250 if tx.outgoing_transfer is not None and len(tx.outgoing_transfer.destinations) > 0:
251 destination_sum: int = 0
252 for destination in tx.outgoing_transfer.destinations:
253 TransferUtils.test_destination(destination)
254 assert destination.amount is not None
255 assert destination.address in destination_addresses
256 destination_sum += destination.amount
258 # assert that transfers sum up to tx amount
259 assert destination_sum == tx.get_outgoing_amount()
261 # assert that outgoing amounts sum up to the amount sent within a small margin
262 amount: int = (send_amount - fee_sum) if self._subtract_fee_from_destinations else send_amount
263 amount = abs(amount - outgoing_sum)
265 if amount > self.SEND_MAX_DIFF:
266 raise Exception("Actual send amount is too different from requested send amount")