Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

replace linter tools with ruff #258

Merged
merged 7 commits into from
Jan 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 0 additions & 10 deletions .flake8

This file was deleted.

4 changes: 0 additions & 4 deletions .isort.cfg

This file was deleted.

33 changes: 16 additions & 17 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,36 +3,35 @@ repos:
- id: end-of-file-fixer
- id: trailing-whitespace
repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.3.0
rev: v5.0.0
- hooks:
- id: flake8
repo: https://github.com/pycqa/flake8
rev: 6.1.0
- hooks:
- args:
- --profile
- black
id: isort
repo: https://github.com/pycqa/isort
rev: 5.12.0
- id: ruff_format
name: ruff format
entry: ruff format
language: system
require_serial: true
types_or: [python, pyi]
repo: local
- hooks:
- id: black
repo: https://github.com/psf/black
rev: 23.7.0
- id: ruff
name: Ruff
entry: ruff check --fix
language: system
types: [python]
repo: local
- hooks:
- entry: mypy
id: mypy
language: system
name: mypy
pass_filenames: false
repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.11.1
repo: local
- hooks:
- id: commitizen
stages:
- commit-msg
repo: https://github.com/commitizen-tools/commitizen
rev: v2.27.1
rev: v4.1.0
- hooks:
- id: prettier
types_or: [ini, json, toml, yaml, markdown]
Expand Down
2 changes: 1 addition & 1 deletion app/api/dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

import enum
import logging
from collections.abc import AsyncGenerator, AsyncIterator
from contextlib import AbstractAsyncContextManager, asynccontextmanager
from pathlib import Path
from typing import AsyncGenerator, AsyncIterator

from chia.rpc.full_node_rpc_client import FullNodeRpcClient
from chia.rpc.rpc_client import RpcClient
Expand Down
2 changes: 1 addition & 1 deletion app/api/v1/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
from __future__ import annotations

from app.api.v1.core import router
from app.api.v1.core import router as router # noqa: PLC0414
20 changes: 12 additions & 8 deletions app/api/v1/activities.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# noqa: I002
# ignore the required import["from __future__ import annotations"]
# This import breaks everything - seems something to do with pydantic

import logging
from typing import Any, Dict, List, Optional
from typing import Any, Optional

