amount is float and sats are int

This commit is contained in:
callebtc 2022-02-16 22:41:12 +01:00
parent 914b9f3ffe
commit 30ab519c3a

View file

@ -68,13 +68,9 @@ async def api_wallet(wallet: WalletTypeInfo = Depends(get_key_type)):
@core_app.put("/api/v1/wallet/balance/{amount}") @core_app.put("/api/v1/wallet/balance/{amount}")
async def api_update_balance( async def api_update_balance(amount: int, wallet: WalletTypeInfo = Depends(get_key_type)):
amount: int, wallet: WalletTypeInfo = Depends(get_key_type)
):
if wallet.wallet.user not in LNBITS_ADMIN_USERS: if wallet.wallet.user not in LNBITS_ADMIN_USERS:
raise HTTPException( raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="Not an admin user")
status_code=HTTPStatus.FORBIDDEN, detail="Not an admin user"
)
payHash = urlsafe_short_hash() payHash = urlsafe_short_hash()
await create_payment( await create_payment(
@ -97,9 +93,7 @@ async def api_update_balance(
@core_app.put("/api/v1/wallet/{new_name}") @core_app.put("/api/v1/wallet/{new_name}")
async def api_update_wallet( async def api_update_wallet(new_name: str, wallet: WalletTypeInfo = Depends(WalletAdminKeyChecker())):
new_name: str, wallet: WalletTypeInfo = Depends(WalletAdminKeyChecker())
):
await update_wallet(wallet.wallet.id, new_name) await update_wallet(wallet.wallet.id, new_name)
return { return {
"id": wallet.wallet.id, "id": wallet.wallet.id,
@ -111,19 +105,15 @@ async def api_update_wallet(
@core_app.get("/api/v1/payments") @core_app.get("/api/v1/payments")
async def api_payments(wallet: WalletTypeInfo = Depends(get_key_type)): async def api_payments(wallet: WalletTypeInfo = Depends(get_key_type)):
await get_payments(wallet_id=wallet.wallet.id, pending=True, complete=True) await get_payments(wallet_id=wallet.wallet.id, pending=True, complete=True)
pendingPayments = await get_payments( pendingPayments = await get_payments(wallet_id=wallet.wallet.id, pending=True, exclude_uncheckable=True)
wallet_id=wallet.wallet.id, pending=True, exclude_uncheckable=True
)
for payment in pendingPayments: for payment in pendingPayments:
await check_invoice_status( await check_invoice_status(wallet_id=payment.wallet_id, payment_hash=payment.payment_hash)
wallet_id=payment.wallet_id, payment_hash=payment.payment_hash
)
return await get_payments(wallet_id=wallet.wallet.id, pending=True, complete=True) return await get_payments(wallet_id=wallet.wallet.id, pending=True, complete=True)
class CreateInvoiceData(BaseModel): class CreateInvoiceData(BaseModel):
out: Optional[bool] = True out: Optional[bool] = True
amount: int = Query(None, ge=0) amount: float = Query(None, ge=0)
memo: str = None memo: str = None
unit: Optional[str] = "sat" unit: Optional[str] = "sat"
description_hash: Optional[str] = None description_hash: Optional[str] = None
@ -142,7 +132,7 @@ async def api_payments_create_invoice(data: CreateInvoiceData, wallet: Wallet):
description_hash = b"" description_hash = b""
memo = data.memo memo = data.memo
if data.unit == "sat": if data.unit == "sat":
amount = data.amount amount = int(data.amount)
else: else:
price_in_sats = await fiat_amount_as_satoshis(data.amount, data.unit) price_in_sats = await fiat_amount_as_satoshis(data.amount, data.unit)
amount = price_in_sats amount = price_in_sats
@ -242,9 +232,7 @@ async def api_payments_create(
status_code=HTTPStatus.BAD_REQUEST, status_code=HTTPStatus.BAD_REQUEST,
detail="BOLT11 string is invalid or not given", detail="BOLT11 string is invalid or not given",
) )
return await api_payments_pay_invoice( return await api_payments_pay_invoice(invoiceData.bolt11, wallet.wallet) # admin key
invoiceData.bolt11, wallet.wallet
) # admin key
# invoice key # invoice key
return await api_payments_create_invoice(invoiceData, wallet.wallet) return await api_payments_create_invoice(invoiceData, wallet.wallet)
@ -258,9 +246,7 @@ class CreateLNURLData(BaseModel):
@core_app.post("/api/v1/payments/lnurl") @core_app.post("/api/v1/payments/lnurl")
async def api_payments_pay_lnurl( async def api_payments_pay_lnurl(data: CreateLNURLData, wallet: WalletTypeInfo = Depends(get_key_type)):
data: CreateLNURLData, wallet: WalletTypeInfo = Depends(get_key_type)
):
domain = urlparse(data.callback).netloc domain = urlparse(data.callback).netloc
async with httpx.AsyncClient() as client: async with httpx.AsyncClient() as client:
@ -292,11 +278,11 @@ async def api_payments_pay_lnurl(
detail=f"{domain} returned an invalid invoice. Expected {data.amount} msat, got {invoice.amount_msat}.", detail=f"{domain} returned an invalid invoice. Expected {data.amount} msat, got {invoice.amount_msat}.",
) )
# if invoice.description_hash != data.description_hash: # if invoice.description_hash != data.description_hash:
# raise HTTPException( # raise HTTPException(
# status_code=HTTPStatus.BAD_REQUEST, # status_code=HTTPStatus.BAD_REQUEST,
# detail=f"{domain} returned an invalid invoice. Expected description_hash == {data.description_hash}, got {invoice.description_hash}.", # detail=f"{domain} returned an invalid invoice. Expected description_hash == {data.description_hash}, got {invoice.description_hash}.",
# ) # )
extra = {} extra = {}
@ -354,12 +340,8 @@ async def subscribe(request: Request, wallet: Wallet):
@core_app.get("/api/v1/payments/sse") @core_app.get("/api/v1/payments/sse")
async def api_payments_sse( async def api_payments_sse(request: Request, wallet: WalletTypeInfo = Depends(get_key_type)):
request: Request, wallet: WalletTypeInfo = Depends(get_key_type) return EventSourceResponse(subscribe(request, wallet), ping=20, media_type="text/event-stream")
):
return EventSourceResponse(
subscribe(request, wallet), ping=20, media_type="text/event-stream"
)
@core_app.get("/api/v1/payments/{payment_hash}") @core_app.get("/api/v1/payments/{payment_hash}")
@ -368,9 +350,7 @@ async def api_payment(payment_hash):
await check_invoice_status(payment.wallet_id, payment_hash) await check_invoice_status(payment.wallet_id, payment_hash)
payment = await get_standalone_payment(payment_hash) payment = await get_standalone_payment(payment_hash)
if not payment: if not payment:
raise HTTPException( raise HTTPException(status_code=HTTPStatus.NOT_FOUND, detail="Payment does not exist.")
status_code=HTTPStatus.NOT_FOUND, detail="Payment does not exist."
)
elif not payment.pending: elif not payment.pending:
return {"paid": True, "preimage": payment.preimage} return {"paid": True, "preimage": payment.preimage}
@ -382,9 +362,7 @@ async def api_payment(payment_hash):
return {"paid": not payment.pending, "preimage": payment.preimage} return {"paid": not payment.pending, "preimage": payment.preimage}
@core_app.get( @core_app.get("/api/v1/lnurlscan/{code}", dependencies=[Depends(WalletInvoiceKeyChecker())])
"/api/v1/lnurlscan/{code}", dependencies=[Depends(WalletInvoiceKeyChecker())]
)
async def api_lnurlscan(code: str): async def api_lnurlscan(code: str):
try: try:
url = lnurl.decode(code) url = lnurl.decode(code)
@ -394,17 +372,10 @@ async def api_lnurlscan(code: str):
name_domain = code.split("@") name_domain = code.split("@")
if len(name_domain) == 2 and len(name_domain[1].split(".")) == 2: if len(name_domain) == 2 and len(name_domain[1].split(".")) == 2:
name, domain = name_domain name, domain = name_domain
url = ( url = ("http://" if domain.endswith(".onion") else "https://") + domain + "/.well-known/lnurlp/" + name
("http://" if domain.endswith(".onion") else "https://")
+ domain
+ "/.well-known/lnurlp/"
+ name
)
# will proceed with these values # will proceed with these values
else: else:
raise HTTPException( raise HTTPException(status_code=HTTPStatus.BAD_REQUEST, detail="invalid lnurl")
status_code=HTTPStatus.BAD_REQUEST, detail="invalid lnurl"
)
# params is what will be returned to the client # params is what will be returned to the client
params: Dict = {"domain": domain} params: Dict = {"domain": domain}
@ -463,20 +434,14 @@ async def api_lnurlscan(code: str):
params.update(balanceCheck=data["balanceCheck"]) params.update(balanceCheck=data["balanceCheck"])
# format callback url and send to client # format callback url and send to client
parsed_callback = parsed_callback._replace( parsed_callback = parsed_callback._replace(query=urlencode(qs, doseq=True))
query=urlencode(qs, doseq=True)
)
params.update(callback=urlunparse(parsed_callback)) params.update(callback=urlunparse(parsed_callback))
if tag == "payRequest": if tag == "payRequest":
params.update(kind="pay") params.update(kind="pay")
params.update(fixed=data["minSendable"] == data["maxSendable"]) params.update(fixed=data["minSendable"] == data["maxSendable"])
params.update( params.update(description_hash=hashlib.sha256(data["metadata"].encode("utf-8")).hexdigest())
description_hash=hashlib.sha256(
data["metadata"].encode("utf-8")
).hexdigest()
)
metadata = json.loads(data["metadata"]) metadata = json.loads(data["metadata"])
for [k, v] in metadata: for [k, v] in metadata:
if k == "text/plain": if k == "text/plain":
@ -528,9 +493,7 @@ async def api_payments_decode(data: str = Query(None)):
async def api_perform_lnurlauth(callback: str): async def api_perform_lnurlauth(callback: str):
err = await perform_lnurlauth(callback) err = await perform_lnurlauth(callback)
if err: if err:
raise HTTPException( raise HTTPException(status_code=HTTPStatus.SERVICE_UNAVAILABLE, detail=err.reason)
status_code=HTTPStatus.SERVICE_UNAVAILABLE, detail=err.reason
)
return "" return ""
@ -553,9 +516,7 @@ async def api_fiat_as_sats(data: ConversionData):
output["sats"] = int(data.amount) output["sats"] = int(data.amount)
output["BTC"] = data.amount / 100000000 output["BTC"] = data.amount / 100000000
for currency in data.to.split(","): for currency in data.to.split(","):
output[currency.strip().upper()] = await satoshis_amount_as_fiat( output[currency.strip().upper()] = await satoshis_amount_as_fiat(data.amount, currency.strip())
data.amount, currency.strip()
)
return output return output
else: else:
output[data.from_.upper()] = data.amount output[data.from_.upper()] = data.amount