be extra safe when failing a payment if pay_invoice throws on sparko.

This commit is contained in:
fiatjaf 2021-03-24 01:51:15 -03:00
parent aabe3364f4
commit a787d60d93
3 changed files with 32 additions and 5 deletions

View file

@ -140,11 +140,12 @@ async def pay_invoice(
else:
# actually pay the external invoice
payment: PaymentResponse = await WALLET.pay_invoice(payment_request)
if payment.ok and payment.checking_id:
if payment.checking_id:
await create_payment(
checking_id=payment.checking_id,
fee=payment.fee_msat,
preimage=payment.preimage,
pending=payment.ok == None,
**payment_kwargs,
)
await delete_payment(temp_id)

View file

@ -15,9 +15,8 @@ class InvoiceResponse(NamedTuple):
class PaymentResponse(NamedTuple):
ok: Optional[
bool
] = None # when ok is None it means we don't know if this succeeded
# when ok is None it means we don't know if this succeeded
ok: Optional[bool] = None
checking_id: Optional[str] = None # payment_hash, rcp_id
fee_msat: int = 0
preimage: Optional[str] = None

View file

@ -109,7 +109,34 @@ class SparkWallet(Wallet):
try:
r = await self.pay(bolt11)
except (SparkError, UnknownError) as exc:
return PaymentResponse(False, None, 0, None, str(exc))
listpays = await self.listpays(bolt11)
if listpays:
pays = listpays["pays"]
if len(pays) == 0:
return PaymentResponse(False, None, 0, None, str(exc))
pay = pays[0]
payment_hash = pay["payment_hash"]
if len(pays) > 1:
raise Exception(
f"listpays({payment_hash}) returned an unexpected response: {listpays}"
)
if pay["status"] == "failed":
return PaymentResponse(False, None, 0, None, str(exc))
elif pay["status"] == "pending":
return PaymentResponse(None, listpays["pays"], 0, None, None)
elif pay["status"] == "complete":
r = pay
r["payment_preimage"] = pay["preimage"]
r["msatoshi"] = int(pay["amount_msat"][0:-4])
r["msatoshi_sent"] = int(pay["amount_sent_msat"][0:-4])
# this may result in an error if it was paid previously
# our database won't allow the same payment_hash to be added twice
# this is good
pass
fee_msat = r["msatoshi_sent"] - r["msatoshi"]
preimage = r["payment_preimage"]