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 wallet_user = wallet.wallet.user
jukeboxs = [jukebox.dict() for jukebox in await get_jukeboxs(wallet_user)]
try: try:
jukeboxs = [jukebox.dict() for jukebox in await get_jukeboxs(wallet_user)]
return jukeboxs return jukeboxs
except: except:

View File

@@ -23,6 +23,7 @@ from .crud import (
delete_pay_link, delete_pay_link,
) )
@lnurlp_ext.get("/api/v1/currencies") @lnurlp_ext.get("/api/v1/currencies")
async def api_list_currencies_available(): async def api_list_currencies_available():
return list(currencies.keys()) return list(currencies.keys())
@@ -30,14 +31,21 @@ async def api_list_currencies_available():
@lnurlp_ext.get("/api/v1/links", status_code=HTTPStatus.OK) @lnurlp_ext.get("/api/v1/links", status_code=HTTPStatus.OK)
# @api_check_wallet_key("invoice") # @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] wallet_ids = [wallet.wallet.id]
if all_wallets: if all_wallets:
wallet_ids = (await get_user(wallet.wallet.user)).wallet_ids wallet_ids = (await get_user(wallet.wallet.user)).wallet_ids
try: 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 [ # return [
# {**link.dict(), "lnurl": link.lnurl} # {**link.dict(), "lnurl": link.lnurl}
# for link in await get_pay_links(wallet_ids) # 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) @lnurlp_ext.get("/api/v1/links/{link_id}", status_code=HTTPStatus.OK)
# @api_check_wallet_key("invoice") # @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) link = await get_pay_link(link_id)
if not link: if not link:
raise HTTPException( raise HTTPException(
detail="Pay link does not exist.", detail="Pay link does not exist.", status_code=HTTPStatus.NOT_FOUND
status_code=HTTPStatus.NOT_FOUND
) )
# return {"message": "Pay link does not exist."}, HTTPStatus.NOT_FOUND # return {"message": "Pay link does not exist."}, HTTPStatus.NOT_FOUND
if link.wallet != wallet.wallet.id: if link.wallet != wallet.wallet.id:
raise HTTPException( raise HTTPException(
detail="Not your pay link.", detail="Not your pay link.", status_code=HTTPStatus.FORBIDDEN
status_code=HTTPStatus.FORBIDDEN
) )
# return {"message": "Not your pay link."}, 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.post("/api/v1/links", status_code=HTTPStatus.CREATED)
@lnurlp_ext.put("/api/v1/links/{link_id}", status_code=HTTPStatus.OK) @lnurlp_ext.put("/api/v1/links/{link_id}", status_code=HTTPStatus.OK)
# @api_check_wallet_key("invoice") # @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: if data.min > data.max:
raise HTTPException( raise HTTPException(
detail="Min is greater than max.", detail="Min is greater than max.", status_code=HTTPStatus.BAD_REQUEST
status_code=HTTPStatus.BAD_REQUEST
) )
# return {"message": "Min is greater than max."}, 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 round(data.min) != data.min or round(data.max) != data.max
): ):
raise HTTPException( raise HTTPException(
detail="Must use full satoshis.", detail="Must use full satoshis.", status_code=HTTPStatus.BAD_REQUEST
status_code=HTTPStatus.BAD_REQUEST
) )
# return {"message": "Must use full satoshis."}, HTTPStatus.BAD_REQUEST # return {"message": "Must use full satoshis."}, HTTPStatus.BAD_REQUEST
if "success_url" in data and data.success_url[:8] != "https://": if "success_url" in data and data.success_url[:8] != "https://":
raise HTTPException( raise HTTPException(
detail="Success URL must be secure https://...", detail="Success URL must be secure https://...",
status_code=HTTPStatus.BAD_REQUEST status_code=HTTPStatus.BAD_REQUEST,
) )
# return ( # return (
# {"message": "Success URL must be secure https://..."}, # {"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: if not link:
raise HTTPException( raise HTTPException(
detail="Pay link does not exist.", detail="Pay link does not exist.", status_code=HTTPStatus.NOT_FOUND
status_code=HTTPStatus.NOT_FOUND
) )
# return ( # return (
# {"message": "Pay link does not exist."}, # {"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: if link.wallet != wallet.wallet.id:
raise HTTPException( raise HTTPException(
detail="Not your pay link.", detail="Not your pay link.", status_code=HTTPStatus.FORBIDDEN
status_code=HTTPStatus.FORBIDDEN
) )
# return {"message": "Not your pay link."}, 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: else:
link = await create_pay_link(data, wallet_id=wallet.wallet.id) link = await create_pay_link(data, wallet_id=wallet.wallet.id)
print("LINK", link) print("LINK", link)
@@ -142,15 +150,13 @@ async def api_link_delete(link_id, wallet: WalletTypeInfo = Depends(get_key_type
if not link: if not link:
raise HTTPException( raise HTTPException(
detail="Pay link does not exist.", detail="Pay link does not exist.", status_code=HTTPStatus.NOT_FOUND
status_code=HTTPStatus.NOT_FOUND
) )
# return {"message": "Pay link does not exist."}, HTTPStatus.NOT_FOUND # return {"message": "Pay link does not exist."}, HTTPStatus.NOT_FOUND
if link.wallet != wallet.wallet.id: if link.wallet != wallet.wallet.id:
raise HTTPException( raise HTTPException(
detail="Not your pay link.", detail="Not your pay link.", status_code=HTTPStatus.FORBIDDEN
status_code=HTTPStatus.FORBIDDEN
) )
# return {"message": "Not your pay link."}, 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]: async def get_satsdice_pays(wallet_ids: Union[str, List[str]]) -> List[satsdiceLink]:
if isinstance(wallet_ids, str): if isinstance(wallet_ids, str):
wallet_ids = [wallet_ids] wallet_ids = [wallet_ids]
print("wallet_ids")
print(wallet_ids)
print("wallet_ids")
q = ",".join(["?"] * len(wallet_ids)) q = ",".join(["?"] * len(wallet_ids))
rows = await db.fetchall( rows = await db.fetchall(
@@ -75,8 +78,7 @@ async def get_satsdice_pays(wallet_ids: Union[str, List[str]]) -> List[satsdiceL
""", """,
(*wallet_ids,), (*wallet_ids,),
) )
return [satsdiceLink(**row) for row in rows]
return [satsdiceLink.from_row(row) for row in rows]
async def update_satsdice_pay(link_id: int, **kwargs) -> Optional[satsdiceLink]: 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( row = await db.fetchone(
"SELECT * FROM satsdice.satsdice_pay WHERE id = ?", (link_id,) "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]: async def increment_satsdice_pay(link_id: int, **kwargs) -> Optional[satsdiceLink]:

View File

@@ -4,9 +4,14 @@ import math
from http import HTTPStatus from http import HTTPStatus
from datetime import datetime from datetime import datetime
from lnbits.core.services import pay_invoice, create_invoice 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 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 . import satsdice_ext
from .crud import ( from .crud import (
get_satsdice_withdraw_by_hash, get_satsdice_withdraw_by_hash,
@@ -20,16 +25,16 @@ from lnurl import LnurlPayResponse, LnurlPayActionResponse, LnurlErrorResponse
##############LNURLP STUFF ##############LNURLP STUFF
@satsdice_ext.route("/api/v1/lnurlp/<link_id>", methods=["GET"]) @satsdice_ext.get("/api/v1/lnurlp/{link_id}", name="satsdice.lnurlp_response")
async def api_lnurlp_response(link_id): async def api_lnurlp_response(req: Request, link_id: str = Query(None)):
link = await get_satsdice_pay(link_id) link = await get_satsdice_pay(link_id)
if not link: if not link:
return ( raise HTTPException(
jsonify({"status": "ERROR", "reason": "LNURL-payy not found."}), status_code=HTTPStatus.NOT_FOUND,
HTTPStatus.OK, detail="LNURL-pay not found.",
) )
resp = LnurlPayResponse( resp = LnurlPayResponse(
callback=url_for( callback=req.url_for(
"satsdice.api_lnurlp_callback", link_id=link.id, _external=True "satsdice.api_lnurlp_callback", link_id=link.id, _external=True
), ),
min_sendable=math.ceil(link.min_bet * 1) * 1000, min_sendable=math.ceil(link.min_bet * 1) * 1000,
@@ -38,41 +43,31 @@ async def api_lnurlp_response(link_id):
) )
params = resp.dict() params = resp.dict()
return jsonify(params), HTTPStatus.OK return params
@satsdice_ext.route("/api/v1/lnurlp/cb/<link_id>", methods=["GET"]) @satsdice_ext.get("/api/v1/lnurlp/cb/{link_id}")
async def api_lnurlp_callback(link_id): async def api_lnurlp_callback(link_id: str = Query(None), amount: str = Query(None)):
link = await get_satsdice_pay(link_id) link = await get_satsdice_pay(link_id)
if not link: if not link:
return ( raise HTTPException(
jsonify({"status": "ERROR", "reason": "LNUeL-pay not found."}), status_code=HTTPStatus.NOT_FOUND,
HTTPStatus.OK, detail="LNURL-pay not found.",
) )
min, max = link.min_bet, link.max_bet min, max = link.min_bet, link.max_bet
min = link.min_bet * 1000 min = link.min_bet * 1000
max = link.max_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: if amount_received < min:
return ( return LnurlErrorResponse(
jsonify( reason=f"Amount {amount_received} is smaller than minimum {min}."
LnurlErrorResponse( ).dict()
reason=f"Amount {amount_received} is smaller than minimum {min}."
).dict()
),
HTTPStatus.OK,
)
elif amount_received > max: elif amount_received > max:
return ( return LnurlErrorResponse(
jsonify( reason=f"Amount {amount_received} is greater than maximum {max}."
LnurlErrorResponse( ).dict()
reason=f"Amount {amount_received} is greater than maximum {max}."
).dict()
),
HTTPStatus.OK,
)
payment_hash, payment_request = await create_invoice( payment_hash, payment_request = await create_invoice(
wallet_id=link.wallet, wallet_id=link.wallet,
@@ -85,9 +80,11 @@ async def api_lnurlp_callback(link_id):
) )
success_action = link.success_action(payment_hash) success_action = link.success_action(payment_hash)
link = await create_satsdice_payment( data = []
satsdice_pay=link.id, value=amount_received / 1000, payment_hash=payment_hash data.satsdice_payy = link.id
) data.value = amount_received / 1000
data.payment_hash = payment_hash
link = await create_satsdice_payment(data)
if success_action: if success_action:
resp = LnurlPayActionResponse( resp = LnurlPayActionResponse(
pr=payment_request, pr=payment_request,
@@ -100,64 +97,63 @@ async def api_lnurlp_callback(link_id):
routes=[], routes=[],
) )
return jsonify(resp.dict()), HTTPStatus.OK return resp.dict()
##############LNURLW STUFF ##############LNURLW STUFF
@satsdice_ext.route("/api/v1/lnurlw/<unique_hash>", methods=["GET"]) @satsdice_ext.get("/api/v1/lnurlw/{unique_hash}", name="satsdice.lnurlw_response")
async def api_lnurlw_response(unique_hash): async def api_lnurlw_response(unique_hash: str = Query(None)):
link = await get_satsdice_withdraw_by_hash(unique_hash) link = await get_satsdice_withdraw_by_hash(unique_hash)
if not link: if not link:
return ( raise HTTPException(
jsonify({"status": "ERROR", "reason": "LNURL-satsdice not found."}), status_code=HTTPStatus.NOT_FOUND,
HTTPStatus.OK, detail="LNURL-satsdice not found.",
) )
if link.used: if link.used:
return ( raise HTTPException(
jsonify({"status": "ERROR", "reason": "satsdice is spent."}), status_code=HTTPStatus.OK,
HTTPStatus.OK, detail="satsdice is spent.",
) )
return jsonify(link.lnurl_response.dict()), HTTPStatus.OK return link.lnurl_response.dict()
# CALLBACK # CALLBACK
@satsdice_ext.route("/api/v1/lnurlw/cb/<unique_hash>", methods=["GET"]) @satsdice_ext.get("/api/v1/lnurlw/cb/{unique_hash}")
async def api_lnurlw_callback(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) link = await get_satsdice_withdraw_by_hash(unique_hash)
paylink = await get_satsdice_pay(link.satsdice_pay) paylink = await get_satsdice_pay(link.satsdice_pay)
k1 = request.args.get("k1", type=str) payment_request = pr
payment_request = request.args.get("pr", type=str)
now = int(datetime.now().timestamp()) now = int(datetime.now().timestamp())
if not link: if not link:
return ( raise HTTPException(
jsonify({"status": "ERROR", "reason": "LNURL-satsdice not found."}), status_code=HTTPStatus.NOT_FOUND,
HTTPStatus.OK, detail="LNURL-satsdice not found.",
) )
if link.used: if link.used:
return ( raise HTTPException(
jsonify({"status": "ERROR", "reason": "satsdice is spent."}), status_code=HTTPStatus.OK,
HTTPStatus.OK, detail="satsdice is spent.",
) )
if link.k1 != k1: 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: if now < link.open_time:
return ( return {"status": "ERROR", "reason": f"Wait {link.open_time - now} seconds."}
jsonify(
{"status": "ERROR", "reason": f"Wait {link.open_time - now} seconds."}
),
HTTPStatus.OK,
)
try: try:
await update_satsdice_withdraw(link.id, used=1) await update_satsdice_withdraw(link.id, used=1)
@@ -171,12 +167,12 @@ async def api_lnurlw_callback(unique_hash):
except ValueError as e: except ValueError as e:
await update_satsdice_withdraw(link.id, used=1) await update_satsdice_withdraw(link.id, used=1)
return jsonify({"status": "ERROR", "reason": str(e)}) return {"status": "ERROR", "reason": str(e)}
except PermissionError: except PermissionError:
await update_satsdice_withdraw(link.id, used=1) 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: except Exception as e:
await update_satsdice_withdraw(link.id, used=1) 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.main import BaseModel
from pydantic import BaseModel from pydantic import BaseModel
from typing import Optional from typing import Optional
from fastapi import FastAPI, Request
class satsdiceLink(NamedTuple): class satsdiceLink(BaseModel):
id: int id: str
wallet: str wallet: str
title: str title: str
min_bet: int min_bet: int
@@ -26,22 +27,20 @@ class satsdiceLink(NamedTuple):
base_url: str base_url: str
open_time: int open_time: int
def lnurl(self, req: Request) -> Lnurl:
return lnurl_encode(req.url_for("satsdice.lnurlp_response", item_id=self.id))
@classmethod @classmethod
def from_row(cls, row: Row) -> "satsdiceLink": def from_row(cls, row: Row) -> "satsdiceLink":
data = dict(row) data = dict(row)
return cls(**data) 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 @property
def lnurlpay_metadata(self) -> LnurlPayMetadata: def lnurlpay_metadata(self) -> LnurlPayMetadata:
return LnurlPayMetadata(json.dumps([["text/plain", self.title]])) return LnurlPayMetadata(json.dumps([["text/plain", self.title]]))
def success_action(self, payment_hash: str) -> Optional[Dict]: def success_action(self, payment_hash: str, req: Request) -> Optional[Dict]:
url = url_for( url = req.url_for(
"satsdice.displaywin", "satsdice.displaywin",
link_id=self.id, link_id=self.id,
payment_hash=payment_hash, payment_hash=payment_hash,
@@ -59,20 +58,15 @@ class satsdiceLink(NamedTuple):
} }
class satsdicePayment(NamedTuple): class satsdicePayment(BaseModel):
payment_hash: str payment_hash: str
satsdice_pay: str satsdice_pay: str
value: int value: int
paid: bool paid: bool
lost: bool lost: bool
@classmethod
def from_row(cls, row: Row) -> "satsdicePayment":
data = dict(row)
return cls(**data)
class satsdiceWithdraw(BaseModel):
class satsdiceWithdraw(NamedTuple):
id: str id: str
satsdice_pay: str satsdice_pay: str
value: int value: int
@@ -81,28 +75,22 @@ class satsdiceWithdraw(NamedTuple):
open_time: int open_time: int
used: int used: int
@classmethod def lnurl(self, req: Request) -> Lnurl:
def from_row(cls, row: Row) -> "satsdiceWithdraw": return lnurl_encode(
data = dict(row) req.url_for(
return cls(**data) "satsdice.lnurlw_response",
unique_hash=self.unique_hash,
_external=True,
)
)
@property @property
def is_spent(self) -> bool: def is_spent(self) -> bool:
return self.used >= 1 return self.used >= 1
@property @property
def lnurl(self) -> Lnurl: def lnurl_response(self, req: Request) -> LnurlWithdrawResponse:
url = url_for( url = req.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(
"satsdice.api_lnurlw_callback", "satsdice.api_lnurlw_callback",
unique_hash=self.unique_hash, unique_hash=self.unique_hash,
_external=True, _external=True,
@@ -116,7 +104,7 @@ class satsdiceWithdraw(NamedTuple):
) )
class HashCheck(NamedTuple): class HashCheck(BaseModel):
id: str id: str
lnurl_id: str lnurl_id: str

View File

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

View File

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

View File

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