Skip to content

Commit 2e88dd7

Browse files
committed
chore: added ruff formating to root files
Signed-off-by: Manish Dait <daitmanish88@gmail.com>
1 parent 31408c6 commit 2e88dd7

11 files changed

Lines changed: 83 additions & 93 deletions

File tree

examples/tokens/token_airdrop_transaction.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -499,7 +499,6 @@ def token_airdrop():
499499
client,
500500
operator_id,
501501
recipient_id,
502-
token_id,
503502
nft_id,
504503
serial_number,
505504
balances_before,

examples/tokens/token_create_transaction_token_metadata.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,7 @@ def create_token_with_metadata():
210210
try_update_metadata_without_key(client, operator_key, token_a)
211211

212212
token_b, metadata_key = create_token_with_metadata_key(client, metadata_key, operator_id, operator_key)
213-
update_metadata_with_key(client, token_b, metadata_key, operator_key)
213+
update_metadata_with_key(client, token_b, metadata_key)
214214

215215
demonstrate_metadata_length_validation(client, operator_key, operator_id)
216216

examples/transaction/transfer_transaction_nft.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,7 @@ def main():
175175
client, operator_id, operator_key = setup_client()
176176
account_id, new_account_private_key = create_test_account(client)
177177
token_id = create_nft(client, operator_id, operator_key)
178-
nft_id = mint_nft(client, token_id, operator_key)
178+
nft_id = mint_nft(client, token_id)
179179
associate_nft(client, account_id, token_id, new_account_private_key)
180180

181181
# Transfer the NFT to the new account

generate_proto.py

