Satsdice working, although invoices are not being seen as paid

This commit is contained in:
Ben Arc 2021-10-20 03:08:43 +01:00
parent 47b3e537f4
commit e0db0bc6cd
4 changed files with 129 additions and 82 deletions

View file

@ -60,7 +60,7 @@ async def get_satsdice_pay(link_id: str) -> 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 get_satsdice_pays(wallet_ids: Union[str, List[str]]) -> List[satsdiceLink]: async def get_satsdice_pays(wallet_ids: Union[str, List[str]]) -> List[satsdiceLink]:
@ -102,7 +102,7 @@ async def increment_satsdice_pay(link_id: int, **kwargs) -> Optional[satsdiceLin
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 delete_satsdice_pay(link_id: int) -> None: async def delete_satsdice_pay(link_id: int) -> None:
@ -124,9 +124,9 @@ async def create_satsdice_payment(data: CreateSatsDicePayment) -> satsdicePaymen
) )
VALUES (?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?)
""", """,
(data.payment_hash, data.satsdice_pay, data.value, False, False), (data["payment_hash"], data["satsdice_pay"], data["value"], False, False),
) )
payment = await get_satsdice_payment(payment_hash) payment = await get_satsdice_payment(data["payment_hash"])
assert payment, "Newly created withdraw couldn't be retrieved" assert payment, "Newly created withdraw couldn't be retrieved"
return payment return payment
@ -136,7 +136,7 @@ async def get_satsdice_payment(payment_hash: str) -> Optional[satsdicePayment]:
"SELECT * FROM satsdice.satsdice_payment WHERE payment_hash = ?", "SELECT * FROM satsdice.satsdice_payment WHERE payment_hash = ?",
(payment_hash,), (payment_hash,),
) )
return satsdicePayment.from_row(row) if row else None return satsdicePayment(**row) if row else None
async def update_satsdice_payment( async def update_satsdice_payment(
@ -152,7 +152,7 @@ async def update_satsdice_payment(
"SELECT * FROM satsdice.satsdice_payment WHERE payment_hash = ?", "SELECT * FROM satsdice.satsdice_payment WHERE payment_hash = ?",
(payment_hash,), (payment_hash,),
) )
return satsdicePayment.from_row(row) if row else None return satsdicePayment(**row) if row else None
##################SATSDICE WITHDRAW LINKS ##################SATSDICE WITHDRAW LINKS
@ -173,16 +173,16 @@ async def create_satsdice_withdraw(data: CreateSatsDiceWithdraw) -> satsdiceWith
VALUES (?, ?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?, ?)
""", """,
( (
data.payment_hash, data["payment_hash"],
data.satsdice_pay, data["satsdice_pay"],
data.value, data["value"],
urlsafe_short_hash(), urlsafe_short_hash(),
urlsafe_short_hash(), urlsafe_short_hash(),
int(datetime.now().timestamp()), int(datetime.now().timestamp()),
data.used, data["used"],
), ),
) )
withdraw = await get_satsdice_withdraw(payment_hash, 0) withdraw = await get_satsdice_withdraw(data["payment_hash"], 0)
assert withdraw, "Newly created withdraw couldn't be retrieved" assert withdraw, "Newly created withdraw couldn't be retrieved"
return withdraw return withdraw
@ -198,7 +198,7 @@ async def get_satsdice_withdraw(withdraw_id: str, num=0) -> Optional[satsdiceWit
for item in row: for item in row:
withdraw.append(item) withdraw.append(item)
withdraw.append(num) withdraw.append(num)
return satsdiceWithdraw.from_row(row) return satsdiceWithdraw(**row)
async def get_satsdice_withdraw_by_hash( async def get_satsdice_withdraw_by_hash(
@ -214,7 +214,7 @@ async def get_satsdice_withdraw_by_hash(
for item in row: for item in row:
withdraw.append(item) withdraw.append(item)
withdraw.append(num) withdraw.append(num)
return satsdiceWithdraw.from_row(row) return satsdiceWithdraw(**row)
async def get_satsdice_withdraws( async def get_satsdice_withdraws(
@ -229,7 +229,7 @@ async def get_satsdice_withdraws(
(*wallet_ids,), (*wallet_ids,),
) )
return [satsdiceWithdraw.from_row(row) for row in rows] return [satsdiceWithdraw(**row) for row in rows]
async def update_satsdice_withdraw( async def update_satsdice_withdraw(
@ -243,7 +243,7 @@ async def update_satsdice_withdraw(
row = await db.fetchone( row = await db.fetchone(
"SELECT * FROM satsdice.satsdice_withdraw WHERE id = ?", (withdraw_id,) "SELECT * FROM satsdice.satsdice_withdraw WHERE id = ?", (withdraw_id,)
) )
return satsdiceWithdraw.from_row(row) if row else None return satsdiceWithdraw(**row) if row else None
async def delete_satsdice_withdraw(withdraw_id: str) -> None: async def delete_satsdice_withdraw(withdraw_id: str) -> None:

View file

@ -31,10 +31,13 @@ from .models import CreateSatsDicePayment
##############LNURLP STUFF ##############LNURLP STUFF
@satsdice_ext.get("/api/v1/lnurlp/{link_id}", name="satsdice.lnurlp_response") @satsdice_ext.get(
"/api/v1/lnurlp/{link_id}",
response_class=HTMLResponse,
name="satsdice.lnurlp_response",
)
async def api_lnurlp_response(req: Request, link_id: str = Query(None)): 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)
print(link)
if not link: if not link:
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="LNURL-pay not found." status_code=HTTPStatus.NOT_FOUND, detail="LNURL-pay not found."
@ -55,12 +58,12 @@ async def api_lnurlp_response(req: Request, link_id: str = Query(None)):
name="satsdice.api_lnurlp_callback", name="satsdice.api_lnurlp_callback",
) )
async def api_lnurlp_callback( async def api_lnurlp_callback(
data: CreateSatsDicePayment,
req: Request, req: Request,
link_id: str = Query(None), link_id: str = Query(None),
amount: str = Query(None), amount: str = Query(None),
): ):
link = await get_satsdice_pay(link_id) link = await get_satsdice_pay(link_id)
print(link)
if not link: if not link:
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="LNURL-pay not found." status_code=HTTPStatus.NOT_FOUND, detail="LNURL-pay not found."
@ -93,24 +96,20 @@ async def api_lnurlp_callback(
) )
success_action = link.success_action(payment_hash=payment_hash, req=req) success_action = link.success_action(payment_hash=payment_hash, req=req)
print("success_action")
print(success_action) data: CreateSatsDicePayment = {
print("success_action") "satsdice_pay": link.id,
data.satsdice_pay = link.id "value": amount_received / 1000,
data.value = amount_received / 1000 "payment_hash": payment_hash,
data.payment_hash = payment_hash }
link = await create_satsdice_payment(data)
if success_action: await create_satsdice_payment(data)
payResponse = { payResponse = {
"pr": payment_request, "pr": payment_request,
"success_action": success_action, "successAction": success_action,
"routes": [], "routes": [],
} }
else: print(json.dumps(payResponse))
payResponse = {
"pr": payment_request,
"routes": [],
}
return json.dumps(payResponse) return json.dumps(payResponse)
@ -118,29 +117,45 @@ async def api_lnurlp_callback(
##############LNURLW STUFF ##############LNURLW STUFF
@satsdice_ext.get("/api/v1/lnurlw/{unique_hash}", name="satsdice.lnurlw_response") @satsdice_ext.get(
async def api_lnurlw_response(unique_hash: str = Query(None)): "/api/v1/lnurlw/{unique_hash}",
response_class=HTMLResponse,
name="satsdice.lnurlw_response",
)
async def api_lnurlw_response(req: Request, 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:
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="LNURL-satsdice not found." status_code=HTTPStatus.NOT_FOUND, detail="LNURL-satsdice not found."
) )
if link.used: if link.used:
raise HTTPException(status_code=HTTPStatus.OK, detail="satsdice is spent.") raise HTTPException(status_code=HTTPStatus.OK, detail="satsdice is spent.")
url = req.url_for("satsdice.api_lnurlw_callback", unique_hash=link.unique_hash)
return json.dumps(link.lnurl_response) withdrawResponse = {
"tag": "withdrawRequest",
"callback": url,
"k1": link.k1,
"minWithdrawable": link.value * 1000,
"maxWithdrawable": link.value * 1000,
"defaultDescription": "Satsdice winnings!",
}
return json.dumps(withdrawResponse)
# CALLBACK # CALLBACK
@satsdice_ext.get( @satsdice_ext.get(
"/api/v1/lnurlw/cb/{unique_hash}", name="satsdice.api_lnurlw_callback" "/api/v1/lnurlw/cb/{unique_hash}",
response_class=HTMLResponse,
name="satsdice.api_lnurlw_callback",
) )
async def api_lnurlw_callback( async def api_lnurlw_callback(
unique_hash: str = Query(None), k1: str = Query(None), pr: str = Query(None) req: Request,
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)

View file

@ -43,7 +43,6 @@ class satsdiceLink(BaseModel):
url = req.url_for( url = req.url_for(
"satsdice.displaywin", link_id=self.id, payment_hash=payment_hash "satsdice.displaywin", link_id=self.id, payment_hash=payment_hash
) )
print(url)
return {"tag": "url", "description": "Check the attached link", "url": url} return {"tag": "url", "description": "Check the attached link", "url": url}
@ -102,7 +101,7 @@ class CreateSatsDiceLink(BaseModel):
base_url: str = Query(None) base_url: str = Query(None)
min_bet: str = Query(None) min_bet: str = Query(None)
max_bet: str = Query(None) max_bet: str = Query(None)
multiplier: int = Query(0) multiplier: float = Query(0)
chance: float = Query(0) chance: float = Query(0)
haircut: int = Query(0) haircut: int = Query(0)

View file

@ -22,9 +22,10 @@ from fastapi.templating import Jinja2Templates
from starlette.exceptions import HTTPException from starlette.exceptions import HTTPException
from starlette.responses import HTMLResponse from starlette.responses import HTMLResponse
from lnbits.core.models import User, Payment from lnbits.core.models import User, Payment
from fastapi.params import Depends from fastapi.params import Depends
from fastapi.param_functions import Query from fastapi.param_functions import Query
import random
from .models import CreateSatsDiceWithdraw
templates = Jinja2Templates(directory="templates") templates = Jinja2Templates(directory="templates")
@ -37,35 +38,47 @@ async def index(request: Request, user: User = Depends(check_user_exists)):
@satsdice_ext.get("/{link_id}") @satsdice_ext.get("/{link_id}")
async def display(link_id): async def display(request: Request, link_id: str = Query(None)):
link = await get_satsdice_pay(link_id) or abort( link = await get_satsdice_pay(link_id) or abort(
HTTPStatus.NOT_FOUND, "satsdice link does not exist." HTTPStatus.NOT_FOUND, "satsdice link does not exist."
) )
return satsdice_renderer().TemplateResponse( return satsdice_renderer().TemplateResponse(
"satsdice/display.html", "satsdice/display.html",
chance=link.chance, {
multiplier=link.multiplier, "request": request,
lnurl=link.lnurl, "chance": link.chance,
unique=True, "multiplier": link.multiplier,
"lnurl": link.lnurl(request),
"unique": True,
},
) )
@satsdice_ext.get("/win/{link_id}/{payment_hash}", name="satsdice.displaywin") @satsdice_ext.get("/win/{link_id}/{payment_hash}", name="satsdice.displaywin")
async def displaywin(link_id: str = Query(None), payment_hash: str = Query(None)): async def displaywin(
request: Request, 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."
) )
withdrawLink = await get_satsdice_withdraw(payment_hash)
status = await check_invoice_status(
wallet_id=satsdicelink.wallet, payment_hash=payment_hash
)
withdrawLink = await get_satsdice_withdraw(payment_hash)
if withdrawLink: if withdrawLink:
return satsdice_renderer().TemplateResponse( return satsdice_renderer().TemplateResponse(
"satsdice/displaywin.html", "satsdice/displaywin.html",
value=withdrawLink.value, {
chance=satsdicelink.chance, "request": request,
multiplier=satsdicelink.multiplier, "value": withdrawLink.value,
lnurl=withdrawLink.lnurl, "chance": satsdicelink.chance,
paid=False, "multiplier": satsdicelink.multiplier,
lost=False, "lnurl": withdrawLink.lnurl(request),
"paid": False,
"lost": False,
},
) )
payment = await get_standalone_payment(payment_hash) or abort( payment = await get_standalone_payment(payment_hash) or abort(
@ -78,43 +91,63 @@ async def displaywin(link_id: str = Query(None), payment_hash: str = Query(None)
HTTPStatus.NOT_FOUND, "satsdice link does not exist." HTTPStatus.NOT_FOUND, "satsdice link does not exist."
) )
if payment.pending == 1: if payment.pending == 1:
print("pending") print("cunt")
return satsdice_renderer().TemplateResponse( return satsdice_renderer().TemplateResponse(
"satsdice/error.html", link=satsdicelink.id, paid=False, lost=False "satsdice/error.html",
{
"request": request,
"link": satsdicelink.id,
"paid": False,
"lost": False,
},
) )
await update_satsdice_payment(payment_hash, paid=1) await update_satsdice_payment(payment_hash, paid=1)
paylink = await get_satsdice_payment(payment_hash)
if not paylink:
paylink = await get_satsdice_payment(payment_hash) or abort( return satsdice_renderer().TemplateResponse(
HTTPStatus.NOT_FOUND, "satsdice link does not exist." "satsdice/error.html",
) {
"request": request,
if paylink.lost == 1: "link": satsdicelink.id,
print("lost") "paid": False,
return satsdice_renderer().TemplateResponse( "lost": True,
"satsdice/error.html", link=satsdicelink.id, paid=False, lost=True },
) )
rand = random.randint(0, 100) rand = random.randint(0, 100)
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",
{
"request": request,
"link": satsdicelink.id,
"paid": False,
"lost": True,
},
) )
data = []
data.payment_hash = payment_hash data: CreateSatsDiceWithdraw = {
data.satsdice_pay = (satsdicelink.id,) "satsdice_pay": satsdicelink.id,
data.value = (paylink.value * satsdicelink.multiplier,) "value": paylink.value * satsdicelink.multiplier,
data.used = 0 "payment_hash": payment_hash,
"used": 0,
}
withdrawLink = await create_satsdice_withdraw(data) withdrawLink = await create_satsdice_withdraw(data)
return satsdice_renderer().TemplateResponse( return satsdice_renderer().TemplateResponse(
"satsdice/displaywin.html", "satsdice/displaywin.html",
value=withdrawLink.value, {
chance=satsdicelink.chance, "request": request,
multiplier=satsdicelink.multiplier, "value": withdrawLink.value,
lnurl=withdrawLink.lnurl, "chance": satsdicelink.chance,
paid=False, "multiplier": satsdicelink.multiplier,
lost=False, "lnurl": withdrawLink.lnurl(request),
"paid": False,
"lost": False,
},
) )