Merge pull request #1369 from prusnak/autoflake

add flake8 + add pylint + fix reported issues
This commit is contained in:
Arc 2023-01-31 11:47:56 +00:00 committed by GitHub
commit c45c6b8ae8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
144 changed files with 677 additions and 414 deletions

27
.github/workflows/flake8.yml vendored Normal file
View file

@ -0,0 +1,27 @@
name: flake8
on: [push, pull_request]
jobs:
check:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.9"]
poetry-version: ["1.3.1"]
steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- name: Set up Poetry ${{ matrix.poetry-version }}
uses: abatilo/actions-poetry@v2
with:
poetry-version: ${{ matrix.poetry-version }}
- name: Install dependencies
run: |
poetry config virtualenvs.create false
poetry install
- name: Run tests
run: make flake8

27
.github/workflows/pylint.yml vendored Normal file
View file

@ -0,0 +1,27 @@
name: pylint
on: [push, pull_request]
jobs:
check:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.9"]
poetry-version: ["1.3.1"]
steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- name: Set up Poetry ${{ matrix.poetry-version }}
uses: abatilo/actions-poetry@v2
with:
poetry-version: ${{ matrix.poetry-version }}
- name: Install dependencies
run: |
poetry config virtualenvs.create false
poetry install
- name: Run tests
run: make pylint

View file

