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

feat: code quality #93

Merged
merged 3 commits into from
Aug 2, 2024
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: 10 additions & 0 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
name: lint
on:
push:
branches:
- main
pull_request:

jobs:
lint:
uses: lnbits/lnbits/.github/workflows/lint.yml@dev
15 changes: 7 additions & 8 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
on:
push:
tags:
- "v[0-9]+.[0-9]+.[0-9]+"
- 'v[0-9]+.[0-9]+.[0-9]+'

jobs:

release:
runs-on: ubuntu-latest
steps:
Expand Down Expand Up @@ -34,12 +33,12 @@ jobs:
- name: Create pull request in extensions repo
env:
GH_TOKEN: ${{ secrets.EXT_GITHUB }}
repo_name: "${{ github.event.repository.name }}"
tag: "${{ github.ref_name }}"
branch: "update-${{ github.event.repository.name }}-${{ github.ref_name }}"
title: "[UPDATE] ${{ github.event.repository.name }} to ${{ github.ref_name }}"
body: "https://github.com/lnbits/${{ github.event.repository.name }}/releases/${{ github.ref_name }}"
archive: "https://github.com/lnbits/${{ github.event.repository.name }}/archive/refs/tags/${{ github.ref_name }}.zip"
repo_name: '${{ github.event.repository.name }}'
tag: '${{ github.ref_name }}'
branch: 'update-${{ github.event.repository.name }}-${{ github.ref_name }}'
title: '[UPDATE] ${{ github.event.repository.name }} to ${{ github.ref_name }}'
body: 'https://github.com/lnbits/${{ github.event.repository.name }}/releases/${{ github.ref_name }}'
archive: 'https://github.com/lnbits/${{ github.event.repository.name }}/archive/refs/tags/${{ github.ref_name }}.zip'
run: |
cd lnbits-extensions
git checkout -b $branch
Expand Down
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
__pycache__
node_modules
.mypy_cache
.venv
12 changes: 12 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"semi": false,
"arrowParens": "avoid",
"insertPragma": false,
"printWidth": 80,
"proseWrap": "preserve",
"singleQuote": true,
"trailingComma": "none",
"useTabs": false,
"bracketSameLine": false,
"bracketSpacing": false
}
47 changes: 47 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
all: format check

format: prettier black ruff

check: mypy pyright checkblack checkruff checkprettier

prettier:
poetry run ./node_modules/.bin/prettier --write .
pyright:
poetry run ./node_modules/.bin/pyright

mypy:
poetry run mypy .

black:
poetry run black .

ruff:
poetry run ruff check . --fix

checkruff:
poetry run ruff check .

checkprettier:
poetry run ./node_modules/.bin/prettier --check .

checkblack:
poetry run black --check .

checkeditorconfig:
editorconfig-checker

test:
PYTHONUNBUFFERED=1 \
DEBUG=true \
poetry run pytest
install-pre-commit-hook:
@echo "Installing pre-commit hook to git"
@echo "Uninstall the hook with poetry run pre-commit uninstall"
poetry run pre-commit install

pre-commit:
poetry run pre-commit run --all-files


checkbundle:
@echo "skipping checkbundle"
69 changes: 24 additions & 45 deletions __init__.py
Original file line number Diff line number Diff line change
@@ -1,41 +1,18 @@
import asyncio

from fastapi import APIRouter, Request, Response
from fastapi.routing import APIRoute

from lnbits.db import Database
from lnbits.helpers import template_renderer
from lnbits.tasks import create_permanent_unique_task
from typing import Callable
from fastapi.responses import JSONResponse

db = Database("ext_tpos")


class LNURLErrorResponseHandler(APIRoute):
def get_route_handler(self) -> Callable:
original_route_handler = super().get_route_handler()

async def custom_route_handler(request: Request) -> Response:
try:
response = await original_route_handler(request)
except HTTPException as exc:
logger.debug(f"HTTPException: {exc}")
response = JSONResponse(
status_code=exc.status_code,
content={"status": "ERROR", "reason": f"{exc.detail}"},
)
except Exception as exc:
raise exc

return response

return custom_route_handler
from fastapi import APIRouter
from loguru import logger

from .crud import db
from .tasks import wait_for_paid_invoices
from .views import tpos_generic_router
from .views_api import tpos_api_router
from .views_lnurl import tpos_lnurl_router

tpos_ext: APIRouter = APIRouter(
prefix="/tpos", tags=["TPoS"], route_class=LNURLErrorResponseHandler
)
tpos_ext = APIRouter(prefix="/tpos", tags=["TPoS"])
tpos_ext.include_router(tpos_generic_router)
tpos_ext.include_router(tpos_lnurl_router)
tpos_ext.include_router(tpos_api_router)

tpos_static_files = [
{
Expand All @@ -44,26 +21,28 @@ async def custom_route_handler(request: Request) -> Response:
}
]


def tpos_renderer():
return template_renderer(["tpos/templates"])


from .lnurl import * # noqa: F401,F403
from .tasks import wait_for_paid_invoices
from .views import * # noqa
from .views_api import * # noqa


scheduled_tasks: list[asyncio.Task] = []


def tpos_stop():
for task in scheduled_tasks:
try:
task.cancel()
except Exception as ex:
logger.warning(ex)


def tpos_start():
from lnbits.tasks import create_permanent_unique_task
motorina0 marked this conversation as resolved.
Show resolved Hide resolved

task = create_permanent_unique_task("ext_tpos", wait_for_paid_invoices)
scheduled_tasks.append(task)


