lnbits-legend/lnbits/extensions/splitpayments/tasks.py

63 lines
1.9 KiB
Python
Raw Normal View History

import asyncio
2021-10-18 12:34:45 +01:00
from loguru import logger
from lnbits.core.models import Payment
2022-10-21 17:35:58 +02:00
from lnbits.core.services import create_invoice, pay_invoice
from lnbits.helpers import get_current_extension_name
from lnbits.tasks import register_invoice_listener
2021-10-18 12:34:45 +01:00
from .crud import get_targets
async def wait_for_paid_invoices():
invoice_queue = asyncio.Queue()
register_invoice_listener(invoice_queue, get_current_extension_name())
2021-10-18 12:34:45 +01:00
while True:
payment = await invoice_queue.get()
await on_invoice_paid(payment)
async def on_invoice_paid(payment: Payment) -> None:
2022-10-21 17:35:58 +02:00
if payment.extra.get("tag") == "splitpayments":
# already a splitted payment, ignore
2021-10-18 12:34:45 +01:00
return
targets = await get_targets(payment.wallet_id)
if not targets:
return
2022-10-21 17:35:58 +02:00
total_percent = sum([target.percent for target in targets])
2021-10-18 12:34:45 +01:00
2022-10-21 17:35:58 +02:00
if total_percent > 100:
logger.error("splitpayment failure: total percent adds up to more than 100%")
2021-10-18 12:34:45 +01:00
return
2022-10-21 17:35:58 +02:00
logger.debug(f"performing split payments to {len(targets)} targets")
for target in targets:
2022-12-13 20:01:05 +00:00
if target.tag and payment.extra.get("tag") == target.tag:
amount = int(payment.amount)
elif target.percent:
amount = int(payment.amount * target.percent / 100) # msats
else:
return
2022-10-21 17:35:58 +02:00
payment_hash, payment_request = await create_invoice(
wallet_id=target.wallet,
amount=int(amount / 1000), # sats
internal=True,
memo=f"split payment: {target.percent}% for {target.alias or target.wallet}",
2021-10-18 12:34:45 +01:00
extra={"tag": "splitpayments"},
)
2022-10-21 17:35:58 +02:00
logger.debug(f"created split invoice: {payment_hash}")
2021-10-18 12:34:45 +01:00
2022-10-21 17:35:58 +02:00
checking_id = await pay_invoice(
payment_request=payment_request,
wallet_id=payment.wallet_id,
extra={"tag": "splitpayments"},
)
logger.debug(f"paid split invoice: {checking_id}")