@ -15,12 +15,18 @@ pyright:
black:
poetry run black .
flake8:
poetry run flake8
mypy:
poetry run mypy
isort:
poetry run isort .
pylint:
poetry run pylint *.py lnbits/ tools/ tests/
checkprettier: $(shell find lnbits -name "*.js" -o -name ".html")
./node_modules/.bin/prettier --check lnbits/static/js/*.js lnbits/core/static/js/*.js lnbits/extensions/*/templates/*/*.html ./lnbits/core/templates/core/*.html lnbits/templates/*.html lnbits/extensions/*/static/js/*.js lnbits/extensions/*/static/components/*/*.js lnbits/extensions/*/static/components/*/*.html

View file

@ -1,12 +1,9 @@
import glob
import os
import subprocess
import warnings
from os import path
from pathlib import Path
from typing import Any, List, NamedTuple, Optional
from typing import List
LNBITS_PATH = path.dirname(path.realpath(__file__)) + "/lnbits"
LNBITS_PATH = os.path.dirname(os.path.realpath(__file__)) + "/lnbits"
def get_js_vendored(prefer_minified: bool = False) -> List[str]:

View file

@ -95,7 +95,7 @@ async def check_funding_source() -> None:
original_sigint_handler = signal.getsignal(signal.SIGINT)
def signal_handler(signal, frame):
logger.debug(f"SIGINT received, terminating LNbits.")
logger.debug("SIGINT received, terminating LNbits.")
sys.exit(1)
signal.signal(signal.SIGINT, signal_handler)
@ -388,7 +388,7 @@ class Formatter:
self.fmt: str = self.minimal_fmt
def format(self, record):
function = "{function}".format(**record)
function = "{function}".format(**record) # pylint: disable=C0209
if function == "emit": # uvicorn logs
return self.minimal_fmt
return self.fmt

View file

@ -5,7 +5,6 @@ from decimal import Decimal
from typing import List, NamedTuple, Optional
import bitstring
import embit
import secp256k1
from bech32 import CHARSET, bech32_decode, bech32_encode
from ecdsa import SECP256k1, VerifyingKey
@ -20,7 +19,7 @@ class Route(NamedTuple):
cltv: int
class Invoice(object):
class Invoice:
payment_hash: str
amount_msat: int = 0
description: Optional[str] = None
@ -166,9 +165,7 @@ def lnencode(addr, privkey):
amount = Decimal(str(addr.amount))
# We can only send down to millisatoshi.
if amount * 10**12 % 10:
raise ValueError(
"Cannot encode {}: too many decimal places".format(addr.amount)
)
raise ValueError(f"Cannot encode {addr.amount}: too many decimal places")
amount = addr.currency + shorten_amount(amount)
else:
@ -190,7 +187,7 @@ def lnencode(addr, privkey):
# A writer MUST NOT include more than one `d`, `h`, `n` or `x` fields,
if k in ("d", "h", "n", "x"):
if k in tags_set:
raise ValueError("Duplicate '{}' tag".format(k))
raise ValueError(f"Duplicate '{k}' tag")
if k == "r":
route = bitstring.BitArray()
@ -220,7 +217,7 @@ def lnencode(addr, privkey):
data += tagged_bytes("n", v)
else:
# FIXME: Support unknown tags?
raise ValueError("Unknown tag {}".format(k))
raise ValueError(f"Unknown tag {k}")
tags_set.add(k)
@ -230,7 +227,7 @@ def lnencode(addr, privkey):
# both.
if "d" in tags_set and "h" in tags_set:
raise ValueError("Cannot include both 'd' and 'h'")
if not "d" in tags_set and not "h" in tags_set:
if "d" not in tags_set and "h" not in tags_set:
raise ValueError("Must include either 'd' or 'h'")
# We actually sign the hrp, then data (padded to 8 bits with zeroes).
@ -245,7 +242,7 @@ def lnencode(addr, privkey):
return bech32_encode(hrp, bitarray_to_u5(data))
class LnAddr(object):
class LnAddr:
def __init__(
self, paymenthash=None, amount=None, currency="bc", tags=None, date=None
):
@ -259,12 +256,9 @@ class LnAddr(object):
self.amount = amount
def __str__(self):
return "LnAddr[{}, amount={}{} tags=[{}]]".format(
bytes.hex(self.pubkey.serialize()).decode(),
self.amount,
self.currency,
", ".join([k + "=" + str(v) for k, v in self.tags]),
)
pubkey = bytes.hex(self.pubkey.serialize()).decode()
tags = ", ".join([k + "=" + str(v) for k, v in self.tags])
return f"LnAddr[{pubkey}, amount={self.amount}{self.currency} tags=[{tags}]]"
def shorten_amount(amount):
@ -296,7 +290,7 @@ def _unshorten_amount(amount: str) -> int:
# A reader SHOULD fail if `amount` contains a non-digit, or is followed by
# anything except a `multiplier` in the table above.
if not re.fullmatch(r"\d+[pnum]?", str(amount)):
raise ValueError("Invalid amount '{}'".format(amount))
raise ValueError(f"Invalid amount '{amount}'")
if unit in units:
return int(int(amount[:-1]) * 100_000_000_000 / units[unit])
@ -347,11 +341,10 @@ def _trim_to_bytes(barr):
def _readable_scid(short_channel_id: int) -> str:
return "{blockheight}x{transactionindex}x{outputindex}".format(
blockheight=((short_channel_id >> 40) & 0xFFFFFF),
transactionindex=((short_channel_id >> 16) & 0xFFFFFF),
outputindex=(short_channel_id & 0xFFFF),
)
blockheight = (short_channel_id >> 40) & 0xFFFFFF
transactionindex = (short_channel_id >> 16) & 0xFFFFFF
outputindex = short_channel_id & 0xFFFF
return f"{blockheight}x{transactionindex}x{outputindex}"
def _u5_to_bitarray(arr: List[int]) -> bitstring.BitArray:

View file

@ -9,7 +9,7 @@ core_app: APIRouter = APIRouter()
core_app_extra: CoreAppExtra = CoreAppExtra()
from .views.admin_api import * # noqa
from .views.api import * # noqa
from .views.generic import * # noqa
from .views.public_api import * # noqa
from .views.admin_api import * # noqa: F401,F403
from .views.api import * # noqa: F401,F403
from .views.generic import * # noqa: F401,F403
from .views.public_api import * # noqa: F401,F403

View file

@ -358,7 +358,7 @@ async def get_payments(
args: List[Any] = []
clause: List[str] = []
if since != None:
if since is not None:
if db.type == POSTGRES:
clause.append("time > to_timestamp(?)")
elif db.type == COCKROACH:
@ -702,7 +702,7 @@ async def delete_admin_settings():
async def update_admin_settings(data: EditableSettings):
await db.execute(f"UPDATE settings SET editable_settings = ?", (json.dumps(data),))
await db.execute("UPDATE settings SET editable_settings = ?", (json.dumps(data),))
async def update_super_user(super_user: str):
@ -711,7 +711,7 @@ async def update_super_user(super_user: str):
async def create_admin_settings(super_user: str, new_settings: dict):
sql = f"INSERT INTO settings (super_user, editable_settings) VALUES (?, ?)"
sql = "INSERT INTO settings (super_user, editable_settings) VALUES (?, ?)"
await db.execute(sql, (super_user, json.dumps(new_settings)))
return await get_super_settings()
@ -740,7 +740,7 @@ async def update_migration_version(conn, db_name, version):
async def create_tinyurl(domain: str, endless: bool, wallet: str):
tinyurl_id = shortuuid.uuid()[:8]
await db.execute(
f"INSERT INTO tiny_url (id, url, endless, wallet) VALUES (?, ?, ?, ?)",
"INSERT INTO tiny_url (id, url, endless, wallet) VALUES (?, ?, ?, ?)",
(
tinyurl_id,
domain,
@ -753,7 +753,7 @@ async def create_tinyurl(domain: str, endless: bool, wallet: str):
async def get_tinyurl(tinyurl_id: str) -> Optional[TinyURL]:
row = await db.fetchone(
f"SELECT * FROM tiny_url WHERE id = ?",
"SELECT * FROM tiny_url WHERE id = ?",
(tinyurl_id,),
)
return TinyURL.from_row(row) if row else None
@ -761,14 +761,14 @@ async def get_tinyurl(tinyurl_id: str) -> Optional[TinyURL]:
async def get_tinyurl_by_url(url: str) -> List[TinyURL]:
rows = await db.fetchall(
f"SELECT * FROM tiny_url WHERE url = ?",
"SELECT * FROM tiny_url WHERE url = ?",
(url,),
)
return [TinyURL.from_row(row) for row in rows]
async def delete_tinyurl(tinyurl_id: str):
row = await db.execute(
f"DELETE FROM tiny_url WHERE id = ?",
await db.execute(
"DELETE FROM tiny_url WHERE id = ?",
(tinyurl_id,),
)

View file

@ -37,7 +37,7 @@ async def run_migration(db: Connection, migrations_module: Any, current_version:
print(f"running migration {db_name}.{version}")
await migrate(db)
if db.schema == None:
if db.schema is None:
await update_migration_version(db, db_name, version)
else:
async with core_db.connect() as conn:

View file

@ -6,8 +6,8 @@ import time
from sqlite3 import Row
from typing import Callable, Dict, List, Optional
from ecdsa import SECP256k1, SigningKey # type: ignore
from lnurl import encode as lnurl_encode # type: ignore
from ecdsa import SECP256k1, SigningKey
from lnurl import encode as lnurl_encode
from loguru import logger
from pydantic import BaseModel

View file

@ -14,7 +14,6 @@ from lnbits import bolt11
from lnbits.db import Connection
from lnbits.decorators import WalletTypeInfo, require_admin_key
from lnbits.helpers import url_for, urlsafe_short_hash
from lnbits.requestvars import g
from lnbits.settings import (
FAKE_WALLET,
EditableSettings,
@ -22,7 +21,6 @@ from lnbits.settings import (
readonly_variables,
send_admin_user_to_saas,
settings,
transient_variables,
)
from lnbits.wallets.base import PaymentResponse, PaymentStatus
@ -214,22 +212,22 @@ async def pay_invoice(
)
logger.debug(f"backend: pay_invoice finished {temp_id}")
if payment.checking_id and payment.ok != False:
if payment.checking_id and payment.ok is not False:
# payment.ok can be True (paid) or None (pending)!
logger.debug(f"updating payment {temp_id}")
async with db.connect() as conn:
await update_payment_details(
checking_id=temp_id,
pending=payment.ok != True,
pending=payment.ok is not True,
fee=payment.fee_msat,
preimage=payment.preimage,
new_checking_id=payment.checking_id,
conn=conn,
)
logger.debug(f"payment successful {payment.checking_id}")
elif payment.checking_id is None and payment.ok == False:
elif payment.checking_id is None and payment.ok is False:
# payment failed
logger.warning(f"backend sent payment failure")
logger.warning("backend sent payment failure")
async with db.connect() as conn:
logger.debug(f"deleting temporary payment {temp_id}")
await delete_wallet_payment(temp_id, wallet_id, conn=conn)
@ -431,7 +429,7 @@ async def check_admin_settings():
update_cached_settings(settings_db.dict())
# printing settings for debugging
logger.debug(f"Admin settings:")
logger.debug("Admin settings:")
for key, value in settings.dict(exclude_none=True).items():
logger.debug(f"{key}: {value}")
@ -449,7 +447,7 @@ async def check_admin_settings():
def update_cached_settings(sets_dict: dict):
for key, value in sets_dict.items():
if not key in readonly_variables + transient_variables:
if key not in readonly_variables:
try:
setattr(settings, key, value)
except:

View file

@ -184,7 +184,7 @@ async def api_payments_create_invoice(data: CreateInvoiceData, wallet: Wallet):
async with db.connect() as conn:
try:
payment_hash, payment_request = await create_invoice(
_, payment_request = await create_invoice(
wallet_id=wallet.id,
amount=amount,
memo=memo,
@ -560,10 +560,10 @@ async def api_lnurlscan(code: str, wallet: WalletTypeInfo = Depends(get_key_type
for [k, v] in metadata:
if k == "text/plain":
params.update(description=v)
if k == "image/jpeg;base64" or k == "image/png;base64":
if k in ("image/jpeg;base64", "image/png;base64"):
data_uri = "data:" + k + "," + v
params.update(image=data_uri)
if k == "text/email" or k == "text/identifier":
if k in ("text/email", "text/identifier"):
params.update(targetUser=v)
params.update(commentAllowed=data.get("commentAllowed", 0))
@ -702,7 +702,7 @@ async def websocket_connect(websocket: WebSocket, item_id: str):
await websocketManager.connect(websocket)
try:
while True:
data = await websocket.receive_text()
await websocket.receive_text()
except WebSocketDisconnect:
websocketManager.disconnect(websocket)

View file

@ -120,7 +120,7 @@ async def extensions_install(
)
)
await update_installed_extension_state(
ext_id=ext_id, active=activate != None
ext_id=ext_id, active=activate is not None
)
all_extensions = list(map(lambda e: e.code, get_valid_extensions()))
@ -137,7 +137,7 @@ async def extensions_install(
"dependencies": ext.dependencies,
"isInstalled": ext.id in installed_exts_ids,
"isAvailable": ext.id in all_extensions,
"isActive": not ext.id in inactive_extensions,
"isActive": ext.id not in inactive_extensions,
"latestRelease": dict(ext.latest_release)
if ext.latest_release
else None,

View file

@ -135,7 +135,7 @@ class Database(Compat):
if value is None:
return None
f = "%Y-%m-%d %H:%M:%S.%f"
if not "." in value:
if "." not in value:
f = "%Y-%m-%d %H:%M:%S"
return time.mktime(datetime.datetime.strptime(value, f).timetuple())

View file

@ -245,7 +245,7 @@ async def check_user_exists(usr: UUID4) -> User:
async def check_admin(usr: UUID4) -> User:
user = await check_user_exists(usr)
if user.id != settings.super_user and not user.id in settings.lnbits_admin_users:
if user.id != settings.super_user and user.id not in settings.lnbits_admin_users:
raise HTTPException(
status_code=HTTPStatus.UNAUTHORIZED,
detail="User not authorized. No admin privileges.",

View file

@ -240,7 +240,7 @@ class InstallableExtension(BaseModel):
return False
with open(config_file, "r") as json_file:
config_json = json.load(json_file)
return config_json.get("is_installed") == True
return config_json.get("is_installed") is True
def download_archive(self):
ext_zip_file = self.zip_path
@ -467,7 +467,7 @@ class InstalledExtensionMiddleware:
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if not "path" in scope:
if "path" not in scope:
await self.app(scope, receive, send)
return

View file

@ -21,6 +21,6 @@ def bleskomat_renderer():
return template_renderer(["lnbits/extensions/bleskomat/templates"])
from .lnurl_api import * # noqa
from .views import * # noqa
from .views_api import * # noqa
from .lnurl_api import * # noqa: F401,F403
from .views import * # noqa: F401,F403
from .views_api import * # noqa: F401,F403

View file

@ -1,6 +1,6 @@
import json
import os
from typing import Callable, Dict, Union
from typing import Callable, Union
import httpx

View file

@ -128,7 +128,7 @@ def unshorten_lnurl_query(query: dict) -> Dict[str, str]:
long_tag = rules["tags"][tag]
new_query["tag"] = long_tag
tag = long_tag
if not tag in rules["params"]:
if tag not in rules["params"]:
raise LnurlValidationError(f'Unknown tag: "{tag}"')
for key in query:
if key in rules["params"][str(tag)]:
@ -142,7 +142,7 @@ def unshorten_lnurl_query(query: dict) -> Dict[str, str]:
# Unshorten general keys:
short_key = key
long_key = rules["query"][short_key]
if not long_key in new_query:
if long_key not in new_query:
if short_key in query:
new_query[long_key] = query[short_key]
else:

View file

@ -42,7 +42,7 @@ async def api_bleskomat_lnurl(req: Request):
# The API key ID, nonce, and tag should be present in the query string.
for field in ["id", "nonce", "tag"]:
if not field in query:
if field not in query:
raise LnurlHttpError(
f'Failed API key signature check: Missing "{field}"',
HTTPStatus.BAD_REQUEST,
@ -105,7 +105,7 @@ async def api_bleskomat_lnurl(req: Request):
# No signature provided.
# Treat as "action" callback.
if not "k1" in query:
if "k1" not in query:
raise LnurlHttpError("Missing secret", HTTPStatus.BAD_REQUEST)
secret = query["k1"]

View file

@ -85,7 +85,7 @@ class BleskomatLnurl(BaseModel):
# Perform tag-specific checks.
if tag == "withdrawRequest":
for field in ["pr"]:
if not field in query:
if field not in query:
raise LnurlValidationError(f'Missing required parameter: "{field}"')
# Check the bolt11 invoice(s) provided.
pr = query["pr"]

View file

@ -24,14 +24,14 @@ def boltcards_renderer():
return template_renderer(["lnbits/extensions/boltcards/templates"])
from .lnurl import * # noqa
from .tasks import * # noqa
from .lnurl import * # noqa: F401,F403
from .tasks import * # noqa: F401,F403
def boltcards_start():
loop = asyncio.get_event_loop()
loop.create_task(catch_everything_and_restart(wait_for_paid_invoices))
loop.create_task(catch_everything_and_restart(wait_for_paid_invoices)) # noqa: F405
from .views import * # noqa
from .views_api import * # noqa
from .views import * # noqa: F401,F403
from .views_api import * # noqa: F401,F403

View file

@ -160,7 +160,7 @@ async def update_card_otp(otp: str, id: str):
async def get_hit(hit_id: str) -> Optional[Hit]:
row = await db.fetchone(f"SELECT * FROM boltcards.hits WHERE id = ?", (hit_id,))
row = await db.fetchone("SELECT * FROM boltcards.hits WHERE id = ?", (hit_id,))
if not row:
return None
@ -183,7 +183,7 @@ async def get_hits(cards_ids: List[str]) -> List[Hit]:
async def get_hits_today(card_id: str) -> List[Hit]:
rows = await db.fetchall(
f"SELECT * FROM boltcards.hits WHERE card_id = ?",
"SELECT * FROM boltcards.hits WHERE card_id = ?",
(card_id,),
)
updatedrow = []
@ -258,7 +258,7 @@ async def create_refund(hit_id, refund_amount) -> Refund:
async def get_refund(refund_id: str) -> Optional[Refund]:
row = await db.fetchone(
f"SELECT * FROM boltcards.refunds WHERE id = ?", (refund_id,)
"SELECT * FROM boltcards.refunds WHERE id = ?", (refund_id,)
)
if not row:
return None

View file

@ -28,6 +28,7 @@ from .nxp424 import decryptSUN, getSunMAC
###############LNURLWITHDRAW#################
# /boltcards/api/v1/scan?p=00000000000000000000000000000000&c=0000000000000000
@boltcards_ext.get("/api/v1/scan/{external_id}")
async def api_scan(p, c, request: Request, external_id: str = Query(None)):
@ -123,7 +124,7 @@ async def lnurl_callback(
wallet_id=card.wallet,
payment_request=pr,
max_sat=card.tx_limit,
extra={"tag": "boltcard", "tag": hit.id},
extra={"tag": "boltcard", "hit": hit.id},
)
return {"status": "OK"}
except Exception as exc:
@ -180,7 +181,7 @@ async def lnurlp_response(req: Request, hit_id: str = Query(None)):
card = await get_card(hit.card_id)
assert card
if not hit:
return {"status": "ERROR", "reason": f"LNURL-pay record not found."}
return {"status": "ERROR", "reason": "LNURL-pay record not found."}
if not card.enable:
return {"status": "ERROR", "reason": "Card is disabled."}
payResponse = {
@ -204,7 +205,7 @@ async def lnurlp_callback(hit_id: str = Query(None), amount: str = Query(None)):
card = await get_card(hit.card_id)
assert card
if not hit:
return {"status": "ERROR", "reason": f"LNURL-pay record not found."}
return {"status": "ERROR", "reason": "LNURL-pay record not found."}
_, payment_request = await create_invoice(
wallet_id=card.wallet,

View file

@ -1,6 +1,3 @@
from lnbits.helpers import urlsafe_short_hash
async def m001_initial(db):
await db.execute(
"""

View file

@ -25,8 +25,8 @@ boltz_static_files = [
]
from .tasks import check_for_pending_swaps, wait_for_paid_invoices
from .views import * # noqa
from .views_api import * # noqa
from .views import * # noqa: F401,F403
from .views_api import * # noqa: F401,F403
def boltz_start():

View file

@ -32,7 +32,7 @@ async def get_submarine_swaps(wallet_ids: Union[str, List[str]]) -> List[Submari
async def get_all_pending_submarine_swaps() -> List[SubmarineSwap]:
rows = await db.fetchall(
f"SELECT * FROM boltz.submarineswap WHERE status='pending' order by time DESC",
"SELECT * FROM boltz.submarineswap WHERE status='pending' order by time DESC",
)
return [SubmarineSwap(**row) for row in rows]
@ -107,7 +107,7 @@ async def get_reverse_submarine_swaps(
async def get_all_pending_reverse_submarine_swaps() -> List[ReverseSubmarineSwap]:
rows = await db.fetchall(
f"SELECT * FROM boltz.reverse_submarineswap WHERE status='pending' order by time DESC"
"SELECT * FROM boltz.reverse_submarineswap WHERE status='pending' order by time DESC"
)
return [ReverseSubmarineSwap(**row) for row in rows]

View file

@ -101,10 +101,10 @@ async def check_for_pending_swaps():
swaps = await get_all_pending_submarine_swaps()
reverse_swaps = await get_all_pending_reverse_submarine_swaps()
if len(swaps) > 0 or len(reverse_swaps) > 0:
logger.debug(f"Boltz - startup swap check")
logger.debug("Boltz - startup swap check")
except:
logger.error(
f"Boltz - startup swap check, database is not created yet, do nothing"
"Boltz - startup swap check, database is not created yet, do nothing"
)
return
@ -143,10 +143,10 @@ async def check_swap(swap: SubmarineSwap, client):
timeout_block_height=swap.timeout_block_height,
)
await update_swap_status(swap.id, "refunded")
except BoltzNotFoundException as exc:
except BoltzNotFoundException:
logger.debug(f"Boltz - swap: {swap.boltz_id} does not exist.")
await update_swap_status(swap.id, "failed")
except MempoolBlockHeightException as exc:
except MempoolBlockHeightException:
logger.debug(
f"Boltz - tried to refund swap: {swap.id}, but has not reached the timeout."
)
@ -171,7 +171,7 @@ async def check_reverse_swap(reverse_swap: ReverseSubmarineSwap, client):
logger.debug(f"Boltz - swap_status: {str(exc)}")
await update_swap_status(reverse_swap.id, "failed")
# should only happen while development when regtest is reset
except BoltzNotFoundException as exc:
except BoltzNotFoundException:
logger.debug(f"Boltz - reverse swap: {reverse_swap.boltz_id} does not exist.")
await update_swap_status(reverse_swap.id, "failed")
except Exception as exc:

View file

@ -37,7 +37,7 @@ from .utils import check_balance, create_boltz_client, execute_reverse_swap
@boltz_ext.get(
"/api/v1/swap/mempool",
name=f"boltz.get /swap/mempool",
name="boltz.get /swap/mempool",
summary="get a the mempool url",
description="""
This endpoint gets the URL from mempool.space
@ -52,7 +52,7 @@ async def api_mempool_url():
# NORMAL SWAP
@boltz_ext.get(
"/api/v1/swap",
name=f"boltz.get /swap",
name="boltz.get /swap",
summary="get a list of swaps a swap",
description="""
This endpoint gets a list of normal swaps.
@ -74,7 +74,7 @@ async def api_submarineswap(
@boltz_ext.post(
"/api/v1/swap/refund",
name=f"boltz.swap_refund",
name="boltz.swap_refund",
summary="refund of a swap",
description="""
This endpoint attempts to refund a normal swaps, creates onchain tx and sets swap status ro refunded.
@ -122,7 +122,7 @@ async def api_submarineswap_refund(swap_id: str):
@boltz_ext.post(
"/api/v1/swap",
status_code=status.HTTP_201_CREATED,
name=f"boltz.post /swap",
name="boltz.post /swap",
summary="create a submarine swap",
description="""
This endpoint creates a submarine swap
@ -164,7 +164,7 @@ async def api_submarineswap_create(data: CreateSubmarineSwap):
# REVERSE SWAP
@boltz_ext.get(
"/api/v1/swap/reverse",
name=f"boltz.get /swap/reverse",
name="boltz.get /swap/reverse",
summary="get a list of reverse swaps",
description="""
This endpoint gets a list of reverse swaps.
@ -187,7 +187,7 @@ async def api_reverse_submarineswap(
@boltz_ext.post(
"/api/v1/swap/reverse",
status_code=status.HTTP_201_CREATED,
name=f"boltz.post /swap/reverse",
name="boltz.post /swap/reverse",
summary="create a reverse submarine swap",
description="""
This endpoint creates a reverse submarine swap
@ -221,7 +221,7 @@ async def api_reverse_submarineswap_create(
@boltz_ext.get(
"/api/v1/swap/reverse/auto",
name=f"boltz.get /swap/reverse/auto",
name="boltz.get /swap/reverse/auto",
summary="get a list of auto reverse swaps",
description="""
This endpoint gets a list of auto reverse swaps.
@ -244,7 +244,7 @@ async def api_auto_reverse_submarineswap(
@boltz_ext.post(
"/api/v1/swap/reverse/auto",
status_code=status.HTTP_201_CREATED,
name=f"boltz.post /swap/reverse/auto",
name="boltz.post /swap/reverse/auto",
summary="create a auto reverse submarine swap",
description="""
This endpoint creates a auto reverse submarine swap
@ -273,7 +273,7 @@ async def api_auto_reverse_submarineswap_create(data: CreateAutoReverseSubmarine
@boltz_ext.delete(
"/api/v1/swap/reverse/auto/{swap_id}",
name=f"boltz.delete /swap/reverse/auto",
name="boltz.delete /swap/reverse/auto",
summary="delete a auto reverse submarine swap",
description="""
This endpoint deletes a auto reverse submarine swap
@ -288,7 +288,7 @@ async def api_auto_reverse_submarineswap_delete(swap_id: str):
@boltz_ext.post(
"/api/v1/swap/status",
name=f"boltz.swap_status",
name="boltz.swap_status",
summary="shows the status of a swap",
description="""
This endpoint attempts to get the status of the swap.
@ -315,7 +315,7 @@ async def api_swap_status(swap_id: str):
@boltz_ext.get(
"/api/v1/swap/boltz",
name=f"boltz.get /swap/boltz",
name="boltz.get /swap/boltz",
summary="get a boltz configuration",
description="""
This endpoint gets configuration for boltz. (limits, fees...)

View file

@ -10,7 +10,6 @@ from lnbits.tasks import catch_everything_and_restart
db = Database("ext_cashu")
import sys
cashu_static_files = [
{
@ -38,8 +37,8 @@ def cashu_renderer():
from .tasks import startup_cashu_mint, wait_for_paid_invoices
from .views import * # noqa
from .views_api import * # noqa
from .views import * # noqa: F401,F403
from .views_api import * # noqa: F401,F403
def cashu_start():

View file

@ -1,18 +1,7 @@
import os
import random
import time
from typing import Any, List, Optional, Union
from cashu.core.base import MintKeyset
from embit import bip32, bip39, ec, script
from embit.networks import NETWORKS
from loguru import logger
from lnbits.db import Connection, Database
from lnbits.helpers import urlsafe_short_hash
from typing import List, Optional, Union
from . import db
from .models import Cashu, Pegs, Promises, Proof
from .models import Cashu
async def create_cashu(

View file

@ -1,5 +1,5 @@
from sqlite3 import Row
from typing import List, Union
from typing import List
from fastapi import Query
from pydantic import BaseModel

View file

@ -1,5 +1,4 @@
import asyncio
import json
from cashu.core.migrations import migrate_databases
from cashu.mint import migrations
@ -8,14 +7,12 @@ from lnbits.core.models import Payment
from lnbits.tasks import register_invoice_listener
from . import db, ledger
from .crud import get_cashu
async def startup_cashu_mint():
await migrate_databases(db, migrations)
await ledger.load_used_proofs()
await ledger.init_keysets(autosave=False)
pass
async def wait_for_paid_invoices():

View file

@ -1,6 +1,6 @@
import math
from http import HTTPStatus
from typing import Dict, List, Union
from typing import Dict, Union
# -------- cashu imports
from cashu.core.base import (
@ -322,7 +322,7 @@ async def melt_coins(
await pay_invoice(
wallet_id=cashu.wallet,
payment_request=invoice,
description=f"Pay cashu invoice",
description="Pay cashu invoice",
extra={"tag": "cashu", "cashu_name": cashu.name},
)
except Exception as e:
@ -335,7 +335,7 @@ async def melt_coins(
status: PaymentStatus = await check_transaction_status(
cashu.wallet, invoice_obj.payment_hash
)
if status.paid == True:
if status.paid is True:
logger.debug(
f"Cashu: Payment successful, invalidating proofs for {invoice_obj.payment_hash}"
)
@ -349,7 +349,7 @@ async def melt_coins(
detail=f"Cashu: {str(e)}",
)
finally:
logger.debug(f"Cashu: Unset pending")
logger.debug("Cashu: Unset pending")
# delete proofs from pending list
await ledger._unset_proofs_pending(proofs)

View file

@ -21,5 +21,5 @@ def deezy_renderer():
return template_renderer(["lnbits/extensions/deezy/templates"])
from .views import * # noqa
from .views_api import * # noqa
from .views import * # noqa: F401,F403
from .views_api import * # noqa: F401,F403

View file

@ -1,4 +1,3 @@
from http import HTTPStatus
from typing import List, Optional
from . import db
@ -8,7 +7,7 @@ from .models import BtcToLnSwap, LnToBtcSwap, Token, UpdateLnToBtcSwap
async def get_ln_to_btc() -> List[LnToBtcSwap]:
rows = await db.fetchall(
f"SELECT * FROM deezy.ln_to_btc_swap ORDER BY created_at DESC",
"SELECT * FROM deezy.ln_to_btc_swap ORDER BY created_at DESC",
)
return [LnToBtcSwap(**row) for row in rows]
@ -17,7 +16,7 @@ async def get_ln_to_btc() -> List[LnToBtcSwap]:
async def get_btc_to_ln() -> List[BtcToLnSwap]:
rows = await db.fetchall(
f"SELECT * FROM deezy.btc_to_ln_swap ORDER BY created_at DESC",
"SELECT * FROM deezy.btc_to_ln_swap ORDER BY created_at DESC",
)
return [BtcToLnSwap(**row) for row in rows]
@ -26,7 +25,7 @@ async def get_btc_to_ln() -> List[BtcToLnSwap]:
async def get_token() -> Optional[Token]:
row = await db.fetchone(
f"SELECT * FROM deezy.token ORDER BY created_at DESC",
"SELECT * FROM deezy.token ORDER BY created_at DESC",
)
return Token(**row) if row else None

View file

@ -15,7 +15,7 @@ async def m001_initial(db):
"""
)
await db.execute(
f"""
"""
CREATE TABLE deezy.btc_to_ln_swap (
id TEXT PRIMARY KEY,
ln_address TEXT NOT NULL,
@ -28,7 +28,7 @@ async def m001_initial(db):
"""
)
await db.execute(
f"""
"""
CREATE TABLE deezy.token (
deezy_token TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP

View file

@ -1,7 +1,4 @@
from typing import Optional
from pydantic.main import BaseModel
from sqlalchemy.engine import base # type: ignore
class Token(BaseModel):

View file

@ -1,4 +1,4 @@
from fastapi import FastAPI, Request
from fastapi import Request
from fastapi.params import Depends
from fastapi.templating import Jinja2Templates
from starlette.responses import HTMLResponse

View file

@ -21,5 +21,5 @@ def discordbot_renderer():
return template_renderer(["lnbits/extensions/discordbot/templates"])
from .views import * # noqa
from .views_api import * # noqa
from .views import * # noqa: F401,F403
from .views_api import * # noqa: F401,F403

View file

@ -1,5 +1,4 @@
from sqlite3 import Row
from typing import Optional
from fastapi.param_functions import Query
from pydantic import BaseModel

View file

@ -26,8 +26,8 @@ def events_renderer():
from .tasks import wait_for_paid_invoices
from .views import * # noqa
from .views_api import * # noqa
from .views import * # noqa: F401,F403
from .views_api import * # noqa: F401,F403
def events_start():

View file

@ -50,12 +50,12 @@ async def api_event_create(
event = await get_event(event_id)
if not event:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail=f"Event does not exist."
status_code=HTTPStatus.NOT_FOUND, detail="Event does not exist."
)
if event.wallet != wallet.wallet.id:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN, detail=f"Not your event."
status_code=HTTPStatus.FORBIDDEN, detail="Not your event."
)
event = await update_event(event_id, **data.dict())
else:
@ -69,11 +69,11 @@ async def api_form_delete(event_id, wallet: WalletTypeInfo = Depends(get_key_typ
event = await get_event(event_id)
if not event:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail=f"Event does not exist."
status_code=HTTPStatus.NOT_FOUND, detail="Event does not exist."
)
if event.wallet != wallet.wallet.id:
raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail=f"Not your event.")
raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="Not your event.")
await delete_event(event_id)
await delete_event_tickets(event_id)
@ -101,7 +101,7 @@ async def api_ticket_make_ticket(event_id, name, email):
event = await get_event(event_id)
if not event:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail=f"Event does not exist."
status_code=HTTPStatus.NOT_FOUND, detail="Event does not exist."
)
try:
payment_hash, payment_request = await create_invoice(
@ -121,7 +121,7 @@ async def api_ticket_send_ticket(event_id, payment_hash, data: CreateTicket):
if not event:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail=f"Event could not be fetched.",
detail="Event could not be fetched.",
)
status = await api_payment(payment_hash)
@ -141,7 +141,7 @@ async def api_ticket_send_ticket(event_id, payment_hash, data: CreateTicket):
if not ticket:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail=f"Event could not be fetched.",
detail="Event could not be fetched.",
)
return {"paid": True, "ticket_id": ticket.id}
return {"paid": False}
@ -152,13 +152,11 @@ async def api_ticket_delete(ticket_id, wallet: WalletTypeInfo = Depends(get_key_
ticket = await get_ticket(ticket_id)
if not ticket:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail=f"Ticket does not exist."
status_code=HTTPStatus.NOT_FOUND, detail="Ticket does not exist."
)
if ticket.wallet != wallet.wallet.id:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN, detail=f"Not your ticket."
)
raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="Not your ticket.")
await delete_ticket(ticket_id)
return "", HTTPStatus.NO_CONTENT
@ -188,7 +186,7 @@ async def api_event_register_ticket(ticket_id):
status_code=HTTPStatus.FORBIDDEN, detail="Ticket not paid for."
)
if ticket.registered == True:
if ticket.registered is True:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN, detail="Ticket already registered"
)

View file

@ -25,8 +25,8 @@ def example_renderer():
from .tasks import wait_for_paid_invoices
from .views import *
from .views_api import *
from .views import * # noqa: F401,F403
from .views_api import * # noqa: F401,F403
def tpos_start():

View file

@ -1,5 +1,3 @@
import asyncio
from fastapi import APIRouter
from fastapi.staticfiles import StaticFiles
@ -24,5 +22,5 @@ def gerty_renderer():
return template_renderer(["lnbits/extensions/gerty/templates"])
from .views import * # noqa
from .views_api import * # noqa
from .views import * # noqa: F401,F403
from .views_api import * # noqa: F401,F403

View file

@ -8,7 +8,7 @@ from loguru import logger
from lnbits.helpers import urlsafe_short_hash
from . import db
from .models import Gerty, Mempool, MempoolEndpoint
from .models import Gerty, MempoolEndpoint
async def create_gerty(wallet_id: str, data: Gerty) -> Gerty:

View file

@ -13,7 +13,7 @@ from lnbits.settings import settings
from lnbits.utils.exchange_rates import satoshis_amount_as_fiat
from .crud import get_mempool_info
from .number_prefixer import *
from .number_prefixer import * # noqa: F403
def get_percent_difference(current, previous, precision=3):
@ -110,7 +110,9 @@ async def get_mining_dashboard(gerty):
)
text.append(
get_text_item_dict(
text="{0}hash".format(si_format(hashrateNow, 6, True, " ")),
text="{0}hash".format(
si_format(hashrateNow, 6, True, " ") # noqa: F405
),
font_size=20,
gerty_type=gerty.type,
)
@ -320,7 +322,9 @@ async def get_mining_stat(stat_slug: str, gerty):
text = []
if stat_slug == "mining_current_hash_rate":
stat = await api_get_mining_stat(stat_slug, gerty)
current = "{0}hash".format(si_format(stat["current"], 6, True, " "))
current = "{0}hash".format(
si_format(stat["current"], 6, True, " ") # noqa: F405
)
text.append(
get_text_item_dict(
text="Current Mining Hashrate", font_size=20, gerty_type=gerty.type

View file

@ -68,7 +68,7 @@ async def m006_add_gerty_model_col(db):
"""
await db.execute("ALTER TABLE gerty.mempool RENAME TO mempool_old")
await db.execute(
f"""
"""
CREATE TABLE gerty.mempool (
id TEXT PRIMARY KEY,
mempool_endpoint TEXT NOT NULL,

View file

@ -31,7 +31,7 @@ def si_formatter(value):
the value cannot be classified.
"""
classifier = si_classifier(value)
if classifier == None:
if classifier is None:
# Don't know how to classify this value
return None
@ -48,7 +48,7 @@ def si_format(value, precision=4, long_form=False, separator=""):
"""
scaled, short_suffix, long_suffix = si_formatter(value)
if scaled == None:
if scaled is None:
# Don't know how to format this value
return value

View file

@ -21,4 +21,4 @@ hivemind_static_files = [
}
]
from .views import * # noqa
from .views import * # noqa: F401,F403

View file

@ -32,5 +32,5 @@ def invoices_start():
loop.create_task(catch_everything_and_restart(wait_for_paid_invoices))
from .views import * # noqa
from .views_api import * # noqa
from .views import * # noqa: F401,F403
from .views_api import * # noqa: F401,F403

View file

@ -23,7 +23,7 @@ async def get_invoice(invoice_id: str) -> Optional[Invoice]:
async def get_invoice_items(invoice_id: str) -> List[InvoiceItem]:
rows = await db.fetchall(
f"SELECT * FROM invoices.invoice_items WHERE invoice_id = ?", (invoice_id,)
"SELECT * FROM invoices.invoice_items WHERE invoice_id = ?", (invoice_id,)
)
return [InvoiceItem.from_row(row) for row in rows]
@ -54,7 +54,7 @@ async def get_invoices(wallet_ids: Union[str, List[str]]) -> List[Invoice]:
async def get_invoice_payments(invoice_id: str) -> List[Payment]:
rows = await db.fetchall(
f"SELECT * FROM invoices.payments WHERE invoice_id = ?", (invoice_id,)
"SELECT * FROM invoices.payments WHERE invoice_id = ?", (invoice_id,)
)
return [Payment.from_row(row) for row in rows]

View file

@ -25,8 +25,8 @@ def jukebox_renderer():
from .tasks import wait_for_paid_invoices
from .views import * # noqa
from .views_api import * # noqa
from .views import * # noqa: F401,F403
from .views_api import * # noqa: F401,F403
def jukebox_start():

View file

@ -58,7 +58,7 @@ async def get_jukebox_by_user(user: str) -> Optional[Jukebox]:
async def get_jukeboxs(user: str) -> List[Jukebox]:
rows = await db.fetchall('SELECT * FROM jukebox.jukebox WHERE "user" = ?', (user,))
for row in rows:
if row.sp_playlists == None:
if row.sp_playlists is None:
await delete_jukebox(row.id)
rows = await db.fetchall('SELECT * FROM jukebox.jukebox WHERE "user" = ?', (user,))

View file

@ -123,7 +123,7 @@ async def api_get_jukebox_song(
if "items" not in r.json():
if r.status_code == 401:
token = await api_get_token(juke_id)
if token == False:
if token is False:
return False
elif retry:
raise HTTPException(
@ -205,7 +205,7 @@ async def api_get_jukebox_device_check(
return json.loads(rDevice.text)
elif rDevice.status_code == 401 or rDevice.status_code == 403:
token = await api_get_token(juke_id)
if token == False:
if token is False:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN, detail="No devices connected"
)
@ -309,7 +309,7 @@ async def api_get_jukebox_invoice_paid(
if rDevice.status_code == 200:
isPlaying = rDevice.json()["is_playing"]
if r.status_code == 204 or isPlaying == False:
if r.status_code == 204 or isPlaying is False:
async with httpx.AsyncClient() as client:
uri = ["spotify:track:" + song_id]
assert jukebox.sp_device
@ -324,7 +324,7 @@ async def api_get_jukebox_invoice_paid(
return jukebox_payment
elif r.status_code == 401 or r.status_code == 403:
token = await api_get_token(juke_id)
if token == False:
if token is False:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="Invoice not paid",
@ -359,7 +359,7 @@ async def api_get_jukebox_invoice_paid(
elif r.status_code == 401 or r.status_code == 403:
token = await api_get_token(juke_id)
if token == False:
if token is False:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="Invoice not paid",
@ -379,7 +379,7 @@ async def api_get_jukebox_invoice_paid(
)
elif r.status_code == 401 or r.status_code == 403:
token = await api_get_token(juke_id)
if token == False:
if token is False:
raise HTTPException(
status_code=HTTPStatus.OK, detail="Invoice not paid"
)
@ -433,7 +433,7 @@ async def api_get_jukebox_currently(
elif r.status_code == 401:
token = await api_get_token(juke_id)
if token == False:
if token is False:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN, detail="Invoice not paid"
)

View file

@ -24,10 +24,10 @@ def livestream_renderer():
return template_renderer(["lnbits/extensions/livestream/templates"])
from .lnurl import * # noqa
from .lnurl import * # noqa: F401,F403
from .tasks import wait_for_paid_invoices
from .views import * # noqa
from .views_api import * # noqa
from .views import * # noqa: F401,F403
from .views_api import * # noqa: F401,F403
def livestream_start():

View file

@ -1,9 +1,7 @@
import asyncio
import json
from loguru import logger
from lnbits.core import db as core_db
from lnbits.core.models import Payment
from lnbits.core.services import create_invoice, pay_invoice
from lnbits.helpers import get_current_extension_name

View file

@ -24,10 +24,10 @@ def lnaddress_renderer():
return template_renderer(["lnbits/extensions/lnaddress/templates"])
from .lnurl import * # noqa
from .lnurl import * # noqa: F401,F403
from .tasks import wait_for_paid_invoices
from .views import * # noqa
from .views_api import * # noqa
from .views import * # noqa: F401,F403
from .views_api import * # noqa: F401,F403
def lnaddress_start():

View file

@ -1,5 +1,3 @@
import json
import httpx
from .models import Domains

View file

@ -130,7 +130,7 @@ async def set_address_paid(payment_hash: str) -> Addresses:
address = await get_address(payment_hash)
assert address
if address.paid == False:
if address.paid is False:
await db.execute(
"""
UPDATE lnaddress.address

View file

@ -39,7 +39,7 @@ async def lnurl_response(username: str, domain: str, request: Request):
async def lnurl_callback(address_id, amount: int = Query(...)):
address = await get_address(address_id)
if not address:
return LnurlErrorResponse(reason=f"Address not found").dict()
return LnurlErrorResponse(reason="Address not found").dict()
amount_received = amount

View file

@ -21,7 +21,7 @@ def lndhub_renderer():
return template_renderer(["lnbits/extensions/lndhub/templates"])
from .decorators import * # noqa
from .utils import * # noqa
from .views import * # noqa
from .views_api import * # noqa
from .decorators import * # noqa: F401,F403
from .utils import * # noqa: F401,F403
from .views import * # noqa: F401,F403
from .views_api import * # noqa: F401,F403

View file

@ -228,4 +228,3 @@ async def lndhub_decodeinvoice(invoice: str = Query(None)):
@lndhub_ext.get("/ext/checkrouteinvoice")
async def lndhub_checkrouteinvoice():
"not implemented on canonical lndhub"
pass

View file

@ -24,10 +24,10 @@ def lnurldevice_renderer():
return template_renderer(["lnbits/extensions/lnurldevice/templates"])
from .lnurl import * # noqa
from .lnurl import * # noqa: F401,F403
from .tasks import wait_for_paid_invoices
from .views import * # noqa
from .views_api import * # noqa
from .views import * # noqa: F401,F403
from .views_api import * # noqa: F401,F403
def lnurldevice_start():

View file

@ -1,4 +1,4 @@
from typing import List, Optional, Union
from typing import List, Optional
import shortuuid

View file

@ -3,7 +3,6 @@ import hmac
from http import HTTPStatus
from io import BytesIO
import shortuuid
from embit import bech32, compact
from fastapi import HTTPException, Query, Request
@ -17,7 +16,6 @@ from .crud import (
create_lnurldevicepayment,
get_lnurldevice,
get_lnurldevicepayment,
get_lnurlpayload,
update_lnurldevicepayment,
)
@ -116,7 +114,7 @@ async def lnurl_v1_params(
if switch[0] == gpio and switch[1] == profit and switch[2] == amount:
check = True
if not check:
return {"status": "ERROR", "reason": f"Switch params wrong"}
return {"status": "ERROR", "reason": "Switch params wrong"}
lnurldevicepayment = await create_lnurldevicepayment(
deviceid=device.id,
@ -226,7 +224,7 @@ async def lnurl_callback(
)
if device.device == "atm":
if lnurldevicepayment.payload == lnurldevicepayment.payhash:
return {"status": "ERROR", "reason": f"Payment already claimed"}
return {"status": "ERROR", "reason": "Payment already claimed"}
if not pr:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN, detail="No payment request"
@ -240,7 +238,7 @@ async def lnurl_callback(
if lnurldevicepayment.payload != k1:
return {"status": "ERROR", "reason": "Bad K1"}
if lnurldevicepayment.payhash != "payment_hash":
return {"status": "ERROR", "reason": f"Payment already claimed"}
return {"status": "ERROR", "reason": "Payment already claimed"}
lnurldevicepayment_updated = await update_lnurldevicepayment(
lnurldevicepayment_id=paymentid, payhash=lnurldevicepayment.payload

View file

@ -29,7 +29,7 @@ async def m001_initial(db):
payhash TEXT,
payload TEXT NOT NULL,
pin INT,
sats {db.big_int},
sats {db.big_int},
timestamp TIMESTAMP NOT NULL DEFAULT {db.timestamp_now}
);
"""

View file

@ -24,10 +24,10 @@ def lnurlp_renderer():
return template_renderer(["lnbits/extensions/lnurlp/templates"])
from .lnurl import * # noqa
from .lnurl import * # noqa: F401,F403
from .tasks import wait_for_paid_invoices
from .views import * # noqa
from .views_api import * # noqa
from .views import * # noqa: F401,F403
from .views_api import * # noqa: F401,F403
def lnurlp_start():

View file

@ -10,7 +10,7 @@ async def create_pay_link(data: CreatePayLinkData, wallet_id: str) -> PayLink:
link_id = urlsafe_short_hash()[:6]
result = await db.execute(
f"""
"""
INSERT INTO lnurlp.pay_links (
id,
wallet,
@ -46,6 +46,7 @@ async def create_pay_link(data: CreatePayLinkData, wallet_id: str) -> PayLink:
data.fiat_base_multiplier,
),
)
assert result
link = await get_pay_link(link_id)
assert link, "Newly created link couldn't be retrieved"

View file

@ -1,5 +1,3 @@
import hashlib
import math
from http import HTTPStatus
from fastapi import Request

View file

@ -83,7 +83,7 @@ async def api_link_create_or_update(
detail="Min is greater than max.", status_code=HTTPStatus.BAD_REQUEST
)
if data.currency == None and (
if data.currency is None and (
round(data.min) != data.min or round(data.max) != data.max or data.min < 1
):
raise HTTPException(

View file

@ -34,8 +34,8 @@ def market_renderer():
from .tasks import wait_for_paid_invoices
from .views import * # noqa
from .views_api import * # noqa
from .views import * # noqa: F401,F403
from .views_api import * # noqa: F401,F403
def market_start():

View file

@ -1,18 +1,14 @@
from base64 import urlsafe_b64encode
from typing import List, Optional, Union
from uuid import uuid4
# from lnbits.db import open_ext_db
from lnbits.db import SQLITE
from lnbits.helpers import urlsafe_short_hash
from lnbits.settings import WALLET
from . import db
from .models import (
ChatMessage,
CreateChatMessage,
CreateMarket,
CreateMarketStalls,
Market,
MarketSettings,
OrderDetail,
@ -33,7 +29,7 @@ from .models import (
async def create_market_product(data: createProduct) -> Products:
product_id = urlsafe_short_hash()
await db.execute(
f"""
"""
INSERT INTO market.products (id, stall, product, categories, description, image, price, quantity)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""",
@ -95,7 +91,7 @@ async def delete_market_product(product_id: str) -> None:
async def create_market_zone(user, data: createZones) -> Zones:
zone_id = urlsafe_short_hash()
await db.execute(
f"""
"""
INSERT INTO market.zones (
id,
"user",
@ -143,7 +139,7 @@ async def delete_market_zone(zone_id: str) -> None:
async def create_market_stall(data: createStalls) -> Stalls:
stall_id = urlsafe_short_hash()
await db.execute(
f"""
"""
INSERT INTO market.stalls (
id,
wallet,
@ -257,7 +253,7 @@ async def create_market_order_details(order_id: str, data: List[createOrderDetai
async def get_market_order_details(order_id: str) -> List[OrderDetail]:
rows = await db.fetchall(
f"SELECT * FROM market.order_details WHERE order_id = ?", (order_id,)
"SELECT * FROM market.order_details WHERE order_id = ?", (order_id,)
)
return [OrderDetail(**row) for row in rows]

View file

@ -139,7 +139,7 @@ async def m001_initial(db):
id_conversation TEXT NOT NULL,
timestamp TIMESTAMP NOT NULL DEFAULT """
+ db.timestamp_now
+ """
+ """
);
"""
)

View file

@ -1,6 +1,5 @@
import json
from http import HTTPStatus
from typing import List
from fastapi import (
BackgroundTasks,
@ -11,7 +10,6 @@ from fastapi import (
WebSocketDisconnect,
)
from fastapi.templating import Jinja2Templates
from loguru import logger
from starlette.exceptions import HTTPException
from starlette.responses import HTMLResponse
@ -20,7 +18,6 @@ from lnbits.decorators import check_user_exists
from . import market_ext, market_renderer
from .crud import (
create_chat_message,
create_market_settings,
get_market_market,
get_market_market_stalls,
@ -30,10 +27,8 @@ from .crud import (
get_market_settings,
get_market_stall,
get_market_zone,
get_market_zones,
update_market_product_stock,
)
from .models import CreateChatMessage, SetSettings
from .models import SetSettings
from .notifier import Notifier
templates = Jinja2Templates(directory="templates")

View file

@ -1,9 +1,6 @@
from base64 import urlsafe_b64encode
from http import HTTPStatus
from typing import List, Union
from uuid import uuid4
from fastapi import Body, Depends, Query, Request
from fastapi import Depends, Query
from loguru import logger
from starlette.exceptions import HTTPException
@ -17,7 +14,7 @@ from lnbits.decorators import (
require_invoice_key,
)
from lnbits.helpers import urlsafe_short_hash
from lnbits.utils.exchange_rates import currencies, get_fiat_rate_satoshis
from lnbits.utils.exchange_rates import currencies
from . import db, market_ext
from .crud import (
@ -48,7 +45,6 @@ from .crud import (
get_market_settings,
get_market_stall,
get_market_stalls,
get_market_stalls_by_ids,
get_market_zone,
get_market_zones,
set_market_order_pubkey,
@ -60,12 +56,7 @@ from .crud import (
)
from .models import (
CreateMarket,
CreateMarketStalls,
Orders,
Products,
SetSettings,
Stalls,
Zones,
createOrder,
createProduct,
createStalls,
@ -312,7 +303,7 @@ async def api_market_order_create(data: createOrder):
payment_hash, payment_request = await create_invoice(
wallet_id=data.wallet,
amount=data.total,
memo=f"New order on Market",
memo="New order on Market",
extra={
"tag": "market",
"reference": ref,

View file

@ -12,4 +12,4 @@ def ngrok_renderer():
return template_renderer(["lnbits/extensions/ngrok/templates"])
from .views import *
from .views import * # noqa: F401,F403

View file

@ -32,5 +32,5 @@ def nostrnip5_start():
loop.create_task(catch_everything_and_restart(wait_for_paid_invoices))
from .views import * # noqa
from .views_api import * # noqa
from .views import * # noqa: F401,F403
from .views_api import * # noqa: F401,F403

View file

@ -58,7 +58,7 @@ async def get_address_by_local_part(
async def get_addresses(domain_id: str) -> List[Address]:
rows = await db.fetchall(
f"SELECT * FROM nostrnip5.addresses WHERE domain_id = ?", (domain_id,)
"SELECT * FROM nostrnip5.addresses WHERE domain_id = ?", (domain_id,)
)
return [Address.from_row(row) for row in rows]

View file

@ -24,7 +24,7 @@ async def m001_initial_invoices(db):
local_part TEXT NOT NULL,
pubkey TEXT NOT NULL,
active BOOLEAN NOT NULL DEFAULT false,
time TIMESTAMP NOT NULL DEFAULT {db.timestamp_now},

View file

@ -1,6 +1,4 @@
from enum import Enum
from sqlite3 import Row
from typing import List, Optional
from fastapi.param_functions import Query
from pydantic import BaseModel

View file

@ -1,4 +1,3 @@
from datetime import datetime
from http import HTTPStatus
from fastapi import Depends, Request

View file

@ -270,7 +270,7 @@ async def api_get_nostr_json(
if not local_part:
continue
if address.get("active") == False:
if address.get("active") is False:
continue
if name and name.lower() != local_part.lower():

View file

@ -21,6 +21,6 @@ def offlineshop_renderer():
return template_renderer(["lnbits/extensions/offlineshop/templates"])
from .lnurl import * # noqa
from .views import * # noqa
from .views_api import * # noqa
from .lnurl import * # noqa: F401,F403
from .views import * # noqa: F401,F403
from .views_api import * # noqa: F401,F403

View file

@ -1,19 +1,17 @@
import time
from datetime import datetime
from http import HTTPStatus
from typing import List
from fastapi import Depends, HTTPException, Query, Request
from starlette.responses import HTMLResponse
from lnbits.core.crud import get_standalone_payment
from lnbits.core.models import Payment, User
from lnbits.core.models import User
from lnbits.core.views.api import api_payment
from lnbits.decorators import check_user_exists
from . import offlineshop_ext, offlineshop_renderer
from .crud import get_item, get_shop
from .models import Item
@offlineshop_ext.get("/", response_class=HTMLResponse)

View file

@ -78,7 +78,7 @@ async def api_add_or_update_item(
)
if data.unit != "sat":
data.price = data.price * 100
if item_id == None:
if item_id is None:
await add_item(
shop.id,

View file

@ -21,5 +21,5 @@ def paywall_renderer():
return template_renderer(["lnbits/extensions/paywall/templates"])
from .views import * # noqa
from .views_api import * # noqa
from .views import * # noqa: F401,F403
from .views_api import * # noqa: F401,F403

View file

@ -21,6 +21,6 @@ def satsdice_renderer():
return template_renderer(["lnbits/extensions/satsdice/templates"])
from .lnurl import * # noqa
from .views import * # noqa
from .views_api import * # noqa
from .lnurl import * # noqa: F401,F403
from .views import * # noqa: F401,F403
from .views_api import * # noqa: F401,F403

View file

@ -8,7 +8,6 @@ from lnurl import Lnurl
from lnurl import encode as lnurl_encode
from lnurl.types import LnurlPayMetadata
from pydantic import BaseModel
from pydantic.main import BaseModel
class satsdiceLink(BaseModel):

View file

@ -26,8 +26,8 @@ def satspay_renderer():
from .tasks import wait_for_paid_invoices
from .views import * # noqa
from .views_api import * # noqa
from .views import * # noqa: F401,F403
from .views_api import * # noqa: F401,F403
def satspay_start():

View file

@ -18,7 +18,6 @@ def public_charge(charge: Charges):
"timestamp": charge.timestamp,
"time_elapsed": charge.time_elapsed,
"time_left": charge.time_left,
"paid": charge.paid,
"custom_css": charge.custom_css,
}

View file

@ -33,7 +33,7 @@ async def m002_add_charge_extra_data(db):
Add 'extra' column for storing various config about the charge (JSON format)
"""
await db.execute(
"""ALTER TABLE satspay.charges
"""ALTER TABLE satspay.charges
ADD COLUMN extra TEXT DEFAULT '{"mempool_endpoint": "https://mempool.space", "network": "Mainnet"}';
"""
)

View file

@ -77,7 +77,7 @@ class Charges(BaseModel):
return ChargeConfig(**charge_config)
def must_call_webhook(self):
return self.webhook and self.paid and self.config.webhook_success == False
return self.webhook and self.paid and self.config.webhook_success is False
class SatsPayThemes(BaseModel):

View file

@ -25,8 +25,8 @@ def scrub_renderer():
from .tasks import wait_for_paid_invoices
from .views import * # noqa
from .views_api import * # noqa
from .views import * # noqa: F401,F403
from .views_api import * # noqa: F401,F403
def scrub_start():

View file

@ -3,7 +3,7 @@ async def m001_initial(db):
Initial scrub table.
"""
await db.execute(
f"""
"""
CREATE TABLE scrub.scrub_links (
id TEXT PRIMARY KEY,
wallet TEXT NOT NULL,

View file

@ -25,8 +25,8 @@ def smtp_renderer():
from .tasks import wait_for_paid_invoices
from .views import * # noqa
from .views_api import * # noqa
from .views import * # noqa: F401,F403
from .views_api import * # noqa: F401,F403
def smtp_start():

View file

@ -121,9 +121,9 @@ async def create_email(wallet: str, data: CreateEmail, payment_hash: str = "") -
async def set_email_paid(payment_hash: str) -> bool:
email = await get_email_by_payment_hash(payment_hash)
if email and email.paid == False:
if email and email.paid is False:
await db.execute(
f"UPDATE smtp.email SET paid = true WHERE payment_hash = ?", (payment_hash,)
"UPDATE smtp.email SET paid = true WHERE payment_hash = ?", (payment_hash,)
)
return True
return False
@ -131,13 +131,13 @@ async def set_email_paid(payment_hash: str) -> bool:
async def get_email_by_payment_hash(payment_hash: str) -> Optional[Email]:
row = await db.fetchone(
f"SELECT * FROM smtp.email WHERE payment_hash = ?", (payment_hash,)
"SELECT * FROM smtp.email WHERE payment_hash = ?", (payment_hash,)
)
return Email(**row) if row else None
async def get_email(id: str) -> Optional[Email]:
row = await db.fetchone(f"SELECT * FROM smtp.email WHERE id = ?", (id,))
row = await db.fetchone("SELECT * FROM smtp.email WHERE id = ?", (id,))
return Email(**row) if row else None

View file

@ -36,4 +36,4 @@ async def m001_initial(db):
async def m002_add_payment_hash(db):
await db.execute(f"ALTER TABLE smtp.email ADD COLUMN payment_hash TEXT;")
await db.execute("ALTER TABLE smtp.email ADD COLUMN payment_hash TEXT;")

View file

@ -26,8 +26,8 @@ def splitpayments_renderer():
from .tasks import wait_for_paid_invoices
from .views import * # noqa
from .views_api import * # noqa
from .views import * # noqa: F401,F403
from .views_api import * # noqa: F401,F403
def splitpayments_start():

View file

@ -21,5 +21,5 @@ def streamalerts_renderer():
return template_renderer(["lnbits/extensions/streamalerts/templates"])
from .views import * # noqa
from .views_api import * # noqa
from .views import * # noqa: F401,F403
from .views_api import * # noqa: F401,F403

Some files were not shown because too many files have changed in this diff Show more