Lines changed: 56 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
* TRACE (custom) for verbose details such as per-file rewrites and protoc args.
2222
Run: python generate_proto.py -vv or with trace logs: python generate_proto.py -vvv
2323
"""
24+
2425
import logging
2526
import re
2627
import shutil
@@ -30,26 +31,26 @@
3031
from pathlib import Path
3132
from urllib.parse import urlparse
3233

33-
VERSION="v0.72.0-rc.2"
34+
VERSION = "v0.72.0-rc.2"
3435
SOURCES = [
3536
{
3637
"name": "hedera-protobufs",
3738
"url": "https://github.com/hashgraph/hedera-protobufs",
3839
"version": VERSION,
3940
"strip_count": 1,
40-
"modules": ("mirror",)
41+
"modules": ("mirror",),
4142
},
4243
{
4344
"name": "hiero-consensus-node",
4445
"url": "https://github.com/hiero-ledger/hiero-consensus-node",
4546
"version": VERSION,
46-
"strip_count": 6,
47-
"modules": ("services", "platform", "fee", "sdk", "block", "streams", "blocks")
48-
}
47+
"strip_count": 6,
48+
"modules": ("services", "platform", "fee", "sdk", "block", "streams", "blocks"),
49+
},
4950
]
5051

51-
OUTPUT_DIR="src/hiero_sdk_python/hapi"
52-
CACHE_DIR=".protos"
52+
OUTPUT_DIR = "src/hiero_sdk_python/hapi"
53+
CACHE_DIR = ".protos"
5354

5455
# Map common broken imports in mirror/platform proto
5556
REPLACEMENTS = {
@@ -70,16 +71,19 @@ class Config:
7071
name: str
7172
url: str
7273
version: str
73-
strip_count: int
74+
strip_count: int
7475
modules: tuple = field(default_factory=tuple)
7576

7677

7778
def setup_logging(verbosity: int) -> None:
7879
level = logging.WARNING
79-
if verbosity == 1: level = logging.INFO
80-
elif verbosity == 2: level = logging.DEBUG
81-
elif verbosity >= 3: level = logging.TRACE_LEVEL
82-
80+
if verbosity == 1:
81+
level = logging.INFO
82+
elif verbosity == 2:
83+
level = logging.DEBUG
84+
elif verbosity >= 3:
85+
level = logging.TRACE_LEVEL
86+
8387
logging.basicConfig(level=level, format="%(levelname)s: %(message)s")
8488

8589

@@ -93,11 +97,11 @@ def download_protos(config: Config, cache_path: Path) -> None:
9397

9498
try:
9599
# URL scheme and host validated above
96-
with urllib.request.urlopen(url, timeout=30) as resp: # nosec B310
100+
with urllib.request.urlopen(url, timeout=30) as resp: # nosec B310
97101
safe_extract_tar_stream(resp, config, cache_path)
98102
except Exception as e:
99-
raise RuntimeError(f"Download failed for {config.name}: {e}")
100-
103+
raise RuntimeError(f"Download failed for {config.name}: {e}") from e
104+
101105

102106
def is_safe_tar_member(member: tarfile.TarInfo, base: Path) -> bool:
103107
name = member.name
@@ -111,18 +115,19 @@ def is_safe_tar_member(member: tarfile.TarInfo, base: Path) -> bool:
111115
dest.relative_to(base.resolve())
112116
except ValueError:
113117
return False
114-
115-
return (member.isdir() or member.isreg())
118+
119+
return member.isdir() or member.isreg()
116120

117121

118122
def safe_extract_tar_stream(resp, config: Config, cache_path: Path):
119123
with tarfile.open(fileobj=resp, mode="r|gz") as tar:
120124
for member in tar:
121125
parts = Path(member.name).parts
122126

123-
if len(parts) <= config.strip_count: continue
124-
member.name = "/".join(parts[config.strip_count:])
125-
127+
if len(parts) <= config.strip_count:
128+
continue
129+
member.name = "/".join(parts[config.strip_count :])
130+
126131
if not any(member.name.startswith(p) for p in config.modules):
127132
continue
128133

@@ -132,24 +137,23 @@ def safe_extract_tar_stream(resp, config: Config, cache_path: Path):
132137
if member.isdir():
133138
(cache_path / member.name).mkdir(parents=True, exist_ok=True)
134139
continue
135-
140+
136141
target = cache_path / member.name
137142
target.parent.mkdir(parents=True, exist_ok=True)
138143
with tar.extractfile(member) as src, target.open("wb") as dst:
139144
shutil.copyfileobj(src, dst)
140145

141146

142-
143147
def patch_proto_imports(proto_root: Path):
144148
logging.info("Patching proto files for consistent import paths...")
145149

146150
for proto_file in proto_root.rglob("*.proto"):
147151
content = proto_file.read_text(encoding="utf-8")
148152
new_content = content
149-
153+
150154
for broken, fixed in REPLACEMENTS.items():
151155
new_content = new_content.replace(broken, fixed)
152-
156+
153157
if "platform" in proto_file.parts:
154158
new_content = re.sub(r'import "event/', 'import "platform/event/', new_content)
155159

@@ -160,6 +164,7 @@ def patch_proto_imports(proto_root: Path):
160164
def run_protoc(proto_root: Path, output_root: Path) -> None:
161165
import grpc_tools
162166
from grpc_tools import protoc
167+
163168
google_include = str(Path(grpc_tools.__file__).parent / "_proto")
164169
all_protos = [p.as_posix() for p in proto_root.rglob("*.proto")]
165170

@@ -184,19 +189,23 @@ def fix_imports(output_root: Path):
184189
if py_file.name == "__init__.py":
185190
continue
186191

187-
py_file.write_text("\n".join(
188-
process_file_lines(py_file.read_text(encoding="utf-8").splitlines(), pattern, py_file.relative_to(output_root).parents)
189-
) + "\n", encoding="utf-8")
192+
py_file.write_text(
193+
"\n".join(
194+
process_file_lines(
195+
py_file.read_text(encoding="utf-8").splitlines(), pattern, py_file.relative_to(output_root).parents
196+
)
197+
)
198+
+ "\n",
199+
encoding="utf-8",
200+
)
201+
190202

191203
def process_file_lines(lines, pattern, parents):
192204
"""Process each line in a file and fix imports if needed."""
193205
depth = len(parents) - 1
194206
dots = "." * (depth + 1)
195-
new_lines = []
196207

197-
for line in lines:
198-
new_lines.append(fix_line_import(line, pattern, dots))
199-
return new_lines
208+
return [fix_line_import(line, pattern, dots) for line in lines]
200209

201210

202211
def fix_line_import(line, pattern, dots):
@@ -205,7 +214,7 @@ def fix_line_import(line, pattern, dots):
205214
if not match:
206215
return line
207216

208-
ptype, ppath, psuffix = match.group('type'), match.group('path'), match.group('suffix')
217+
ptype, ppath, psuffix = match.group("type"), match.group("path"), match.group("suffix")
209218
full_module = ppath + psuffix
210219

211220
if ptype == "from":
@@ -217,13 +226,13 @@ def fix_line_import(line, pattern, dots):
217226
if " as " in line:
218227
alias = line.split(" as ", 1)[1].strip()
219228
return (
220-
f"from {dots}{module_parts[0]} import {module_parts[1]} as {alias}"
221-
if len(module_parts) > 1
229+
f"from {dots}{module_parts[0]} import {module_parts[1]} as {alias}"
230+
if len(module_parts) > 1
222231
else f"from {dots} import {module_parts[0]} as {alias}"
223232
)
224233
return (
225-
f"from {dots}{module_parts[0]} import {module_parts[1]}"
226-
if len(module_parts) > 1
234+
f"from {dots}{module_parts[0]} import {module_parts[1]}"
235+
if len(module_parts) > 1
227236
else f"from {dots} import {module_parts[0]}"
228237
)
229238

@@ -233,8 +242,11 @@ def main():
233242
cache_path = Path(CACHE_DIR)
234243
out_path = Path(OUTPUT_DIR)
235244

236-
if cache_path.exists(): shutil.rmtree(cache_path)
237-
if out_path.exists(): shutil.rmtree(out_path)
245+
if cache_path.exists():
246+
shutil.rmtree(cache_path)
247+
248+
if out_path.exists():
249+
shutil.rmtree(out_path)
238250

239251
cache_path.mkdir(parents=True)
240252
out_path.mkdir(parents=True)
@@ -244,18 +256,19 @@ def main():
244256
download_protos(src, cache_path)
245257

246258
patch_proto_imports(cache_path)
247-
259+
248260
logging.info("Running protoc...")
249261
run_protoc(cache_path, out_path)
250-
262+
251263
logging.info("Fixing imports...")
252264
fix_imports(out_path)
253-
265+
254266
for d in [out_path, *out_path.rglob("*")]:
255-
if d.is_dir(): (d / "__init__.py").touch()
267+
if d.is_dir():
268+
(d / "__init__.py").touch()
256269

257270
print(f"✅ Successfully merged and generated HAPI at {out_path}")
258271

259272

260273
if __name__ == "__main__":
261-
main()
274+
main()

scripts/examples/match_examples_src.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import os
22
from collections import defaultdict
33

4-
EXCLUDE_DIRS = ['hapi', '__pycache__']
4+
EXCLUDE_DIRS = ["hapi", "__pycache__"]
55

66

77
# -----------------------------
@@ -16,7 +16,7 @@ def tokenize_filename(path):
1616
def longest_shared_prefix_tokens(a, b):
1717
"""Return longest shared prefix between two token lists."""
1818
prefix = []
19-
for x, y in zip(a, b):
19+
for x, y in zip(a, b, strict=True):
2020
if x == y:
2121
prefix.append(x)
2222
else:
@@ -67,7 +67,6 @@ def list_files(base_path, exclude_dirs=None):
6767
return all_files
6868

6969

70-
7170
# -----------------------------
7271
# Matching helpers
7372
# -----------------------------
@@ -81,7 +80,7 @@ def match_exact_folder(norm_ex, folder_ex, src_map, unmatched_src_set):
8180

8281

8382
def match_by_filename_only(norm_ex, src_map, unmatched_src_set):
84-
for (src_folder, src_norm), src_list in src_map.items():
83+
for (_, src_norm), src_list in src_map.items():
8584
if src_norm == norm_ex:
8685
for src_file in src_list:
8786
unmatched_src_set.discard(src_file)

tests/fuzz/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
# with <3 from Anto
1+
# with <3 from Anto

tests/fuzz/support/helpers.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,11 +48,7 @@ def build_valid_transaction_bytes() -> tuple[bytes, bytes]:
4848
node_id = AccountId.from_string("0.0.3")
4949
receiver_id = AccountId.from_string("0.0.5678")
5050

51-
tx = (
52-
TransferTransaction()
53-
.add_hbar_transfer(operator_id, -100_000_000)
54-
.add_hbar_transfer(receiver_id, 100_000_000)
55-
)
51+
tx = TransferTransaction().add_hbar_transfer(operator_id, -100_000_000).add_hbar_transfer(receiver_id, 100_000_000)
5652
tx.transaction_id = TransactionId.generate(operator_id)
5753
tx.node_account_id = node_id
5854
tx.freeze()

tests/fuzz/support/registry.py

Lines changed: 9 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -142,9 +142,7 @@ def _build_alias_identifier_strategies(
142142
)
143143
account_id_valid_evm = st.one_of(
144144
evm_hex.map(lambda value: AccountIdAliasCase(text=value, shard=0, realm=0, evm_hex=value)),
145-
evm_hex.map(
146-
lambda value: AccountIdAliasCase(text=f"0x{value}", shard=0, realm=0, evm_hex=value)
147-
),
145+
evm_hex.map(lambda value: AccountIdAliasCase(text=f"0x{value}", shard=0, realm=0, evm_hex=value)),
148146
st.builds(
149147
lambda shard_value, realm_value, value: AccountIdAliasCase(
150148
text=f"{shard_value}.{realm_value}.{value}",
@@ -243,9 +241,7 @@ def _build_invalid_identifier_strategies() -> dict[str, SearchStrategy[Any]]:
243241
def _build_private_key_strategies(key_samples: _KeySampleValues) -> dict[str, SearchStrategy[Any]]:
244242
"""Build the private key strategies from the canonical valid sample encodings."""
245243
private_key_valid_string = st.one_of(
246-
with_optional_0x(
247-
st.sampled_from([key_samples.ed_private_raw, key_samples.ed_private_der])
248-
),
244+
with_optional_0x(st.sampled_from([key_samples.ed_private_raw, key_samples.ed_private_der])),
249245
)
250246
private_key_valid_bytes = st.sampled_from(
251247
[
@@ -433,32 +429,18 @@ def _build_contract_value_strategies() -> dict[str, SearchStrategy[Any]]:
433429
"""Build valid and invalid contract parameter cases without changing ABI edge coverage."""
434430
valid_contract_value = st.one_of(
435431
st.booleans().map(lambda value: ContractValueCase("add_bool", value)),
436-
st.integers(min_value=-(2**31), max_value=2**31 - 1).map(
437-
lambda value: ContractValueCase("add_int32", value)
438-
),
439-
st.integers(min_value=0, max_value=2**32 - 1).map(
440-
lambda value: ContractValueCase("add_uint32", value)
441-
),
442-
st.integers(min_value=MIN_I64, max_value=MAX_I64).map(
443-
lambda value: ContractValueCase("add_int64", value)
444-
),
445-
st.integers(min_value=0, max_value=2**64 - 1).map(
446-
lambda value: ContractValueCase("add_uint64", value)
447-
),
432+
st.integers(min_value=-(2**31), max_value=2**31 - 1).map(lambda value: ContractValueCase("add_int32", value)),
433+
st.integers(min_value=0, max_value=2**32 - 1).map(lambda value: ContractValueCase("add_uint32", value)),
434+
st.integers(min_value=MIN_I64, max_value=MAX_I64).map(lambda value: ContractValueCase("add_int64", value)),
435+
st.integers(min_value=0, max_value=2**64 - 1).map(lambda value: ContractValueCase("add_uint64", value)),
448436
st.integers(min_value=-(2**255), max_value=2**255 - 1).map(
449437
lambda value: ContractValueCase("add_int256", value)
450438
),
451-
st.integers(min_value=0, max_value=2**256 - 1).map(
452-
lambda value: ContractValueCase("add_uint256", value)
453-
),
439+
st.integers(min_value=0, max_value=2**256 - 1).map(lambda value: ContractValueCase("add_uint256", value)),
454440
st.text(min_size=0, max_size=32).map(lambda value: ContractValueCase("add_string", value)),
455441
st.binary(min_size=0, max_size=64).map(lambda value: ContractValueCase("add_bytes", value)),
456-
st.binary(min_size=0, max_size=32).map(
457-
lambda value: ContractValueCase("add_bytes32", value)
458-
),
459-
st.binary(min_size=20, max_size=20).map(
460-
lambda value: ContractValueCase("add_address", value)
461-
),
442+
st.binary(min_size=0, max_size=32).map(lambda value: ContractValueCase("add_bytes32", value)),
443+
st.binary(min_size=20, max_size=20).map(lambda value: ContractValueCase("add_address", value)),
462444
with_optional_0x(sized_hex(20)).map(lambda value: ContractValueCase("add_address", value)),
463445
st.lists(st.integers(min_value=-(2**31), max_value=2**31 - 1), min_size=0, max_size=6).map(
464446
lambda value: ContractValueCase("add_int32_array", value)

tests/fuzz/test_hbar_fuzz.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,4 +56,4 @@ def test_hbar_rejects_fractional_tinybars(amount: object) -> None:
5656
def test_hbar_constructor_rejects_invalid_types(value: object) -> None:
5757
"""The constructor must not silently coerce unsupported input types."""
5858
with pytest.raises(TypeError):
59-
Hbar(value)
59+
Hbar(value)

0 commit comments

Comments
 (0)