watchonly working, satspay broken

This commit is contained in:
Ben Arc
2021-03-31 23:49:36 +01:00
parent b05b8c0115
commit 0db516b6e0
9 changed files with 237 additions and 89 deletions
+55 -25
View File
@@ -8,34 +8,56 @@ from lnbits.helpers import urlsafe_short_hash
from quart import jsonify
import httpx
from lnbits.core.services import create_invoice, check_invoice_status
from ..watchonly.crud import get_watch_wallet, get_derive_address
###############CHARGES##########################
async def create_charge(walletid: str, user: str, title: Optional[str] = None, time: Optional[int] = None, amount: Optional[int] = None) -> Charges:
wallet = await get_watch_wallet(walletid)
address = await get_derive_address(walletid, wallet[4] + 1)
async def create_charge(user: str, description: Optional[str] = None, onchainwallet: Optional[str] = None, lnbitswallet: Optional[str] = None, webhook: Optional[str] = None, time: Optional[int] = None, amount: Optional[int] = None) -> Charges:
charge_id = urlsafe_short_hash()
if onchainwallet:
wallet = await get_watch_wallet(onchainwallet)
onchainaddress = await get_derive_address(onchainwallet, wallet[4] + 1)
else:
onchainaddress = None
if lnbitswallet:
payment_hash, payment_request = await create_invoice(
wallet_id=lnbitswallet,
amount=amount,
memo=charge_id)
else:
payment_hash = None
payment_request = None
await db.execute(
"""
INSERT INTO charges (
id,
user,
title,
wallet,
address,
time_to_pay,
description,
onchainwallet,
onchainaddress,
lnbitswallet,
payment_request,
payment_hash,
webhook,
time,
amount,
balance
balance,
paid
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(charge_id, user, title, walletid, address, time, amount, 0),
(charge_id, user, description, onchainwallet, onchainaddress, lnbitswallet, payment_request, payment_hash, webhook, time, amount, 0, False),
)
return await get_charge(charge_id)
async def update_charge(charge_id: str, **kwargs) -> Optional[Charges]:
q = ", ".join([f"{field[0]} = ?" for field in kwargs.items()])
await db.execute(f"UPDATE charges SET {q} WHERE id = ?", (*kwargs.values(), wallet_id))
row = await db.fetchone("SELECT * FROM charges WHERE id = ?", (wallet_id,))
return Charges.from_row(row) if row else None
async def get_charge(charge_id: str) -> Charges:
row = await db.fetchone("SELECT * FROM charges WHERE id = ?", (charge_id,))
@@ -45,7 +67,7 @@ async def get_charge(charge_id: str) -> Charges:
async def get_charges(user: str) -> List[Charges]:
rows = await db.fetchall("SELECT * FROM charges WHERE user = ?", (user,))
for row in rows:
await check_address_balance(row.address)
await check_address_balance(row.id)
rows = await db.fetchall("SELECT * FROM charges WHERE user = ?", (user,))
return [charges.from_row(row) for row in rows]
@@ -53,15 +75,23 @@ async def get_charges(user: str) -> List[Charges]:
async def delete_charge(charge_id: str) -> None:
await db.execute("DELETE FROM charges WHERE id = ?", (charge_id,))
async def check_address_balance(address: str) -> List[Charges]:
address_data = await get_address(address)
mempool = await get_mempool(address_data.user)
try:
async with httpx.AsyncClient() as client:
r = await client.get(mempool.endpoint + "/api/address/" + address)
except Exception:
pass
amount_paid = r.json()['chain_stats']['funded_txo_sum'] - r.json()['chain_stats']['spent_txo_sum']
print(amount_paid)
async def check_address_balance(charge_id: str) -> List[Charges]:
charge = await get_charge(charge_id)
if charge.onchainaddress:
mempool = await get_mempool(charge.user)
try:
async with httpx.AsyncClient() as client:
r = await client.get(mempool.endpoint + "/api/address/" + charge.onchainaddress)
respAmount = r.json()['chain_stats']['funded_txo_sum']
if (charge.balance + respAmount) >= charge.balance:
return await update_charge(charge_id = charge_id, balance = (charge.balance + respAmount), paid = True)
else:
return await update_charge(charge_id = charge_id, balance = (charge.balance + respAmount), paid = False)
except Exception:
pass
if charge.lnbitswallet:
invoice_status = await check_invoice_status(charge.lnbitswallet, charge.payment_hash)
if invoice_status.paid:
return await update_charge(charge_id = charge_id, balance = charge.balance, paid = True)
row = await db.fetchone("SELECT * FROM charges WHERE id = ?", (charge_id,))
return Charges.from_row(row) if row else None
+11 -5
View File
@@ -9,13 +9,19 @@ async def m001_initial(db):
CREATE TABLE IF NOT EXISTS charges (
id TEXT NOT NULL PRIMARY KEY,
user TEXT,
title TEXT,
wallet TEXT NOT NULL,
address TEXT NOT NULL,
time_to_pay INTEGER,
description TEXT,
onchainwallet TEXT,
onchainaddress TEXT,
lnbitswallet TEXT,
lnbitskey TEXT,
payment_request TEXT,
payment_hash TEXT,
webhook TEXT,
time INTEGER,
amount INTEGER,
balance INTEGER DEFAULT 0,
time TIMESTAMP NOT NULL DEFAULT (strftime('%s', 'now'))
paid BOOLEAN,
timestamp TIMESTAMP NOT NULL DEFAULT (strftime('%s', 'now'))
);
"""
)
+10 -5
View File
@@ -4,13 +4,18 @@ from typing import NamedTuple
class Charges(NamedTuple):
id: str
user: str
wallet: str
title: str
address: str
time_to_pay: str
description: str
onchainwallet: str
onchainaddress: str
lnbitswallet: str
payment_request: str
payment_hash: str
webhook: str
time: str
amount: int
balance: int
time: int
paid: bool
timestamp: int
@classmethod
def from_row(cls, row: Row) -> "Payments":
@@ -215,7 +215,7 @@
<div v-if="formDialogCharge.data.onchain">
<q-select filled dense emit-value v-model="onchainwallet" :options="walletLinks" label="Onchain Wallet" />
<q-select filled dense emit-value v-model="formDialogCharge.data.onchainwallet" :options="walletLinks" label="Onchain Wallet" />
</div>
<div v-if="formDialogCharge.data.lnbits">
@@ -223,7 +223,7 @@
filled
dense
emit-value
v-model="formDialog.data.wallet"
v-model="formDialogCharge.data.lnbitswallet"
:options="g.user.walletOptions"
label="Wallet *"
>
@@ -442,10 +442,11 @@
LNbits.api
.request(
'GET',
'/satspay/api/v1/ChargeLinks',
'/satspay/api/v1/charges',
this.g.user.wallets[0].inkey
)
.then(function (response) {
console.log(response.data)
var i
var now = parseInt(new Date() / 1000)
for (i = 0; i < response.data.length; i++) {
@@ -468,8 +469,9 @@
},
sendFormDataCharge: function () {
var self = this
var wallet = self.g.user.wallets[0]
var wallet = self.g.user.wallets[0].inkey
var data = self.formDialogCharge.data
console.log(data)
data.amount = parseInt(data.amount)
data.time = parseInt(data.time)
if (data.id) {
@@ -501,10 +503,11 @@
var self = this
LNbits.api
.request('POST', '/satspay/api/v1/Charge', wallet.inkey, data)
.request('POST', '/satspay/api/v1/charge', wallet, data)
.then(function (response) {
self.ChargeLinks.push(mapCharge(response.data))
self.formDialogCharge.show = false
self.formDialogCharge.data = null
})
.catch(function (error) {
LNbits.utils.notifyApiError(error)
+5 -3
View File
@@ -81,6 +81,7 @@ async def api_wallet_delete(wallet_id):
async def api_charges_retrieve():
charges = await get_charges(g.wallet.user)
print(charges)
if not charges:
return (
jsonify(""),
@@ -106,8 +107,10 @@ async def api_charge_retrieve(charge_id):
@api_check_wallet_key("invoice")
@api_validate_post_request(
schema={
"walletid": {"type": "string", "empty": False, "required": True},
"title": {"type": "string", "empty": False, "required": True},
"onchainwallet": {"type": "string", "empty": False, "required": True},
"lnbitswallet": {"type": "string", "empty": False, "required": True},
"description": {"type": "string", "empty": False, "required": True},
"webhook": {"type": "string", "empty": False, "required": True},
"time": {"type": "integer", "min": 1, "required": True},
"amount": {"type": "integer", "min": 1, "required": True},
}
@@ -117,7 +120,6 @@ async def api_charge_create_or_update(charge_id=None):
if not charge_id:
charge = await create_charge(user = g.wallet.user, **g.data)
return jsonify(charge), HTTPStatus.CREATED
else:
charge = await update_charge(user = g.wallet.user, **g.data)
return jsonify(charge), HTTPStatus.OK