from fastapi import APIRouter, Depends
from fastapi.encoders import jsonable_encoder
Expand Down Expand Up @@ -37,7 +41,7 @@ async def get_activity(

db_crud = crud.DBCrud(db=db)

activity_filters: Dict[str, Any] = {"or": [], "and": []}
activity_filters: dict[str, Any] = {"or": [], "and": []}
cw_filters = {}
match search_by:
case schemas.ActivitySearchBy.ONCHAIN_METADATA:
Expand Down Expand Up @@ -78,7 +82,7 @@ async def get_activity(
if mode is not None:
activity_filters["and"].append(models.Activity.mode.ilike(mode.name))

activities: List[models.Activity]
activities: list[models.Activity]
total: int

order_by_clause = []
Expand All @@ -100,7 +104,7 @@ async def get_activity(
logger.warning(f"No data to get from activities. filters:{activity_filters} page:{page} limit:{limit}")
return schemas.ActivitiesResponse()

activities_with_cw: List[schemas.ActivityWithCW] = []
activities_with_cw: list[schemas.ActivityWithCW] = []
for activity in activities:
unit = units.get(activity.asset_id)
if unit is None:
Expand Down Expand Up @@ -146,7 +150,7 @@ async def get_activity_by_cw_unit_id(
db_crud = crud.DBCrud(db=db)

# fetch unit and related data from CADT
cw_filters: Dict[str, str] = {"warehouseUnitId": cw_unit_id}
cw_filters: dict[str, str] = {"warehouseUnitId": cw_unit_id}

climate_data = crud.ClimateWareHouseCrud(
url=settings.CADT_API_SERVER_HOST,
Expand All @@ -159,7 +163,7 @@ async def get_activity_by_cw_unit_id(
unit_with_metadata = climate_data[0]

# set filters to fetch activity data related to specified unit
activity_filters: Dict[str, Any] = {"or": [], "and": []}
activity_filters: dict[str, Any] = {"or": [], "and": []}
if unit_with_metadata["marketplaceIdentifier"]:
activity_filters["and"].append(models.Activity.asset_id == unit_with_metadata["marketplaceIdentifier"])
else:
Expand All @@ -170,10 +174,10 @@ async def get_activity_by_cw_unit_id(
activity_filters["and"].append(models.Activity.coin_id == coin_id)

activities = [models.Activity]
total: int
_total: int

# fetch activities with filters, 'total' var ignored
(activities, total) = db_crud.select_activity_with_pagination(
(activities, _total) = db_crud.select_activity_with_pagination(
model=models.Activity,
filters=activity_filters,
order_by=[models.Activity.height.asc()],
Expand Down
4 changes: 1 addition & 3 deletions app/api/v1/core.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
from __future__ import annotations

from typing import Dict

from fastapi import APIRouter

from app.api.v1 import activities, cron, keys, organizations, tokens, transactions
Expand All @@ -13,7 +11,7 @@


@router.get("/info")
async def get_info() -> Dict[str, str]:
async def get_info() -> dict[str, str]:
return {
"blockchain_name": "Chia Network",
"blockchain_name_short": "chia",
Expand Down
8 changes: 4 additions & 4 deletions app/api/v1/cron.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import asyncio
import json
import logging
from typing import List, Optional
from typing import Optional

from chia.consensus.block_record import BlockRecord
from chia.rpc.full_node_rpc_client import FullNodeRpcClient
Expand Down Expand Up @@ -38,7 +38,7 @@ async def init_db() -> None:
create_database(Engine.url)
logger.info(f"Create database {Engine.url}")

logger.info(f"Database {Engine.url} exists: " f"{database_exists(Engine.url)}")
logger.info(f"Database {Engine.url} exists: {database_exists(Engine.url)}")

Base.metadata.create_all(Engine)

Expand Down Expand Up @@ -114,7 +114,7 @@ async def _scan_token_activity(
continue

public_key = G1Element.from_bytes(hexstr_to_bytes(tokenization_dict["public_key"]))
activities: List[schemas.Activity] = await blockchain.get_activities(
activities: list[schemas.Activity] = await blockchain.get_activities(
org_uid=tokenization_dict["org_uid"],
warehouse_project_id=tokenization_dict["warehouse_project_id"],
vintage_year=tokenization_dict["vintage_year"],
Expand All @@ -135,7 +135,7 @@ async def _scan_token_activity(
# except json.JSONDecodeError as e:
# logger.error(f"Failed to parse JSON for key {key} in organization {org_name}: {str(e)}")
except Exception as e:
logger.error(f"An error occurred for organization {org_name} under key {key}: {str(e)}")
logger.error(f"An error occurred for organization {org_name} under key {key}: {e!s}")

db_crud.update_block_state(current_height=target_start_height)
return True
Expand Down
4 changes: 4 additions & 0 deletions app/api/v1/keys.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# noqa: I002
# ignore the required import["from __future__ import annotations"]
# This import breaks everything - seems something to do with pydantic

from typing import Optional

from chia.consensus.coinbase import create_puzzlehash_for_pk
Expand Down
4 changes: 4 additions & 0 deletions app/api/v1/organizations.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# noqa: I002
# ignore the required import["from __future__ import annotations"]
# This import breaks everything - seems something to do with pydantic

from typing import Any

from fastapi import APIRouter
Expand Down
14 changes: 9 additions & 5 deletions app/api/v1/tokens.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
# noqa: I002
# ignore the required import["from __future__ import annotations"]
# This import breaks everything - seems something to do with pydantic

import json
import logging
from typing import Any, Dict, Tuple
from typing import Any

from chia.rpc.wallet_rpc_client import WalletRpcClient
from chia.types.blockchain_format.sized_bytes import bytes32
Expand Down Expand Up @@ -59,7 +63,7 @@ async def create_tokenization_tx(
)
(transaction_record, *_) = result["transaction_records"]

token_obj: Dict[str, Any] = {
token_obj: dict[str, Any] = {
"index": wallet.token_index.name(),
"public_key": bytes(wallet.root_public_key),
"asset_id": wallet.tail_program_hash,
Expand Down Expand Up @@ -168,10 +172,10 @@ async def create_detokenization_file(
)
tail_metadata = token.detokenization

mode_to_public_key: Dict[GatewayMode, G1Element] = {
mode_to_public_key: dict[GatewayMode, G1Element] = {
GatewayMode.DETOKENIZATION: G1Element.from_bytes(tail_metadata.public_key),
}
mode_to_message_and_signature: Dict[GatewayMode, Tuple[bytes, G2Element]] = {
mode_to_message_and_signature: dict[GatewayMode, tuple[bytes, G2Element]] = {
GatewayMode.DETOKENIZATION: (
tail_metadata.mod_hash,
G2Element.from_bytes(tail_metadata.signature),
Expand Down Expand Up @@ -275,7 +279,7 @@ async def create_permissionless_retirement_tx(
)
tail_metadata = token.permissionless_retirement

mode_to_message_and_signature: Dict[GatewayMode, Tuple[bytes, G2Element]] = {
mode_to_message_and_signature: dict[GatewayMode, tuple[bytes, G2Element]] = {
GatewayMode.PERMISSIONLESS_RETIREMENT: (
tail_metadata.mod_hash,
G2Element.from_bytes(tail_metadata.signature),
Expand Down
15 changes: 9 additions & 6 deletions app/api/v1/transactions.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
from typing import List, Optional
# noqa: I002
# ignore the required import["from __future__ import annotations"]
# This import breaks everything - seems something to do with pydantic

from typing import Optional

from chia.rpc.wallet_rpc_client import WalletRpcClient
from chia.types.blockchain_format.coin import Coin
Expand Down Expand Up @@ -67,7 +71,7 @@ async def get_transactions(
This endpoint is to be called by the client.
"""

transaction_records: List[TransactionRecord] = await wallet_rpc_client.get_transactions(
transaction_records: list[TransactionRecord] = await wallet_rpc_client.get_transactions(
wallet_id=wallet_id,
start=start,
end=end,
Expand All @@ -76,10 +80,10 @@ async def get_transactions(
to_address=to_address,
)

wallet_objs: List[ChiaJsonObject] = await wallet_rpc_client.get_wallets(
wallet_objs: list[ChiaJsonObject] = await wallet_rpc_client.get_wallets(
wallet_type=WalletType.CAT,
)
wallet_infos: List[WalletInfo] = [WalletInfo.from_json_dict(wallet_obj) for wallet_obj in wallet_objs]
wallet_infos: list[WalletInfo] = [WalletInfo.from_json_dict(wallet_obj) for wallet_obj in wallet_objs]

wallet_info: Optional[WalletInfo]
cat_info: Optional[CATInfo] = None
Expand Down Expand Up @@ -130,8 +134,7 @@ async def get_transactions(
raise ValueError(f"No coin with puzzle hash {gateway_cat_puzzle_hash.hex()}")

mode: GatewayMode
tail_spend: CoinSpend
(mode, tail_spend) = parse_gateway_spend(coin_spend=coin_spend, is_cat=True)
(mode, _tail_spend) = parse_gateway_spend(coin_spend=coin_spend, is_cat=True)

transaction = transaction_record.to_json_dict()
transaction["type"] = CLIMATE_WALLET_INDEX + mode.to_int()
Expand Down
8 changes: 4 additions & 4 deletions app/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import shutil
import sys
from pathlib import Path
from typing import Any, Dict, Optional
from typing import Any, Optional

import yaml
from pydantic import BaseSettings, root_validator, validator
Expand Down Expand Up @@ -71,7 +71,7 @@ def get_instance(cls) -> Settings:
return cls._instance

@root_validator(skip_on_failure=True)
def configure_port(cls, values: Dict[str, Any]) -> Dict[str, Any]:
def configure_port(cls, values: dict[str, Any]) -> dict[str, Any]:
if values["MODE"] == ExecutionMode.REGISTRY:
values["SERVER_PORT"] = values.get("CLIMATE_TOKEN_REGISTRY_PORT", ServerPort.CLIMATE_TOKEN_REGISTRY.value)
elif values["MODE"] == ExecutionMode.CLIENT:
Expand All @@ -90,7 +90,7 @@ def expand_root(cls, v: str) -> Path:
return Path(v).expanduser()

@validator("CONFIG_PATH", "LOG_PATH", "DB_PATH")
def prepend_root(cls, v: str, values: Dict[str, Any]) -> Path:
def prepend_root(cls, v: str, values: dict[str, Any]) -> Path:
full_dir: Path = values["CHIA_ROOT"] / v
parent: Path = full_dir.parent
parent.mkdir(parents=True, exist_ok=True)
Expand All @@ -117,7 +117,7 @@ def get_settings() -> Settings:
config_file.parent.mkdir(parents=True, exist_ok=True)
shutil.copy(default_config_file, config_file)

with open(config_file, "r") as f:
with open(config_file) as f:
settings_dict = yaml.safe_load(f)

settings_dict = default_settings.dict() | (settings_dict or {})
Expand Down
4 changes: 2 additions & 2 deletions app/core/chialisp/gateway.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from __future__ import annotations

from typing import Optional, Tuple
from typing import Optional

from chia.types.blockchain_format.coin import Coin
from chia.types.blockchain_format.program import Program
Expand Down Expand Up @@ -45,7 +45,7 @@ def create_gateway_announcement(
def parse_gateway_spend(
coin_spend: CoinSpend,
is_cat: bool = True,
) -> Tuple[GatewayMode, CoinSpend]:
) -> tuple[GatewayMode, CoinSpend]:
puzzle: Program = coin_spend.puzzle_reveal.to_program()
solution: Program = coin_spend.solution.to_program()
coin: Coin = coin_spend.coin
Expand Down
Loading
Loading