__all__ = [
motorina0 marked this conversation as resolved.
Show resolved Hide resolved
"db",
"tpos_ext",
"tpos_static_files",
"tpos_start",
"tpos_stop",
]
27 changes: 19 additions & 8 deletions crud.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
from typing import List, Optional, Union

from loguru import logger

from lnbits.db import Database
from lnbits.helpers import urlsafe_short_hash
from loguru import logger

from . import db
from .models import CreateTposData, LNURLCharge, TPoS, TPoSClean

db = Database("ext_tpos")


async def get_current_timestamp():
# Get current DB timestamp
timestamp_query = f"SELECT {db.timestamp_now}"
if db.type in {"POSTGRES", "COCKROACH"}:
timestamp_query = f"SELECT EXTRACT(EPOCH FROM {db.timestamp_now})"
elif db.type == "SQLITE":
timestamp_query = f"SELECT {db.timestamp_now}"
current_timestamp = (await db.fetchone(timestamp_query))[0]
return int(current_timestamp)

Expand All @@ -22,7 +22,12 @@ async def create_tpos(wallet_id: str, data: CreateTposData) -> TPoS:
tpos_id = urlsafe_short_hash()
await db.execute(
"""
INSERT INTO tpos.pos (id, wallet, name, currency, tip_options, tip_wallet, withdrawlimit, withdrawpin, withdrawamt, withdrawtime, withdrawbtwn, withdrawtimeopt, withdrawpindisabled, withdrawpremium)
INSERT INTO tpos.pos
(
id, wallet, name, currency, tip_options, tip_wallet, withdrawlimit,
withdrawpin, withdrawamt, withdrawtime, withdrawbtwn, withdrawtimeopt,
withdrawpindisabled, withdrawpremium
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
Expand Down Expand Up @@ -62,7 +67,10 @@ async def start_lnurlcharge(tpos_id: str):
)
assert (
now - tpos.withdrawtime > withdraw_time_seconds
), f"Last withdraw was made too recently, please try again in {int(withdraw_time_seconds - (now - tpos.withdrawtime))} secs"
), f"""
Last withdraw was made too recently, please try again in
{int(withdraw_time_seconds - (now - tpos.withdrawtime))} secs
"""

token = urlsafe_short_hash()
await db.execute(
Expand Down Expand Up @@ -120,7 +128,10 @@ async def update_tpos_withdraw(data: TPoS, tpos_id: str) -> TPoS:
# Check if the time between withdrawals is less than withdrawbtwn
assert (
time_elapsed > withdraw_time_seconds
), f"Last withdraw was made too recently, please try again in {int(withdraw_time_seconds - (time_elapsed))} secs"
), f"""
Last withdraw was made too recently, please try again in
{int(withdraw_time_seconds - (time_elapsed))} secs"
"""

# Update the withdraw time in the database
await db.execute(
Expand Down
12 changes: 6 additions & 6 deletions description.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ A powerful air-gapped software Point of Sale can be shared via a QR code.

Its functions include:

* Generating invoices
* Denomination in sats and ANY fiat currency
* Boltcard support
* Adding items for a checkout experience
* An ATM feature that allows you to sell Bitcoin back to your customers for a profit!
- Generating invoices
- Denomination in sats and ANY fiat currency
- Boltcard support
- Adding items for a checkout experience
- An ATM feature that allows you to sell Bitcoin back to your customers for a profit!

A favorite onboarding solution for merchants who want to accumulate Bitcoin, can ben achieved by also using the Boltz extension for automatic trustless swaps out to on-chain.
A favorite onboarding solution for merchants who want to accumulate Bitcoin, can ben achieved by also using the Boltz extension for automatic trustless swaps out to on-chain.
5 changes: 3 additions & 2 deletions migrations.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,11 @@ async def m008_atm_time_option_and_pin_toggle(db):
Add a time mins/sec and pin toggle
"""
await db.execute(
"ALTER TABLE tpos.pos ADD COLUMN withdrawtimeopt TEXT DEFAULT 'mins';"
"ALTER TABLE tpos.pos " "ADD COLUMN withdrawtimeopt TEXT DEFAULT 'mins'"
)
await db.execute(
"ALTER TABLE tpos.pos ADD COLUMN withdrawpindisabled BOOL NOT NULL DEFAULT false;"
"ALTER TABLE tpos.pos "
"ADD COLUMN withdrawpindisabled BOOL NOT NULL DEFAULT false"
)


Expand Down
15 changes: 1 addition & 14 deletions models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@
from typing import List, Optional

from fastapi import Request
from lnurl import Lnurl, LnurlWithdrawResponse
from lnurl import Lnurl
from lnurl import encode as lnurl_encode
from lnurl.types import ClearnetUrl, MilliSatoshi
from pydantic import BaseModel, Field, validator


Expand Down Expand Up @@ -77,18 +76,6 @@ def lnurl(self, req: Request) -> Lnurl:
)
return lnurl_encode(url)

def lnurl_response(self, req: Request) -> LnurlWithdrawResponse:
motorina0 marked this conversation as resolved.
Show resolved Hide resolved
url = str(req.url_for("tpos.tposlnurlcharge.callback"))
assert self.amount
amount = int(self.amount)
return LnurlWithdrawResponse(
callback=ClearnetUrl(url, scheme="https"),
k1=self.k1,
minWithdrawable=MilliSatoshi(amount * 1000),
maxWithdrawable=MilliSatoshi(amount * 1000),
defaultDescription=self.title,
)


class HashCheck(BaseModel):
hash: bool
Expand Down
59 changes: 59 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading