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

79 lines
2.3 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:
2023-01-05 11:05:03 +00:00
if not payment.extra:
return
if payment.extra.get("tag") == "splitpayments" or payment.extra.get("splitted"):
2022-10-21 17:35:58 +02:00
# already a splitted payment, ignore
2021-10-18 12:34:45 +01:00
return
targets = await get_targets(payment.wallet_id)
2022-12-13 23:41:40 +00:00
logger.debug(targets)
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
logger.debug(f"performing split payments to {len(targets)} targets")
amount_to_split = payment.amount
2023-01-05 14:37:31 +00:00
if payment.extra.get("amount"):
2023-01-06 09:46:43 +00:00
amount_to_split = (payment.extra.get("amount") or 0) * 1000
2022-10-21 17:35:58 +02:00
for target in targets:
2023-01-05 12:20:31 +00:00
if target.percent > 0:
tagged = target.tag in payment.extra
2023-01-06 10:27:03 +00:00
amount = int(amount_to_split * target.percent / 100) # msats
2023-01-05 12:20:31 +00:00
memo = (
f"split payment: {target.percent}% for {target.alias or target.wallet}"
)
if tagged:
memo = f"Pushed tagged payment to {target.alias}"
2023-01-06 10:27:03 +00:00
amount = int(amount_to_split)
2023-01-05 12:20:31 +00:00
payment_hash, payment_request = await create_invoice(
wallet_id=target.wallet,
amount=int(amount / 1000), # sats
internal=True,
memo=memo,
)
logger.debug(f"created split invoice: {payment_hash}")
extra = {**payment.extra, "splitted": True}
checking_id = await pay_invoice(
payment_request=payment_request,
wallet_id=payment.wallet_id,
2023-01-05 14:37:31 +00:00
extra=extra,
2023-01-05 12:20:31 +00:00
)
logger.debug(f"paid split invoice: {checking_id}")
2022-12-14 00:06:36 +00:00
2022-12-13 23:41:40 +00:00
logger.debug(f"performing split to {len(targets)} targets")