lnbits-legend/lnbits/extensions/boltz/crud.py

226 lines
6 KiB
Python
Raw Normal View History

Boltz.exchange Extension (#922) * initial commit and still draft, ready for review * forgot to uncomment this line * fee estimation and blockheight * resolve conversation with michael, to use mempool websockets instead of boltz status event * Update lnbits/extensions/boltz/boltz.py Co-authored-by: michael1011 <me@michael1011.at> * add status to swaps, add sorting and data into listing * add swap status checks, change urls to docker test setup, dynamic minimum and maximum limits * fix docker hosts for development * add api endpoints to _api_docs * add wallet name and id, to list and status information * fix status_update for reverse_swaps * chore: format with black * more blackformatting and refactoring create_swap() * fix variable bug * check if swap is already refunded * use create_task instead of ensure_future * add mempool and boltz urls depending on DEBUG .env * raise exception in mempool fails * fix onchain txs, sending funds to wrong address and add a refund address for normal swaps beforehand * add status to swaps, add sorting and data into listing * add swap status checks, change urls to docker test setup, dynamic minimum and maximum limits * add wallet name and id, to list and status information * fix status_update for reverse_swaps * chore: format with black * use create_task instead of ensure_future * add mempool and boltz urls depending on DEBUG .env * fix onchain txs, sending funds to wrong address and add a refund address for normal swaps beforehand * black formatting * add some logging with loguru, and remove function duplication * cleanup readme * updates/suggestions from calle Co-authored-by: calle <93376500+callebtc@users.noreply.github.com> * remove unused comments * Update API Endpoints Co-authored-by: calle <93376500+callebtc@users.noreply.github.com> * un-factor get_boltz_pairs * added a explaination for the onchain tx * remove unused template file * rename api endpoints * fix isort and prettier * more verbose logging!! * add boltz to mock_data.zip * new mockdata * remove comment * better readme * fix mempool urls * change /refund /check /status to post requests * first step in tests2 * add first tests * change refund,check,status to post requests * next try on tests * overall code improvements * just testing tests * throw http exceptions in views_api * require admincheck for refund,check,status and added fastapi documentation for those * added more tests * black * many code improvements * adding tests * temp fix test * fix race condition when pay_invoice fails * test are working * add boltz env variables * add startup check, bugfixes, improvements * improve on status checking * remove check_invoice_status * more fixes and tests * testing testing testing * make tests run again inside regtest * fix bad error :O * fix postgres boolean bug and add swap test * Update README.md Update README.md Update README.md Update README.md * some mypy * blacked * the missing commit? * fix api_docs readme link * better refunding error catching fix * check swaps now also shows pending reverse swap, ui improvements, tooltips * add backend check for boltz limits fixup * many improvements, startup check for swaps working, reverse needs more testing * little last fixes * remove unused logic * fastapi documentation fixup * formatting and remove unused tests * fix test * fix swapstatus model * Update lnbits/extensions/boltz/tasks.py Co-authored-by: calle <93376500+callebtc@users.noreply.github.com> * Update lnbits/extensions/boltz/views_api.py Co-authored-by: calle <93376500+callebtc@users.noreply.github.com> * balance check msg, format * fix mypy data override * fix swapstatus, remove can refund column * Update lnbits/extensions/boltz/README.md Co-authored-by: michael1011 <me@michael1011.at> * empty lines * fix error message when swap is not found * remove preimage_hash from database * fix api_docs html fix api_docs html * catch boltz network exceptions better * formatting * check for timeout on swap at get request Co-authored-by: michael1011 <me@michael1011.at> Co-authored-by: fusion44 <some.fusion@gmail.com> Co-authored-by: calle <93376500+callebtc@users.noreply.github.com>
2022-08-30 12:51:17 +02:00
from http import HTTPStatus
from typing import List, Optional, Union
from loguru import logger
from starlette.exceptions import HTTPException
from . import db
from .models import (
CreateReverseSubmarineSwap,
CreateSubmarineSwap,
ReverseSubmarineSwap,
SubmarineSwap,
)
"""
Submarine Swaps
"""
async def get_submarine_swaps(wallet_ids: Union[str, List[str]]) -> List[SubmarineSwap]:
if isinstance(wallet_ids, str):
wallet_ids = [wallet_ids]
q = ",".join(["?"] * len(wallet_ids))
rows = await db.fetchall(
f"SELECT * FROM boltz.submarineswap WHERE wallet IN ({q}) order by time DESC",
(*wallet_ids,),
)
return [SubmarineSwap(**row) for row in rows]
async def get_pending_submarine_swaps(
wallet_ids: Union[str, List[str]]
) -> List[SubmarineSwap]:
if isinstance(wallet_ids, str):
wallet_ids = [wallet_ids]
q = ",".join(["?"] * len(wallet_ids))
rows = await db.fetchall(
f"SELECT * FROM boltz.submarineswap WHERE wallet IN ({q}) and status='pending' order by time DESC",
(*wallet_ids,),
)
return [SubmarineSwap(**row) for row in rows]
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",
)
return [SubmarineSwap(**row) for row in rows]
async def get_submarine_swap(swap_id) -> SubmarineSwap:
row = await db.fetchone(
"SELECT * FROM boltz.submarineswap WHERE id = ?", (swap_id,)
)
return SubmarineSwap(**row) if row else None
async def create_submarine_swap(swap: SubmarineSwap) -> Optional[SubmarineSwap]:
await db.execute(
"""
INSERT INTO boltz.submarineswap (
id,
wallet,
payment_hash,
status,
boltz_id,
refund_privkey,
refund_address,
expected_amount,
timeout_block_height,
address,
bip21,
redeem_script,
amount
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
swap.id,
swap.wallet,
swap.payment_hash,
swap.status,
swap.boltz_id,
swap.refund_privkey,
swap.refund_address,
swap.expected_amount,
swap.timeout_block_height,
swap.address,
swap.bip21,
swap.redeem_script,
swap.amount,
),
)
return await get_submarine_swap(swap.id)
async def delete_submarine_swap(swap_id):
await db.execute("DELETE FROM boltz.submarineswap WHERE id = ?", (swap_id,))
async def get_reverse_submarine_swaps(
wallet_ids: Union[str, List[str]]
) -> List[ReverseSubmarineSwap]:
if isinstance(wallet_ids, str):
wallet_ids = [wallet_ids]
q = ",".join(["?"] * len(wallet_ids))
rows = await db.fetchall(
f"SELECT * FROM boltz.reverse_submarineswap WHERE wallet IN ({q}) order by time DESC",
(*wallet_ids,),
)
return [ReverseSubmarineSwap(**row) for row in rows]
async def get_pending_reverse_submarine_swaps(
wallet_ids: Union[str, List[str]]
) -> List[ReverseSubmarineSwap]:
if isinstance(wallet_ids, str):
wallet_ids = [wallet_ids]
q = ",".join(["?"] * len(wallet_ids))
rows = await db.fetchall(
f"SELECT * FROM boltz.reverse_submarineswap WHERE wallet IN ({q}) and status='pending' order by time DESC",
(*wallet_ids,),
)
return [ReverseSubmarineSwap(**row) for row in rows]
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"
)
return [ReverseSubmarineSwap(**row) for row in rows]
async def get_reverse_submarine_swap(swap_id) -> SubmarineSwap:
row = await db.fetchone(
"SELECT * FROM boltz.reverse_submarineswap WHERE id = ?", (swap_id,)
)
return ReverseSubmarineSwap(**row) if row else None
async def create_reverse_submarine_swap(
swap: ReverseSubmarineSwap,
) -> Optional[ReverseSubmarineSwap]:
await db.execute(
"""
INSERT INTO boltz.reverse_submarineswap (
id,
wallet,
status,
boltz_id,
instant_settlement,
preimage,
claim_privkey,
lockup_address,
invoice,
onchain_amount,
onchain_address,
timeout_block_height,
redeem_script,
amount
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
swap.id,
swap.wallet,
swap.status,
swap.boltz_id,
swap.instant_settlement,
swap.preimage,
swap.claim_privkey,
swap.lockup_address,
swap.invoice,
swap.onchain_amount,
swap.onchain_address,
swap.timeout_block_height,
swap.redeem_script,
swap.amount,
),
)
return await get_reverse_submarine_swap(swap.id)
async def update_swap_status(swap_id: str, status: str):
reverse = ""
swap = await get_submarine_swap(swap_id)
if swap is None:
swap = await get_reverse_submarine_swap(swap_id)
if swap is None:
return None
if type(swap) == SubmarineSwap:
await db.execute(
"UPDATE boltz.submarineswap SET status='"
+ status
+ "' WHERE id='"
+ swap.id
+ "'"
)
if type(swap) == ReverseSubmarineSwap:
reverse = "reverse"
await db.execute(
"UPDATE boltz.reverse_submarineswap SET status='"
+ status
+ "' WHERE id='"
+ swap.id
+ "'"
)
message = f"Boltz - {reverse} swap status change: {status}. boltz_id: {swap.boltz_id}, wallet: {swap.wallet}"
logger.info(message)
return swap