Skip to content

Commit ffe72e5

Browse files
committed
chore: updated files to pass linting errors due to ruff update
1 parent 36ce785 commit ffe72e5

20 files changed

+337
-965
lines changed

examples/payments/payments.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1+
from algokit_utils import AlgorandClient
2+
13
from algokit_subscriber.subscriber import AlgorandSubscriber
24
from algokit_subscriber.types.subscription import SubscribedTransaction
3-
from algokit_utils import AlgorandClient
45

56
algorand = AlgorandClient.mainnet()
67

@@ -58,9 +59,7 @@ def print_payment(transaction: SubscribedTransaction, filter_name: str) -> None:
5859
Here we are only using this EventListener callback for one filter, but if we had multiple filters we could use the filter name to determine which filter the transaction matched.
5960
"""
6061
pay = transaction["payment-transaction"]
61-
print(
62-
f"{filter_name}: {transaction['sender']} sent {pay['receiver']} {pay['amount'] * 1e-6} ALGO"
63-
)
62+
print(f"{filter_name}: {transaction['sender']} sent {pay['receiver']} {pay['amount'] * 1e-6} ALGO")
6463

6564

6665
# Attach our callback to the 'pay txns' filter

examples/usdc/usdc.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1+
from algokit_utils import AlgorandClient
2+
13
from algokit_subscriber.subscriber import AlgorandSubscriber
24
from algokit_subscriber.types.subscription import SubscribedTransaction
3-
from algokit_utils import AlgorandClient
45

56
algorand = AlgorandClient.mainnet()
67

@@ -54,9 +55,7 @@ def print_usdc(transaction: SubscribedTransaction, filter_name: str) -> None:
5455
Here we are only using this EventListener callback for one filter, but if we had multiple filters we could use the filter name to determine which filter the transaction matched.
5556
"""
5657
axfer = transaction["asset-transfer-transaction"]
57-
print(
58-
f"{filter_name}: {transaction['sender']} sent {axfer['receiver']} {axfer['amount'] * 1e-6} USDC"
59-
)
58+
print(f"{filter_name}: {transaction['sender']} sent {axfer['receiver']} {axfer['amount'] * 1e-6} USDC")
6059

6160

6261
subscriber.on("usdc", print_usdc)

src/algokit_subscriber/__init__.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,14 @@
1515
__all__ = [
1616
"AlgorandSubscriber",
1717
"AlgorandSubscriberConfig",
18-
"TransactionSubscriptionParams",
19-
"TransactionSubscriptionResult",
20-
"NamedTransactionFilter",
21-
"TransactionFilter",
22-
"EventListener",
2318
"Arc28EventGroup",
24-
"SubscribedTransaction",
25-
"get_subscribed_transactions",
2619
"BalanceChange",
2720
"BalanceChangeRole",
21+
"EventListener",
22+
"NamedTransactionFilter",
23+
"SubscribedTransaction",
24+
"TransactionFilter",
25+
"TransactionSubscriptionParams",
26+
"TransactionSubscriptionResult",
27+
"get_subscribed_transactions",
2828
]

src/algokit_subscriber/block.py

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,8 @@
1010

1111
def block_response_to_block_data(response: bytes) -> BlockData:
1212
return cast(
13-
BlockData,
14-
msgpack.unpackb(
15-
response, strict_map_key=False, unicode_errors="surrogateescape"
16-
),
13+
"BlockData",
14+
msgpack.unpackb(response, strict_map_key=False, unicode_errors="surrogateescape"),
1715
)
1816

1917

@@ -25,9 +23,7 @@ def get_blocks_bulk(context: dict[str, int], client: AlgodClient) -> list[BlockD
2523
:return: The blocks
2624
"""
2725
# Grab 30 at a time to not overload the node
28-
block_chunks = chunk_array(
29-
range_inclusive(context["start_round"], context["max_round"]), 30
30-
)
26+
block_chunks = chunk_array(range_inclusive(context["start_round"], context["max_round"]), 30)
3127
blocks = []
3228

3329
for chunk in block_chunks:
@@ -41,12 +37,10 @@ def get_blocks_bulk(context: dict[str, int], client: AlgodClient) -> list[BlockD
4137
params={"format": "msgpack"},
4238
response_format="msgpack",
4339
)
44-
decoded = block_response_to_block_data(cast(bytes, response))
40+
decoded = block_response_to_block_data(cast("bytes", response))
4541
blocks.append(decoded)
4642

4743
elapsed_time = time.time() - start_time
48-
logger.debug(
49-
f"Retrieved {len(chunk)} blocks from round {chunk[0]} via algod in {elapsed_time:.2f}s"
50-
)
44+
logger.debug(f"Retrieved {len(chunk)} blocks from round {chunk[0]} via algod in {elapsed_time:.2f}s")
5145

5246
return blocks

src/algokit_subscriber/indexer_lookup.py

Lines changed: 9 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,7 @@ def transaction(transaction_id: str, indexer: IndexerClient) -> TransactionLooku
2626
return indexer.transaction(txid=transaction_id) # type: ignore[no-untyped-call, no-any-return]
2727

2828

29-
def lookup_account_by_address(
30-
account_address: str, indexer: IndexerClient
31-
) -> AccountLookupResult:
29+
def lookup_account_by_address(account_address: str, indexer: IndexerClient) -> AccountLookupResult:
3230
"""
3331
Looks up an account by address using Indexer.
3432
"""
@@ -64,9 +62,7 @@ def build_request(next_token: str | None = None) -> dict[str, Any]:
6462

6563
return args
6664

67-
return execute_paginated_request(
68-
indexer.lookup_account_application_by_creator, extract_items, build_request
69-
)
65+
return execute_paginated_request(indexer.lookup_account_application_by_creator, extract_items, build_request)
7066

7167

7268
def lookup_asset_holdings(
@@ -88,29 +84,17 @@ def build_request(next_token: str | None = None) -> dict[str, Any]:
8884
args: dict[str, Any] = {
8985
"asset-id": asset_id,
9086
"limit": pagination_limit or DEFAULT_INDEXER_MAX_API_RESOURCES_PER_ACCOUNT,
91-
"include-all": (
92-
options["include-all"] if options and "include-all" in options else None
93-
),
94-
"currency-greater-than": (
95-
options["currency-greater-than"]
96-
if options and "currency-greater-than" in options
97-
else None
98-
),
99-
"currency-less-than": (
100-
options["currency-less-than"]
101-
if options and "currency-less-than" in options
102-
else None
103-
),
87+
"include-all": (options["include-all"] if options and "include-all" in options else None),
88+
"currency-greater-than": (options["currency-greater-than"] if options and "currency-greater-than" in options else None),
89+
"currency-less-than": (options["currency-less-than"] if options and "currency-less-than" in options else None),
10490
}
10591

10692
if next_token:
10793
args["next-token"] = next_token
10894

10995
return args
11096

111-
return execute_paginated_request(
112-
indexer.lookup_account_assets, extract_items, build_request
113-
)
97+
return execute_paginated_request(indexer.lookup_account_assets, extract_items, build_request)
11498

11599

116100
def search_transactions(
@@ -127,23 +111,18 @@ def extract_items(response: TransactionSearchResults) -> list[TransactionResult]
127111
nonlocal current_round
128112
if "message" in response:
129113
raise Exception({"status": 404, **response})
130-
if response["current-round"] > current_round:
131-
current_round = response["current-round"]
114+
current_round = max(current_round, response["current-round"])
132115
return response["transactions"]
133116

134117
def build_request(next_token: str | None = None) -> dict[str, Any]:
135118
args: dict[str, Any] = search_criteria
136-
args["limit"] = (
137-
pagination_limit or DEFAULT_INDEXER_MAX_API_RESOURCES_PER_ACCOUNT
138-
)
119+
args["limit"] = pagination_limit or DEFAULT_INDEXER_MAX_API_RESOURCES_PER_ACCOUNT
139120
if next_token:
140121
args["next_page"] = next_token
141122

142123
return args
143124

144-
transactions = execute_paginated_request(
145-
indexer.search_transactions, extract_items, build_request
146-
)
125+
transactions = execute_paginated_request(indexer.search_transactions, extract_items, build_request)
147126

148127
return {
149128
"current-round": current_round,

src/algokit_subscriber/subscriber.py

Lines changed: 16 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -42,12 +42,12 @@ def __init__(
4242
self.filter_names = [f["name"] for f in self.config["filters"]]
4343

4444
if config["sync_behaviour"] == "catchup-with-indexer" and not indexer_client:
45-
raise ValueError(
46-
"Received sync behaviour of catchup-with-indexer, but didn't receive an indexer instance."
47-
)
45+
raise ValueError("Received sync behaviour of catchup-with-indexer, but didn't receive an indexer instance.")
4846

4947
def default_error_handler(
50-
self, error: Any, _str: str | None = None # noqa: ANN401
48+
self,
49+
error: Any, # noqa: ANN401
50+
_str: str | None = None,
5151
) -> None:
5252
raise error
5353

@@ -56,15 +56,13 @@ def poll_once(self) -> TransactionSubscriptionResult:
5656
Execute a single subscription poll.
5757
"""
5858
watermark = self.config["watermark_persistence"]["get"]() or 0
59-
current_round = cast(dict, self.algod.status())["last-round"]
59+
current_round = cast("dict", self.algod.status())["last-round"]
6060

61-
self.event_emitter.emit(
62-
"before:poll", {"watermark": watermark, "current_round": current_round}
63-
)
61+
self.event_emitter.emit("before:poll", {"watermark": watermark, "current_round": current_round})
6462

6563
poll_result = get_subscribed_transactions(
6664
subscription=cast(
67-
TransactionSubscriptionParams,
65+
"TransactionSubscriptionParams",
6866
{"watermark": watermark, "current_round": current_round, **self.config},
6967
),
7068
algod=self.algod,
@@ -74,21 +72,11 @@ def poll_once(self) -> TransactionSubscriptionResult:
7472
try:
7573
for filter_name in self.filter_names:
7674
mapper = next(
77-
(
78-
f.get("mapper")
79-
for f in self.config["filters"]
80-
if f["name"] == filter_name
81-
),
75+
(f.get("mapper") for f in self.config["filters"] if f["name"] == filter_name),
8276
None,
8377
)
84-
matched_transactions = [
85-
t
86-
for t in poll_result["subscribed_transactions"]
87-
if filter_name in (t.get("filters_matched") or [])
88-
]
89-
mapped_transactions = (
90-
mapper(matched_transactions) if mapper else matched_transactions
91-
)
78+
matched_transactions = [t for t in poll_result["subscribed_transactions"] if filter_name in (t.get("filters_matched") or [])]
79+
mapped_transactions = mapper(matched_transactions) if mapper else matched_transactions
9280

9381
self.event_emitter.emit(f"batch:{filter_name}", mapped_transactions)
9482
for transaction in mapped_transactions:
@@ -124,16 +112,12 @@ def start( # noqa: C901
124112
duration_in_seconds = time.time() - start_time
125113

126114
if not suppress_log:
127-
logger.info(
128-
f"Subscription poll completed in {duration_in_seconds:.2f}s"
129-
)
115+
logger.info(f"Subscription poll completed in {duration_in_seconds:.2f}s")
130116
logger.info(f"Current round: {result['current_round']}")
131117
logger.info(f"Starting watermark: {result['starting_watermark']}")
132118
logger.info(f"New watermark: {result['new_watermark']}")
133119
logger.info(f"Synced round range: {result['synced_round_range']}")
134-
logger.info(
135-
f"Subscribed transactions: {len(result['subscribed_transactions'])}"
136-
)
120+
logger.info(f"Subscribed transactions: {len(result['subscribed_transactions'])}")
137121

138122
if inspect:
139123
inspect(result)
@@ -142,9 +126,7 @@ def start( # noqa: C901
142126
if self.stop_requested:
143127
break # type: ignore[unreachable]
144128

145-
if result["current_round"] > result[
146-
"new_watermark"
147-
] or not self.config.get("wait_for_block_when_at_tip", False):
129+
if result["current_round"] > result["new_watermark"] or not self.config.get("wait_for_block_when_at_tip", False):
148130
sleep_time = self.config.get("frequency_in_seconds", 1)
149131
if not suppress_log:
150132
logger.info(f"Sleeping for {sleep_time}s")
@@ -156,9 +138,7 @@ def start( # noqa: C901
156138
wait_start = time.time()
157139
self.algod.status_after_block(result["current_round"])
158140
if not suppress_log:
159-
logger.info(
160-
f"Waited for {time.time() - wait_start:.2f}s until next block"
161-
)
141+
logger.info(f"Waited for {time.time() - wait_start:.2f}s until next block")
162142
except Exception as e:
163143
self.event_emitter.emit("error", e)
164144
self.started = False
@@ -174,15 +154,11 @@ def on(self, filter_name: str, listener: EventListener) -> "AlgorandSubscriber":
174154
Register an event handler to run on every subscribed transaction matching the given filter name.
175155
"""
176156
if filter_name == "error":
177-
raise ValueError(
178-
"'error' is reserved, please supply a different filter_name."
179-
)
157+
raise ValueError("'error' is reserved, please supply a different filter_name.")
180158
self.event_emitter.on(filter_name, listener)
181159
return self
182160

183-
def on_batch(
184-
self, filter_name: str, listener: EventListener
185-
) -> "AlgorandSubscriber":
161+
def on_batch(self, filter_name: str, listener: EventListener) -> "AlgorandSubscriber":
186162
"""
187163
Register an event handler to run on all subscribed transactions matching the given filter name
188164
for each subscription poll.

0 commit comments

Comments
 (0)