2021-11-25 18:52:16 +00:00
|
|
|
import asyncio
|
2021-10-18 12:34:45 +01:00
|
|
|
|
2022-07-07 14:30:16 +02:00
|
|
|
from loguru import logger
|
|
|
|
|
2021-11-25 18:52:16 +00:00
|
|
|
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()
|
2022-10-04 09:51:47 +02:00
|
|
|
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)
|
2022-10-06 15:21:09 +01:00
|
|
|
|
|
|
|
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:
|
|
|
|
amount = int(payment.amount * target.percent / 100) # msats
|
|
|
|
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}")
|