Satsdice error, confused over url_for

This commit is contained in:
benarc 2021-10-15 14:28:41 +01:00
parent 85feb0de86
commit 982415f013
8 changed files with 168 additions and 156 deletions

View File

@ -39,8 +39,8 @@ async def api_get_jukeboxs(
):
wallet_user = wallet.wallet.user
jukeboxs = [jukebox.dict() for jukebox in await get_jukeboxs(wallet_user)]
try:
jukeboxs = [jukebox.dict() for jukebox in await get_jukeboxs(wallet_user)]
return jukeboxs
except:

View File

@ -23,6 +23,7 @@ from .crud import (
delete_pay_link,
)
@lnurlp_ext.get("/api/v1/currencies")
async def api_list_currencies_available():
return list(currencies.keys())
@ -30,14 +31,21 @@ async def api_list_currencies_available():
@lnurlp_ext.get("/api/v1/links", status_code=HTTPStatus.OK)
# @api_check_wallet_key("invoice")
async def api_links(req: Request, wallet: WalletTypeInfo = Depends(get_key_type), all_wallets: bool = Query(False)):
async def api_links(
req: Request,
wallet: WalletTypeInfo = Depends(get_key_type),
all_wallets: bool = Query(False),
):
wallet_ids = [wallet.wallet.id]
if all_wallets:
wallet_ids = (await get_user(wallet.wallet.user)).wallet_ids
try:
return [{**link.dict(), "lnurl": link.lnurl(req)} for link in await get_pay_links(wallet_ids)]
return [
{**link.dict(), "lnurl": link.lnurl(req)}
for link in await get_pay_links(wallet_ids)
]
# return [
# {**link.dict(), "lnurl": link.lnurl}
# for link in await get_pay_links(wallet_ids)
@ -58,20 +66,20 @@ async def api_links(req: Request, wallet: WalletTypeInfo = Depends(get_key_type)
@lnurlp_ext.get("/api/v1/links/{link_id}", status_code=HTTPStatus.OK)
# @api_check_wallet_key("invoice")
async def api_link_retrieve(r: Request, link_id, wallet: WalletTypeInfo = Depends(get_key_type)):
async def api_link_retrieve(
r: Request, link_id, wallet: WalletTypeInfo = Depends(get_key_type)
):
link = await get_pay_link(link_id)
if not link:
raise HTTPException(
detail="Pay link does not exist.",
status_code=HTTPStatus.NOT_FOUND
detail="Pay link does not exist.", status_code=HTTPStatus.NOT_FOUND
)
# return {"message": "Pay link does not exist."}, HTTPStatus.NOT_FOUND
if link.wallet != wallet.wallet.id:
raise HTTPException(
detail="Not your pay link.",
status_code=HTTPStatus.FORBIDDEN
detail="Not your pay link.", status_code=HTTPStatus.FORBIDDEN
)
# return {"message": "Not your pay link."}, HTTPStatus.FORBIDDEN
@ -81,11 +89,14 @@ async def api_link_retrieve(r: Request, link_id, wallet: WalletTypeInfo = Depend
@lnurlp_ext.post("/api/v1/links", status_code=HTTPStatus.CREATED)
@lnurlp_ext.put("/api/v1/links/{link_id}", status_code=HTTPStatus.OK)
# @api_check_wallet_key("invoice")
async def api_link_create_or_update(data: CreatePayLinkData, link_id=None, wallet: WalletTypeInfo = Depends(get_key_type)):
async def api_link_create_or_update(
data: CreatePayLinkData,
link_id=None,
wallet: WalletTypeInfo = Depends(get_key_type),
):
if data.min > data.max:
raise HTTPException(
detail="Min is greater than max.",
status_code=HTTPStatus.BAD_REQUEST
detail="Min is greater than max.", status_code=HTTPStatus.BAD_REQUEST
)
# return {"message": "Min is greater than max."}, HTTPStatus.BAD_REQUEST
@ -93,15 +104,14 @@ async def api_link_create_or_update(data: CreatePayLinkData, link_id=None, walle
round(data.min) != data.min or round(data.max) != data.max
):
raise HTTPException(
detail="Must use full satoshis.",
status_code=HTTPStatus.BAD_REQUEST
detail="Must use full satoshis.", status_code=HTTPStatus.BAD_REQUEST
)
# return {"message": "Must use full satoshis."}, HTTPStatus.BAD_REQUEST
if "success_url" in data and data.success_url[:8] != "https://":
raise HTTPException(
detail="Success URL must be secure https://...",
status_code=HTTPStatus.BAD_REQUEST
status_code=HTTPStatus.BAD_REQUEST,
)
# return (
# {"message": "Success URL must be secure https://..."},
@ -113,8 +123,7 @@ async def api_link_create_or_update(data: CreatePayLinkData, link_id=None, walle
if not link:
raise HTTPException(
detail="Pay link does not exist.",
status_code=HTTPStatus.NOT_FOUND
detail="Pay link does not exist.", status_code=HTTPStatus.NOT_FOUND
)
# return (
# {"message": "Pay link does not exist."},
@ -123,12 +132,11 @@ async def api_link_create_or_update(data: CreatePayLinkData, link_id=None, walle
if link.wallet != wallet.wallet.id:
raise HTTPException(
detail="Not your pay link.",
status_code=HTTPStatus.FORBIDDEN
detail="Not your pay link.", status_code=HTTPStatus.FORBIDDEN
)
# return {"message": "Not your pay link."}, HTTPStatus.FORBIDDEN
link = await update_pay_link(link_id, data)
link = await update_pay_link(data, link_id=link_id)
else:
link = await create_pay_link(data, wallet_id=wallet.wallet.id)
print("LINK", link)
@ -142,15 +150,13 @@ async def api_link_delete(link_id, wallet: WalletTypeInfo = Depends(get_key_type
if not link:
raise HTTPException(
detail="Pay link does not exist.",
status_code=HTTPStatus.NOT_FOUND
detail="Pay link does not exist.", status_code=HTTPStatus.NOT_FOUND
)
# return {"message": "Pay link does not exist."}, HTTPStatus.NOT_FOUND
if link.wallet != wallet.wallet.id:
raise HTTPException(
detail="Not your pay link.",
status_code=HTTPStatus.FORBIDDEN
detail="Not your pay link.", status_code=HTTPStatus.FORBIDDEN
)
# return {"message": "Not your pay link."}, HTTPStatus.FORBIDDEN

View File

@ -66,6 +66,9 @@ async def get_satsdice_pay(link_id: str) -> Optional[satsdiceLink]:
async def get_satsdice_pays(wallet_ids: Union[str, List[str]]) -> List[satsdiceLink]:
if isinstance(wallet_ids, str):
wallet_ids = [wallet_ids]
print("wallet_ids")
print(wallet_ids)
print("wallet_ids")
q = ",".join(["?"] * len(wallet_ids))
rows = await db.fetchall(
@ -75,8 +78,7 @@ async def get_satsdice_pays(wallet_ids: Union[str, List[str]]) -> List[satsdiceL
""",
(*wallet_ids,),
)
return [satsdiceLink.from_row(row) for row in rows]
return [satsdiceLink(**row) for row in rows]
async def update_satsdice_pay(link_id: int, **kwargs) -> Optional[satsdiceLink]:
@ -88,7 +90,7 @@ async def update_satsdice_pay(link_id: int, **kwargs) -> Optional[satsdiceLink]:
row = await db.fetchone(
"SELECT * FROM satsdice.satsdice_pay WHERE id = ?", (link_id,)
)
return satsdiceLink.from_row(row) if row else None
return satsdiceLink(**row) if row else None
async def increment_satsdice_pay(link_id: int, **kwargs) -> Optional[satsdiceLink]:

View File

@ -4,9 +4,14 @@ import math
from http import HTTPStatus
from datetime import datetime
from lnbits.core.services import pay_invoice, create_invoice
from http import HTTPStatus
from starlette.exceptions import HTTPException
from starlette.responses import HTMLResponse, JSONResponse # type: ignore
from lnbits.utils.exchange_rates import get_fiat_rate_satoshis
from fastapi import FastAPI, Request
from fastapi.params import Depends
from typing import Optional
from fastapi.param_functions import Query
from . import satsdice_ext
from .crud import (
get_satsdice_withdraw_by_hash,
@ -20,16 +25,16 @@ from lnurl import LnurlPayResponse, LnurlPayActionResponse, LnurlErrorResponse
##############LNURLP STUFF
@satsdice_ext.route("/api/v1/lnurlp/<link_id>", methods=["GET"])
async def api_lnurlp_response(link_id):
@satsdice_ext.get("/api/v1/lnurlp/{link_id}", name="satsdice.lnurlp_response")
async def api_lnurlp_response(req: Request, link_id: str = Query(None)):
link = await get_satsdice_pay(link_id)
if not link:
return (
jsonify({"status": "ERROR", "reason": "LNURL-payy not found."}),
HTTPStatus.OK,
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail="LNURL-pay not found.",
)
resp = LnurlPayResponse(
callback=url_for(
callback=req.url_for(
"satsdice.api_lnurlp_callback", link_id=link.id, _external=True
),
min_sendable=math.ceil(link.min_bet * 1) * 1000,
@ -38,41 +43,31 @@ async def api_lnurlp_response(link_id):
)
params = resp.dict()
return jsonify(params), HTTPStatus.OK
return params
@satsdice_ext.route("/api/v1/lnurlp/cb/<link_id>", methods=["GET"])
async def api_lnurlp_callback(link_id):
@satsdice_ext.get("/api/v1/lnurlp/cb/{link_id}")
async def api_lnurlp_callback(link_id: str = Query(None), amount: str = Query(None)):
link = await get_satsdice_pay(link_id)
if not link:
return (
jsonify({"status": "ERROR", "reason": "LNUeL-pay not found."}),
HTTPStatus.OK,
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail="LNURL-pay not found.",
)
min, max = link.min_bet, link.max_bet
min = link.min_bet * 1000
max = link.max_bet * 1000
amount_received = int(request.args.get("amount") or 0)
amount_received = int(amount or 0)
if amount_received < min:
return (
jsonify(
LnurlErrorResponse(
reason=f"Amount {amount_received} is smaller than minimum {min}."
).dict()
),
HTTPStatus.OK,
)
return LnurlErrorResponse(
reason=f"Amount {amount_received} is smaller than minimum {min}."
).dict()
elif amount_received > max:
return (
jsonify(
LnurlErrorResponse(
reason=f"Amount {amount_received} is greater than maximum {max}."
).dict()
),
HTTPStatus.OK,
)
return LnurlErrorResponse(
reason=f"Amount {amount_received} is greater than maximum {max}."
).dict()
payment_hash, payment_request = await create_invoice(
wallet_id=link.wallet,
@ -85,9 +80,11 @@ async def api_lnurlp_callback(link_id):
)
success_action = link.success_action(payment_hash)
link = await create_satsdice_payment(
satsdice_pay=link.id, value=amount_received / 1000, payment_hash=payment_hash
)
data = []
data.satsdice_payy = link.id
data.value = amount_received / 1000
data.payment_hash = payment_hash
link = await create_satsdice_payment(data)
if success_action:
resp = LnurlPayActionResponse(
pr=payment_request,
@ -100,64 +97,63 @@ async def api_lnurlp_callback(link_id):
routes=[],
)
return jsonify(resp.dict()), HTTPStatus.OK
return resp.dict()
##############LNURLW STUFF
@satsdice_ext.route("/api/v1/lnurlw/<unique_hash>", methods=["GET"])
async def api_lnurlw_response(unique_hash):
@satsdice_ext.get("/api/v1/lnurlw/{unique_hash}", name="satsdice.lnurlw_response")
async def api_lnurlw_response(unique_hash: str = Query(None)):
link = await get_satsdice_withdraw_by_hash(unique_hash)
if not link:
return (
jsonify({"status": "ERROR", "reason": "LNURL-satsdice not found."}),
HTTPStatus.OK,
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail="LNURL-satsdice not found.",
)
if link.used:
return (
jsonify({"status": "ERROR", "reason": "satsdice is spent."}),
HTTPStatus.OK,
raise HTTPException(
status_code=HTTPStatus.OK,
detail="satsdice is spent.",
)
return jsonify(link.lnurl_response.dict()), HTTPStatus.OK
return link.lnurl_response.dict()
# CALLBACK
@satsdice_ext.route("/api/v1/lnurlw/cb/<unique_hash>", methods=["GET"])
async def api_lnurlw_callback(unique_hash):
@satsdice_ext.get("/api/v1/lnurlw/cb/{unique_hash}")
async def api_lnurlw_callback(
unique_hash: str = Query(None), k1: str = Query(None), pr: str = Query(None)
):
link = await get_satsdice_withdraw_by_hash(unique_hash)
paylink = await get_satsdice_pay(link.satsdice_pay)
k1 = request.args.get("k1", type=str)
payment_request = request.args.get("pr", type=str)
payment_request = pr
now = int(datetime.now().timestamp())
if not link:
return (
jsonify({"status": "ERROR", "reason": "LNURL-satsdice not found."}),
HTTPStatus.OK,
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail="LNURL-satsdice not found.",
)
if link.used:
return (
jsonify({"status": "ERROR", "reason": "satsdice is spent."}),
HTTPStatus.OK,
raise HTTPException(
status_code=HTTPStatus.OK,
detail="satsdice is spent.",
)
if link.k1 != k1:
return jsonify({"status": "ERROR", "reason": "Bad request."}), HTTPStatus.OK
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST,
detail="Bad request..",
)
if now < link.open_time:
return (
jsonify(
{"status": "ERROR", "reason": f"Wait {link.open_time - now} seconds."}
),
HTTPStatus.OK,
)
return {"status": "ERROR", "reason": f"Wait {link.open_time - now} seconds."}
try:
await update_satsdice_withdraw(link.id, used=1)
@ -171,12 +167,12 @@ async def api_lnurlw_callback(unique_hash):
except ValueError as e:
await update_satsdice_withdraw(link.id, used=1)
return jsonify({"status": "ERROR", "reason": str(e)})
return {"status": "ERROR", "reason": str(e)}
except PermissionError:
await update_satsdice_withdraw(link.id, used=1)
return jsonify({"status": "ERROR", "reason": "satsdice link is empty."})
return {"status": "ERROR", "reason": "satsdice link is empty."}
except Exception as e:
await update_satsdice_withdraw(link.id, used=1)
return jsonify({"status": "ERROR", "reason": str(e)})
return {"status": "ERROR", "reason": str(e)}
return jsonify({"status": "OK"}), HTTPStatus.OK
return {"status": "OK"}

View File

@ -9,10 +9,11 @@ from fastapi.param_functions import Query
from pydantic.main import BaseModel
from pydantic import BaseModel
from typing import Optional
from fastapi import FastAPI, Request
class satsdiceLink(NamedTuple):
id: int
class satsdiceLink(BaseModel):
id: str
wallet: str
title: str
min_bet: int
@ -26,22 +27,20 @@ class satsdiceLink(NamedTuple):
base_url: str
open_time: int
def lnurl(self, req: Request) -> Lnurl:
return lnurl_encode(req.url_for("satsdice.lnurlp_response", item_id=self.id))
@classmethod
def from_row(cls, row: Row) -> "satsdiceLink":
data = dict(row)
return cls(**data)
@property
def lnurl(self) -> Lnurl:
url = url_for("satsdice.api_lnurlp_response", link_id=self.id, _external=True)
return lnurl_encode(url)
@property
def lnurlpay_metadata(self) -> LnurlPayMetadata:
return LnurlPayMetadata(json.dumps([["text/plain", self.title]]))
def success_action(self, payment_hash: str) -> Optional[Dict]:
url = url_for(
def success_action(self, payment_hash: str, req: Request) -> Optional[Dict]:
url = req.url_for(
"satsdice.displaywin",
link_id=self.id,
payment_hash=payment_hash,
@ -59,20 +58,15 @@ class satsdiceLink(NamedTuple):
}
class satsdicePayment(NamedTuple):
class satsdicePayment(BaseModel):
payment_hash: str
satsdice_pay: str
value: int
paid: bool
lost: bool
@classmethod
def from_row(cls, row: Row) -> "satsdicePayment":
data = dict(row)
return cls(**data)
class satsdiceWithdraw(NamedTuple):
class satsdiceWithdraw(BaseModel):
id: str
satsdice_pay: str
value: int
@ -81,28 +75,22 @@ class satsdiceWithdraw(NamedTuple):
open_time: int
used: int
@classmethod
def from_row(cls, row: Row) -> "satsdiceWithdraw":
data = dict(row)
return cls(**data)
def lnurl(self, req: Request) -> Lnurl:
return lnurl_encode(
req.url_for(
"satsdice.lnurlw_response",
unique_hash=self.unique_hash,
_external=True,
)
)
@property
def is_spent(self) -> bool:
return self.used >= 1
@property
def lnurl(self) -> Lnurl:
url = url_for(
"satsdice.api_lnurlw_response",
unique_hash=self.unique_hash,
_external=True,
)
return lnurl_encode(url)
@property
def lnurl_response(self) -> LnurlWithdrawResponse:
url = url_for(
def lnurl_response(self, req: Request) -> LnurlWithdrawResponse:
url = req.url_for(
"satsdice.api_lnurlw_callback",
unique_hash=self.unique_hash,
_external=True,
@ -116,7 +104,7 @@ class satsdiceWithdraw(NamedTuple):
)
class HashCheck(NamedTuple):
class HashCheck(BaseModel):
id: str
lnurl_id: str

View File

@ -346,6 +346,7 @@
this.g.user.wallets[0].inkey
)
.then(response => {
console.log(response.data)
this.payLinks = response.data.map(mapPayLink)
})
.catch(err => {
@ -512,6 +513,7 @@
},
created() {
console.log('this.multiValue')
console.log(this.g.user)
if (this.g.user.wallets.length) {
var getPayLinks = this.getPayLinks
getPayLinks()

View File

@ -9,6 +9,15 @@ from .crud import (
create_satsdice_withdraw,
get_satsdice_withdraw,
)
from lnbits.core.crud import (
get_payments,
get_standalone_payment,
delete_expired_invoices,
get_balance_checks,
)
from lnbits.core.services import (
check_invoice_status,
)
from fastapi import FastAPI, Request
from fastapi.params import Depends
from fastapi.templating import Jinja2Templates
@ -44,7 +53,7 @@ async def display(link_id):
@satsdice_ext.get("/win/{link_id}/{payment_hash}")
async def displaywin(link_id, payment_hash):
async def displaywin(link_id: str = Query(None), payment_hash: str = Query(None)):
satsdicelink = await get_satsdice_pay(link_id) or abort(
HTTPStatus.NOT_FOUND, "satsdice link does not exist."
)
@ -91,17 +100,15 @@ async def displaywin(link_id, payment_hash):
chance = satsdicelink.chance
if rand > chance:
await update_satsdice_payment(payment_hash, lost=1)
return satsdice_renderer().TemplateResponse(
"satsdice/error.html", link=satsdicelink.id, paid=False, lost=True
)
withdrawLink = await create_satsdice_withdraw(
payment_hash=payment_hash,
satsdice_pay=satsdicelink.id,
value=paylink.value * satsdicelink.multiplier,
used=0,
)
return satsdice_renderer().TemplateResponse(
"satsdice/error.html", link=satsdicelink.id, paid=False, lost=True
)
data = []
data.payment_hash = payment_hash
data.satsdice_pay = (satsdicelink.id,)
data.value = (paylink.value * satsdicelink.multiplier,)
data.used = 0
withdrawLink = await create_satsdice_withdraw(data)
return satsdice_renderer().TemplateResponse(
"satsdice/displaywin.html",
value=withdrawLink.value,

View File

@ -35,17 +35,21 @@ from lnbits.decorators import (
@satsdice_ext.get("/api/v1/links")
async def api_links(wallet: WalletTypeInfo = Depends(get_key_type)):
async def api_links(
request: Request,
wallet: WalletTypeInfo = Depends(get_key_type),
all_wallets: str = Query(None),
):
wallet_ids = [wallet.wallet.id]
if "all_wallets" in request.args:
if all_wallets:
wallet_ids = (await get_user(wallet.wallet.user)).wallet_ids
try:
return [
{**link._dict(), **{"lnurl": link.lnurl}}
for link in await get_satsdice_pays(wallet_ids)
]
links = await get_satsdice_pays(wallet_ids)
print(links[0])
return [{link.dict(), {"lnurl": link.lnurl(request)}} for link in links]
except LnurlInvalidUrl:
raise HTTPException(
status_code=HTTPStatus.UPGRADE_REQUIRED,
@ -54,7 +58,11 @@ async def api_links(wallet: WalletTypeInfo = Depends(get_key_type)):
@satsdice_ext.get("/api/v1/links/{link_id}")
async def api_link_retrieve(data: CreateSatsDiceLink, link_id: str = Query(None)):
async def api_link_retrieve(
data: CreateSatsDiceLink,
link_id: str = Query(None),
wallet: WalletTypeInfo = Depends(get_key_type),
):
link = await get_satsdice_pay(link_id)
if not link:
@ -63,7 +71,7 @@ async def api_link_retrieve(data: CreateSatsDiceLink, link_id: str = Query(None)
detail="Pay link does not exist.",
)
if link.wallet != g.wallet.id:
if link.wallet != wallet.wallet.id:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="Not your pay link.",
@ -98,12 +106,13 @@ async def api_link_create_or_update(
status_code=HTTPStatus.FORBIDDEN,
detail="Come on, seriously, this isn't your satsdice!",
)
link = await update_satsdice_pay(data, link_id)
data.link_id = link_id
link = await update_satsdice_pay(data)
else:
link = await create_satsdice_pay(data, wallet_id=wallet.wallet.id)
data.wallet_id = wallet.wallet.id
link = await create_satsdice_pay(data)
return {**link.dict(), **{"lnurl": link.lnurl}}
return {link.dict(), {"lnurl": link.lnurl}}
@satsdice_ext.delete("/api/v1/links/{link_id}")
@ -133,10 +142,12 @@ async def api_link_delete(
@satsdice_ext.get("/api/v1/withdraws")
async def api_withdraws(wallet: WalletTypeInfo = Depends(get_key_type)):
async def api_withdraws(
wallet: WalletTypeInfo = Depends(get_key_type), all_wallets: str = Query(None)
):
wallet_ids = [wallet.wallet.id]
if "all_wallets" in request.args:
if all_wallets:
wallet_ids = (await get_user(wallet.wallet.user)).wallet_ids
try:
return (
@ -170,7 +181,7 @@ async def api_withdraw_retrieve(
detail="satsdice withdraw does not exist.",
)
if withdraw.wallet != g.wallet.id:
if withdraw.wallet != wallet.wallet.id:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="Not your satsdice withdraw.",
@ -193,8 +204,8 @@ async def api_withdraw_create_or_update(
)
usescsv = ""
for i in range(g.data["uses"]):
if g.data["is_unique"]:
for i in range(data.uses):
if data.is_unique:
usescsv += "," + str(i + 1)
else:
usescsv += "," + str(1)
@ -207,18 +218,18 @@ async def api_withdraw_create_or_update(
status_code=HTTPStatus.NOT_FOUND,
detail="satsdice withdraw does not exist.",
)
if withdraw.wallet != g.wallet.id:
if withdraw.wallet != wallet.wallet.id:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="Not your satsdice withdraw.",
)
withdraw = await update_satsdice_withdraw(
withdraw_id, **g.data, usescsv=usescsv, used=0
withdraw_id, **data, usescsv=usescsv, used=0
)
else:
withdraw = await create_satsdice_withdraw(
wallet_id=g.wallet.id, **g.data, usescsv=usescsv
wallet_id=wallet.wallet.id, **data, usescsv=usescsv
)
return {**withdraw._asdict(), **{"lnurl": withdraw.lnurl}}