satsdice lnurl pain

This commit is contained in:
Ben Arc 2021-10-19 23:05:29 +01:00
parent aaaa4ce8e7
commit 47b3e537f4
3 changed files with 63 additions and 52 deletions

View file

@ -1,6 +1,7 @@
import shortuuid # type: ignore import shortuuid # type: ignore
import hashlib import hashlib
import math import math
import json
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
@ -23,7 +24,8 @@ from lnurl import (
LnurlPayResponse, LnurlPayResponse,
LnurlPayActionResponse, LnurlPayActionResponse,
LnurlErrorResponse, LnurlErrorResponse,
) # type: ignore )
from .models import CreateSatsDicePayment
##############LNURLP STUFF ##############LNURLP STUFF
@ -32,25 +34,32 @@ from lnurl import (
@satsdice_ext.get("/api/v1/lnurlp/{link_id}", name="satsdice.lnurlp_response") @satsdice_ext.get("/api/v1/lnurlp/{link_id}", 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."
) )
resp = LnurlPayResponse( payResponse = {
callback=req.url_for( "tag": "payRequest",
"satsdice.api_lnurlp_callback", link_id=link.id, _external=True "callback": req.url_for("satsdice.api_lnurlp_callback", link_id=link.id),
), "metadata": link.lnurlpay_metadata,
min_sendable=math.ceil(link.min_bet * 1) * 1000, "minSendable": math.ceil(link.min_bet * 1) * 1000,
max_sendable=round(link.max_bet * 1) * 1000, "maxSendable": round(link.max_bet * 1) * 1000,
metadata=link.lnurlpay_metadata, }
) return json.dumps(payResponse)
params = resp.dict()
return params
@satsdice_ext.get("/api/v1/lnurlp/cb/{link_id}") @satsdice_ext.get(
async def api_lnurlp_callback(link_id: str = Query(None), amount: str = Query(None)): "/api/v1/lnurlp/cb/{link_id}",
response_class=HTMLResponse,
name="satsdice.api_lnurlp_callback",
)
async def api_lnurlp_callback(
data: CreateSatsDicePayment,
req: Request,
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:
raise HTTPException( raise HTTPException(
@ -63,13 +72,15 @@ async def api_lnurlp_callback(link_id: str = Query(None), amount: str = Query(No
amount_received = int(amount or 0) amount_received = int(amount or 0)
if amount_received < min: if amount_received < min:
return LnurlErrorResponse( raise HTTPException(
reason=f"Amount {amount_received} is smaller than minimum {min}." status_code=HTTPStatus.FORBIDDEN,
).dict() detail=f"Amount {amount_received} is smaller than minimum {min}.",
)
elif amount_received > max: elif amount_received > max:
return LnurlErrorResponse( raise HTTPException(
reason=f"Amount {amount_received} is greater than maximum {max}." status_code=HTTPStatus.FORBIDDEN,
).dict() detail=f"Amount {amount_received} is greater than maximum {max}.",
)
payment_hash, payment_request = await create_invoice( payment_hash, payment_request = await create_invoice(
wallet_id=link.wallet, wallet_id=link.wallet,
@ -81,20 +92,27 @@ async def api_lnurlp_callback(link_id: str = Query(None), amount: str = Query(No
extra={"tag": "satsdice", "link": link.id, "comment": "comment"}, extra={"tag": "satsdice", "link": link.id, "comment": "comment"},
) )
success_action = link.success_action(payment_hash) success_action = link.success_action(payment_hash=payment_hash, req=req)
data = [] print("success_action")
data.satsdice_payy = link.id print(success_action)
print("success_action")
data.satsdice_pay = link.id
data.value = amount_received / 1000 data.value = amount_received / 1000
data.payment_hash = payment_hash data.payment_hash = payment_hash
link = await create_satsdice_payment(data) link = await create_satsdice_payment(data)
if success_action: if success_action:
resp = LnurlPayActionResponse( payResponse = {
pr=payment_request, success_action=success_action, routes=[] "pr": payment_request,
) "success_action": success_action,
"routes": [],
}
else: else:
resp = LnurlPayActionResponse(pr=payment_request, routes=[]) payResponse = {
"pr": payment_request,
"routes": [],
}
return resp.dict() return json.dumps(payResponse)
##############LNURLW STUFF ##############LNURLW STUFF
@ -112,13 +130,15 @@ async def api_lnurlw_response(unique_hash: str = Query(None)):
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.")
return link.lnurl_response.dict() return json.dumps(link.lnurl_response)
# CALLBACK # CALLBACK
@satsdice_ext.get("/api/v1/lnurlw/cb/{unique_hash}") @satsdice_ext.get(
"/api/v1/lnurlw/cb/{unique_hash}", 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) unique_hash: str = Query(None), k1: str = Query(None), pr: str = Query(None)
): ):

View file

@ -41,16 +41,9 @@ class satsdiceLink(BaseModel):
def success_action(self, payment_hash: str, req: Request) -> Optional[Dict]: def success_action(self, payment_hash: str, req: Request) -> Optional[Dict]:
url = req.url_for( url = req.url_for(
"satsdice.displaywin", "satsdice.displaywin", link_id=self.id, payment_hash=payment_hash
link_id=self.id,
payment_hash=payment_hash,
_external=True,
) )
# url: ParseResult = urlparse(url)
print(url) print(url)
# qs: Dict = parse_qs(url.query)
# qs["payment_hash"] = payment_hash
# url = url._replace(query=urlencode(qs, doseq=True))
return {"tag": "url", "description": "Check the attached link", "url": url} return {"tag": "url", "description": "Check the attached link", "url": url}
@ -73,9 +66,7 @@ class satsdiceWithdraw(BaseModel):
def lnurl(self, req: Request) -> Lnurl: def lnurl(self, req: Request) -> Lnurl:
return lnurl_encode( return lnurl_encode(
req.url_for( req.url_for("satsdice.lnurlw_response", unique_hash=self.unique_hash)
"satsdice.lnurlw_response", unique_hash=self.unique_hash, _external=True
)
) )
@property @property
@ -84,16 +75,16 @@ class satsdiceWithdraw(BaseModel):
@property @property
def lnurl_response(self, req: Request) -> LnurlWithdrawResponse: def lnurl_response(self, req: Request) -> LnurlWithdrawResponse:
url = req.url_for( url = req.url_for("satsdice.api_lnurlw_callback", unique_hash=self.unique_hash)
"satsdice.api_lnurlw_callback", unique_hash=self.unique_hash, _external=True withdrawResponse = {
) "tag": "withdrawRequest",
return LnurlWithdrawResponse( "callback": url,
callback=url, "k1": self.k1,
k1=self.k1, "minWithdrawable": self.value * 1000,
minWithdrawable=self.value * 1000, "maxWithdrawable": self.value * 1000,
maxWithdrawable=self.value * 1000, "defaultDescription": "Satsdice winnings!",
default_description="Satsdice winnings!", }
) return withdrawResponse
class HashCheck(BaseModel): class HashCheck(BaseModel):

View file

@ -50,7 +50,7 @@ async def display(link_id):
) )
@satsdice_ext.get("/win/{link_id}/{payment_hash}") @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(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."