mirror of
https://github.com/RoboSats/robosats.git
synced 2025-01-18 12:11:35 +00:00
Conform to pep8 rules (#295)
* Conform to pep8 rules * Fix some more flake8 linting errors
This commit is contained in:
parent
529ffc0d58
commit
4d5c60239f
@ -237,7 +237,7 @@ class OrderAdmin(AdminChangeLinksMixin, admin.ModelAdmin):
|
||||
)
|
||||
|
||||
def amt(self, obj):
|
||||
if obj.has_range and obj.amount == None:
|
||||
if obj.has_range and obj.amount is None:
|
||||
return str(float(obj.min_amount)) + "-" + str(float(obj.max_amount))
|
||||
else:
|
||||
return float(obj.amount)
|
||||
|
@ -1,16 +1,20 @@
|
||||
import grpc, os, hashlib, secrets, ring
|
||||
|
||||
|
||||
from . import lightning_pb2 as lnrpc, lightning_pb2_grpc as lightningstub
|
||||
from . import invoices_pb2 as invoicesrpc, invoices_pb2_grpc as invoicesstub
|
||||
from . import router_pb2 as routerrpc, router_pb2_grpc as routerstub
|
||||
|
||||
from decouple import config
|
||||
import hashlib
|
||||
import os
|
||||
import secrets
|
||||
from base64 import b64decode
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from datetime import timedelta, datetime
|
||||
import grpc
|
||||
import ring
|
||||
from decouple import config
|
||||
from django.utils import timezone
|
||||
|
||||
from . import invoices_pb2 as invoicesrpc
|
||||
from . import invoices_pb2_grpc as invoicesstub
|
||||
from . import lightning_pb2 as lnrpc
|
||||
from . import lightning_pb2_grpc as lightningstub
|
||||
from . import router_pb2 as routerrpc
|
||||
from . import router_pb2_grpc as routerstub
|
||||
|
||||
#######
|
||||
# Should work with LND (c-lightning in the future if there are features that deserve the work)
|
||||
@ -19,7 +23,7 @@ from django.utils import timezone
|
||||
# Read tls.cert from file or .env variable string encoded as base64
|
||||
try:
|
||||
CERT = open(os.path.join(config("LND_DIR"), "tls.cert"), "rb").read()
|
||||
except:
|
||||
except Exception:
|
||||
CERT = b64decode(config("LND_CERT_BASE64"))
|
||||
|
||||
# Read macaroon from file or .env variable string encoded as base64
|
||||
@ -27,7 +31,7 @@ try:
|
||||
MACAROON = open(
|
||||
os.path.join(config("LND_DIR"), config("MACAROON_path")), "rb"
|
||||
).read()
|
||||
except:
|
||||
except Exception:
|
||||
MACAROON = b64decode(config("LND_MACAROON_BASE64"))
|
||||
|
||||
LND_GRPC_HOST = config("LND_GRPC_HOST")
|
||||
@ -236,7 +240,7 @@ class LNNode:
|
||||
@classmethod
|
||||
def resetmc(cls):
|
||||
request = routerrpc.ResetMissionControlRequest()
|
||||
response = cls.routerstub.ResetMissionControl(
|
||||
_ = cls.routerstub.ResetMissionControl(
|
||||
request, metadata=[("macaroon", MACAROON.hex())]
|
||||
)
|
||||
return True
|
||||
@ -256,14 +260,14 @@ class LNNode:
|
||||
|
||||
try:
|
||||
payreq_decoded = cls.decode_payreq(invoice)
|
||||
except:
|
||||
except Exception:
|
||||
payout["context"] = {
|
||||
"bad_invoice": "Does not look like a valid lightning invoice"
|
||||
}
|
||||
return payout
|
||||
|
||||
## Some wallet providers (e.g. Muun) force routing through a private channel with high fees >1500ppm
|
||||
## These payments will fail. So it is best to let the user know in advance this invoice is not valid.
|
||||
# Some wallet providers (e.g. Muun) force routing through a private channel with high fees >1500ppm
|
||||
# These payments will fail. So it is best to let the user know in advance this invoice is not valid.
|
||||
route_hints = payreq_decoded.route_hints
|
||||
|
||||
# Max amount RoboSats will pay for routing
|
||||
|
104
api/logics.py
104
api/logics.py
@ -101,7 +101,7 @@ class Logics:
|
||||
return (
|
||||
False,
|
||||
{
|
||||
"bad_request": f"Your PGP public key does not seem valid.\n"
|
||||
"bad_request": "Your PGP public key does not seem valid.\n"
|
||||
+ f"Stderr: {str(import_pub_result.stderr)}\n"
|
||||
+ f"ReturnCode: {str(import_pub_result.returncode)}\n"
|
||||
+ f"Summary: {str(import_pub_result.summary)}\n"
|
||||
@ -120,7 +120,7 @@ class Logics:
|
||||
return (
|
||||
False,
|
||||
{
|
||||
"bad_request": f"Your PGP encrypted private key does not seem valid.\n"
|
||||
"bad_request": "Your PGP encrypted private key does not seem valid.\n"
|
||||
+ f"Stderr: {str(import_priv_result.stderr)}\n"
|
||||
+ f"ReturnCode: {str(import_priv_result.returncode)}\n"
|
||||
+ f"Summary: {str(import_priv_result.summary)}\n"
|
||||
@ -182,7 +182,7 @@ class Logics:
|
||||
}
|
||||
elif min_sats < max_sats / 8:
|
||||
return False, {
|
||||
"bad_request": f"Your order amount range is too large. Max amount can only be 8 times bigger than min amount"
|
||||
"bad_request": "Your order amount range is too large. Max amount can only be 8 times bigger than min amount"
|
||||
}
|
||||
|
||||
return True, None
|
||||
@ -247,7 +247,7 @@ class Logics:
|
||||
if order.is_explicit:
|
||||
satoshis_now = order.satoshis
|
||||
else:
|
||||
amount = order.amount if order.amount != None else order.max_amount
|
||||
amount = order.amount if order.amount is not None else order.max_amount
|
||||
satoshis_now = cls.calc_sats(
|
||||
amount, order.currency.exchange_rate, order.premium
|
||||
)
|
||||
@ -293,7 +293,7 @@ class Logics:
|
||||
]
|
||||
|
||||
# in any case, if order is_swap and there is an onchain_payment, cancel it.
|
||||
if not order.status in does_not_expire:
|
||||
if order.status not in does_not_expire:
|
||||
cls.cancel_onchain_payment(order)
|
||||
|
||||
if order.status in does_not_expire:
|
||||
@ -342,7 +342,7 @@ class Logics:
|
||||
# If seller is offline the escrow LNpayment does not exist
|
||||
try:
|
||||
cls.cancel_escrow(order)
|
||||
except:
|
||||
except Exception:
|
||||
pass
|
||||
order.status = Order.Status.EXP
|
||||
order.expiry_reason = Order.ExpiryReasons.NESCRO
|
||||
@ -357,7 +357,7 @@ class Logics:
|
||||
# If seller is offline the escrow LNpayment does not even exist
|
||||
try:
|
||||
cls.cancel_escrow(order)
|
||||
except:
|
||||
except Exception:
|
||||
pass
|
||||
taker_bond = order.taker_bond
|
||||
order.taker = None
|
||||
@ -456,10 +456,10 @@ class Logics:
|
||||
order.save()
|
||||
|
||||
# User could be None if a dispute is open automatically due to weird expiration.
|
||||
if not user == None:
|
||||
if user is not None:
|
||||
profile = user.profile
|
||||
profile.num_disputes = profile.num_disputes + 1
|
||||
if profile.orders_disputes_started == None:
|
||||
if profile.orders_disputes_started is None:
|
||||
profile.orders_disputes_started = [str(order.id)]
|
||||
else:
|
||||
profile.orders_disputes_started = list(
|
||||
@ -554,7 +554,7 @@ class Logics:
|
||||
status=OnchainPayment.Status.VALID
|
||||
).aggregate(Sum("num_satoshis"))["num_satoshis__sum"]
|
||||
|
||||
if pending_txs == None:
|
||||
if pending_txs is None:
|
||||
pending_txs = 0
|
||||
|
||||
available_onchain = confirmed - reserve - pending_txs
|
||||
@ -622,7 +622,7 @@ class Logics:
|
||||
context["swap_failure_reason"] = "On-the-fly submarine swaps are dissabled"
|
||||
return True, context
|
||||
|
||||
if order.payout_tx == None:
|
||||
if order.payout_tx is None:
|
||||
# Creates the OnchainPayment object and checks node balance
|
||||
valid = cls.create_onchain_payment(
|
||||
order, user, preliminary_amount=context["invoice_amount"]
|
||||
@ -798,7 +798,7 @@ class Logics:
|
||||
# If the order status is 'Waiting for both'. Move forward to 'waiting for escrow'
|
||||
elif order.status == Order.Status.WF2:
|
||||
# If the escrow does not exist, or is not locked move to WFE.
|
||||
if order.trade_escrow == None:
|
||||
if order.trade_escrow is None:
|
||||
order.status = Order.Status.WFE
|
||||
# If the escrow is locked move to Chat.
|
||||
elif order.trade_escrow.status == LNPayment.Status.LOCKED:
|
||||
@ -827,7 +827,7 @@ class Logics:
|
||||
# TODO Unsafe, does not update ratings, it adds more ratings everytime a new rating is clicked.
|
||||
profile.total_ratings += 1
|
||||
latest_ratings = profile.latest_ratings
|
||||
if latest_ratings == None:
|
||||
if latest_ratings is None:
|
||||
profile.latest_ratings = [rating]
|
||||
profile.avg_rating = rating
|
||||
|
||||
@ -873,18 +873,19 @@ class Logics:
|
||||
return False, {"bad_request": "You cannot cancel this order"}
|
||||
|
||||
# 1) When maker cancels before bond
|
||||
"""The order never shows up on the book and order
|
||||
status becomes "cancelled" """
|
||||
# The order never shows up on the book and order
|
||||
# status becomes "cancelled"
|
||||
if order.status == Order.Status.WFB and order.maker == user:
|
||||
cls.cancel_bond(order.maker_bond)
|
||||
order.status = Order.Status.UCA
|
||||
order.save()
|
||||
return True, None
|
||||
|
||||
# 2.a) When maker cancels after bond
|
||||
"""The order dissapears from book and goes to cancelled. If strict, maker is charged the bond
|
||||
to prevent DDOS on the LN node and order book. If not strict, maker is returned
|
||||
the bond (more user friendly)."""
|
||||
# 2.a) When maker cancels after bond
|
||||
#
|
||||
# The order dissapears from book and goes to cancelled. If strict, maker is charged the bond
|
||||
# to prevent DDOS on the LN node and order book. If not strict, maker is returned
|
||||
# the bond (more user friendly).
|
||||
elif (
|
||||
order.status in [Order.Status.PUB, Order.Status.PAU] and order.maker == user
|
||||
):
|
||||
@ -895,9 +896,10 @@ class Logics:
|
||||
send_message.delay(order.id, "public_order_cancelled")
|
||||
return True, None
|
||||
|
||||
# 2.b) When maker cancels after bond and before taker bond is locked
|
||||
"""The order dissapears from book and goes to cancelled.
|
||||
The bond maker bond is returned."""
|
||||
# 2.b) When maker cancels after bond and before taker bond is locked
|
||||
#
|
||||
# The order dissapears from book and goes to cancelled.
|
||||
# The bond maker bond is returned.
|
||||
elif order.status == Order.Status.TAK and order.maker == user:
|
||||
# Return the maker bond (Maker gets returned the bond for cancelling public order)
|
||||
if cls.return_bond(order.maker_bond):
|
||||
@ -907,22 +909,23 @@ class Logics:
|
||||
send_message.delay(order.id, "public_order_cancelled")
|
||||
return True, None
|
||||
|
||||
# 3) When taker cancels before bond
|
||||
""" The order goes back to the book as public.
|
||||
LNPayment "order.taker_bond" is deleted() """
|
||||
# 3) When taker cancels before bond
|
||||
# The order goes back to the book as public.
|
||||
# LNPayment "order.taker_bond" is deleted()
|
||||
elif order.status == Order.Status.TAK and order.taker == user:
|
||||
# adds a timeout penalty
|
||||
cls.cancel_bond(order.taker_bond)
|
||||
cls.kick_taker(order)
|
||||
return True, None
|
||||
|
||||
# 4) When taker or maker cancel after bond (before escrow)
|
||||
"""The order goes into cancelled status if maker cancels.
|
||||
The order goes into the public book if taker cancels.
|
||||
In both cases there is a small fee."""
|
||||
# 4) When taker or maker cancel after bond (before escrow)
|
||||
#
|
||||
# The order goes into cancelled status if maker cancels.
|
||||
# The order goes into the public book if taker cancels.
|
||||
# In both cases there is a small fee.
|
||||
|
||||
# 4.a) When maker cancel after bond (before escrow)
|
||||
"""The order into cancelled status if maker cancels."""
|
||||
# 4.a) When maker cancel after bond (before escrow)
|
||||
# The order into cancelled status if maker cancels.
|
||||
elif (
|
||||
order.status in [Order.Status.WF2, Order.Status.WFE] and order.maker == user
|
||||
):
|
||||
@ -939,8 +942,8 @@ class Logics:
|
||||
cls.add_slashed_rewards(order.maker_bond, order.taker.profile)
|
||||
return True, None
|
||||
|
||||
# 4.b) When taker cancel after bond (before escrow)
|
||||
"""The order into cancelled status if mtker cancels."""
|
||||
# 4.b) When taker cancel after bond (before escrow)
|
||||
# The order into cancelled status if mtker cancels.
|
||||
elif (
|
||||
order.status in [Order.Status.WF2, Order.Status.WFE] and order.taker == user
|
||||
):
|
||||
@ -958,11 +961,12 @@ class Logics:
|
||||
cls.add_slashed_rewards(order.taker_bond, order.maker.profile)
|
||||
return True, None
|
||||
|
||||
# 5) When trade collateral has been posted (after escrow)
|
||||
"""Always goes to CCA status. Collaboration is needed.
|
||||
When a user asks for cancel, 'order.m/t/aker_asked_cancel' goes True.
|
||||
When the second user asks for cancel. Order is totally cancelled.
|
||||
Must have a small cost for both parties to prevent node DDOS."""
|
||||
# 5) When trade collateral has been posted (after escrow)
|
||||
#
|
||||
# Always goes to CCA status. Collaboration is needed.
|
||||
# When a user asks for cancel, 'order.m/t/aker_asked_cancel' goes True.
|
||||
# When the second user asks for cancel. Order is totally cancelled.
|
||||
# Must have a small cost for both parties to prevent node DDOS.
|
||||
elif order.status in [Order.Status.WFI, Order.Status.CHA]:
|
||||
|
||||
# if the maker had asked, and now the taker does: cancel order, return everything
|
||||
@ -991,7 +995,7 @@ class Logics:
|
||||
|
||||
@classmethod
|
||||
def collaborative_cancel(cls, order):
|
||||
if not order.status in [Order.Status.WFI, Order.Status.CHA]:
|
||||
if order.status not in [Order.Status.WFI, Order.Status.CHA]:
|
||||
return
|
||||
# cancel onchain payment if existing
|
||||
cls.cancel_onchain_payment(order)
|
||||
@ -1155,7 +1159,7 @@ class Logics:
|
||||
# Log a market tick
|
||||
try:
|
||||
MarketTick.log_a_tick(order)
|
||||
except:
|
||||
except Exception:
|
||||
pass
|
||||
send_message.delay(order.id, "order_taken_confirmed")
|
||||
return True
|
||||
@ -1366,7 +1370,7 @@ class Logics:
|
||||
|
||||
def return_bond(bond):
|
||||
"""returns a bond"""
|
||||
if bond == None:
|
||||
if bond is None:
|
||||
return
|
||||
try:
|
||||
LNNode.cancel_return_hold_invoice(bond.payment_hash)
|
||||
@ -1394,7 +1398,7 @@ class Logics:
|
||||
def cancel_bond(bond):
|
||||
"""cancel a bond"""
|
||||
# Same as return bond, but used when the invoice was never LOCKED
|
||||
if bond == None:
|
||||
if bond is None:
|
||||
return True
|
||||
try:
|
||||
LNNode.cancel_return_hold_invoice(bond.payment_hash)
|
||||
@ -1415,7 +1419,7 @@ class Logics:
|
||||
|
||||
# Pay to buyer invoice
|
||||
if not order.is_swap:
|
||||
##### Background process "follow_invoices" will try to pay this invoice until success
|
||||
# Background process "follow_invoices" will try to pay this invoice until success
|
||||
order.status = Order.Status.PAY
|
||||
order.payout.status = LNPayment.Status.FLIGHT
|
||||
order.payout.save()
|
||||
@ -1482,13 +1486,13 @@ class Logics:
|
||||
# RETURN THE BONDS
|
||||
cls.return_bond(order.taker_bond)
|
||||
cls.return_bond(order.maker_bond)
|
||||
##### !!! KEY LINE - PAYS THE BUYER INVOICE !!!
|
||||
# !!! KEY LINE - PAYS THE BUYER INVOICE !!!
|
||||
cls.pay_buyer(order)
|
||||
|
||||
# Add referral rewards (safe)
|
||||
try:
|
||||
cls.add_rewards(order)
|
||||
except:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return True, None
|
||||
@ -1535,12 +1539,12 @@ class Logics:
|
||||
# If the trade is finished
|
||||
if order.status in rating_allowed_status:
|
||||
# if maker, rates taker
|
||||
if order.maker == user and order.maker_rated == False:
|
||||
if order.maker == user and order.maker_rated is False:
|
||||
cls.add_profile_rating(order.taker.profile, rating)
|
||||
order.maker_rated = True
|
||||
order.save()
|
||||
# if taker, rates maker
|
||||
if order.taker == user and order.taker_rated == False:
|
||||
if order.taker == user and order.taker_rated is False:
|
||||
cls.add_profile_rating(order.maker.profile, rating)
|
||||
order.taker_rated = True
|
||||
order.save()
|
||||
@ -1617,7 +1621,7 @@ class Logics:
|
||||
expires_at=reward_payout["expires_at"],
|
||||
)
|
||||
# Might fail if payment_hash already exists in DB
|
||||
except:
|
||||
except Exception:
|
||||
return False, {"bad_invoice": "Give me a new invoice"}
|
||||
|
||||
user.profile.earned_rewards = 0
|
||||
@ -1645,7 +1649,7 @@ class Logics:
|
||||
Summarizes a finished order. Returns a dict with
|
||||
amounts, fees, costs, etc, for buyer and seller.
|
||||
"""
|
||||
if not order.status in [Order.Status.SUC, Order.Status.PAY, Order.Status.FAI]:
|
||||
if order.status not in [Order.Status.SUC, Order.Status.PAY, Order.Status.FAI]:
|
||||
return False, {"bad_summary": "Order has not finished yet"}
|
||||
|
||||
context = {}
|
||||
@ -1705,7 +1709,7 @@ class Logics:
|
||||
platform_summary["contract_exchange_rate"] = float(order.amount) / (
|
||||
float(order.last_satoshis) / 100000000
|
||||
)
|
||||
if order.last_satoshis_time != None:
|
||||
if order.last_satoshis_time is not None:
|
||||
platform_summary["contract_timestamp"] = order.last_satoshis_time
|
||||
platform_summary["contract_total_time"] = (
|
||||
order.contract_finalization_time - order.last_satoshis_time
|
||||
|
@ -1,4 +1,4 @@
|
||||
from django.core.management.base import BaseCommand, CommandError
|
||||
from django.core.management.base import BaseCommand
|
||||
|
||||
import time
|
||||
from api.models import Order
|
||||
|
@ -1,4 +1,4 @@
|
||||
from django.core.management.base import BaseCommand, CommandError
|
||||
from django.core.management.base import BaseCommand
|
||||
|
||||
from api.lightning.node import LNNode
|
||||
from api.tasks import follow_send_payment
|
||||
@ -84,7 +84,7 @@ class Command(BaseCommand):
|
||||
if hasattr(response, "htlcs"):
|
||||
try:
|
||||
hold_lnpayment.expiry_height = response.htlcs[0].expiry_height
|
||||
except:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
except Exception as e:
|
||||
|
@ -1,10 +1,9 @@
|
||||
from django.core.management.base import BaseCommand, CommandError
|
||||
from django.core.management.base import BaseCommand
|
||||
|
||||
from api.models import Profile
|
||||
from api.messages import Telegram
|
||||
from api.utils import get_session
|
||||
from decouple import config
|
||||
import requests
|
||||
import time
|
||||
|
||||
|
||||
@ -36,7 +35,7 @@ class Command(BaseCommand):
|
||||
|
||||
try: # if there is no key message, skips this result.
|
||||
text = result["message"]["text"]
|
||||
except:
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
splitted_text = text.split(" ")
|
||||
@ -44,7 +43,7 @@ class Command(BaseCommand):
|
||||
token = splitted_text[-1]
|
||||
try:
|
||||
profile = Profile.objects.get(telegram_token=token)
|
||||
except:
|
||||
except Exception:
|
||||
print(f"No profile with token {token}")
|
||||
continue
|
||||
|
||||
@ -59,7 +58,7 @@ class Command(BaseCommand):
|
||||
profile.telegram_enabled = True
|
||||
profile.save()
|
||||
break
|
||||
except:
|
||||
except Exception:
|
||||
time.sleep(5)
|
||||
attempts = attempts - 1
|
||||
|
||||
|
@ -18,7 +18,7 @@ class Telegram:
|
||||
else:
|
||||
context["tg_enabled"] = False
|
||||
|
||||
if user.profile.telegram_token == None:
|
||||
if user.profile.telegram_token is None:
|
||||
user.profile.telegram_token = token_urlsafe(15)
|
||||
user.profile.save()
|
||||
|
||||
@ -40,7 +40,7 @@ class Telegram:
|
||||
try:
|
||||
self.session.get(message_url).json()
|
||||
return
|
||||
except:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def welcome(self, user):
|
||||
|
@ -478,7 +478,7 @@ class Order(models.Model):
|
||||
taker_platform_rated = models.BooleanField(default=False, null=False)
|
||||
|
||||
def __str__(self):
|
||||
if self.has_range and self.amount == None:
|
||||
if self.has_range and self.amount is None:
|
||||
amt = str(float(self.min_amount)) + "-" + str(float(self.max_amount))
|
||||
else:
|
||||
amt = float(self.amount)
|
||||
@ -529,7 +529,7 @@ def delete_lnpayment_at_order_deletion(sender, instance, **kwargs):
|
||||
for lnpayment in to_delete:
|
||||
try:
|
||||
lnpayment.delete()
|
||||
except:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@ -640,7 +640,7 @@ class Profile(models.Model):
|
||||
settings.AVATAR_ROOT + instance.profile.avatar.url.split("/")[-1]
|
||||
)
|
||||
avatar_file.unlink()
|
||||
except:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def __str__(self):
|
||||
|
@ -34,7 +34,7 @@ def users_cleansing():
|
||||
if valid:
|
||||
deleted_users.append(str(user))
|
||||
user.delete()
|
||||
except:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
results = {
|
||||
@ -212,7 +212,7 @@ def payments_cleansing():
|
||||
name = str(lnpayment)
|
||||
lnpayment.delete()
|
||||
deleted_lnpayments.append(name)
|
||||
except:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# same for onchain payments
|
||||
@ -229,7 +229,7 @@ def payments_cleansing():
|
||||
name = str(onchainpayment)
|
||||
onchainpayment.delete()
|
||||
deleted_onchainpayments.append(name)
|
||||
except:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
results = {
|
||||
|
@ -1,3 +1,3 @@
|
||||
from django.test import TestCase
|
||||
# from django.test import TestCase
|
||||
|
||||
# Create your tests here.
|
||||
|
16
api/utils.py
16
api/utils.py
@ -1,8 +1,10 @@
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
|
||||
import numpy as np
|
||||
import requests, ring, logging
|
||||
import requests
|
||||
import ring
|
||||
from decouple import config
|
||||
|
||||
from api.models import Order
|
||||
@ -91,7 +93,7 @@ def get_exchange_rates(currencies):
|
||||
blockchain_rates.append(
|
||||
float(blockchain_prices[currency]["last"])
|
||||
)
|
||||
except:
|
||||
except Exception:
|
||||
blockchain_rates.append(np.nan)
|
||||
api_rates.append(blockchain_rates)
|
||||
|
||||
@ -101,10 +103,10 @@ def get_exchange_rates(currencies):
|
||||
for currency in currencies:
|
||||
try:
|
||||
yadio_rates.append(float(yadio_prices["BTC"][currency]))
|
||||
except:
|
||||
except Exception:
|
||||
yadio_rates.append(np.nan)
|
||||
api_rates.append(yadio_rates)
|
||||
except:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if len(api_rates) == 0:
|
||||
@ -123,7 +125,7 @@ def get_lnd_version():
|
||||
try:
|
||||
lnd_version = config("LND_VERSION")
|
||||
return lnd_version
|
||||
except:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# If not dockerized and LND is local, read from CLI
|
||||
@ -131,7 +133,7 @@ def get_lnd_version():
|
||||
stream = os.popen("lnd --version")
|
||||
lnd_version = stream.read()[:-1]
|
||||
return lnd_version
|
||||
except:
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
@ -145,7 +147,7 @@ def get_robosats_commit():
|
||||
commit_hash = commit.read()
|
||||
|
||||
# .git folder is included in .dockerignore. But automatic build will drop in a commit_sha.txt file on root
|
||||
if commit_hash == None or commit_hash == "":
|
||||
if commit_hash is None or commit_hash == "":
|
||||
with open("commit_sha.txt") as f:
|
||||
commit_hash = f.read()
|
||||
|
||||
|
30
api/views.py
30
api/views.py
@ -117,15 +117,15 @@ class MakerView(CreateAPIView):
|
||||
bondless_taker = serializer.data.get("bondless_taker")
|
||||
|
||||
# Optional params
|
||||
if public_duration == None:
|
||||
if public_duration is None:
|
||||
public_duration = PUBLIC_DURATION
|
||||
if escrow_duration == None:
|
||||
if escrow_duration is None:
|
||||
escrow_duration = ESCROW_DURATION
|
||||
if bond_size == None:
|
||||
if bond_size is None:
|
||||
bond_size = BOND_SIZE
|
||||
if bondless_taker == None:
|
||||
if bondless_taker is None:
|
||||
bondless_taker = False
|
||||
if has_range == None:
|
||||
if has_range is None:
|
||||
has_range = False
|
||||
|
||||
# TODO add a check - if `is_explicit` is true then `satoshis` need to be specified
|
||||
@ -138,14 +138,14 @@ class MakerView(CreateAPIView):
|
||||
max_amount = None
|
||||
|
||||
# Either amount or min_max has to be specified.
|
||||
if has_range and (min_amount == None or max_amount == None):
|
||||
if has_range and (min_amount is None or max_amount is None):
|
||||
return Response(
|
||||
{
|
||||
"bad_request": "You must specify min_amount and max_amount for a range order"
|
||||
},
|
||||
status.HTTP_400_BAD_REQUEST,
|
||||
)
|
||||
elif not has_range and amount == None:
|
||||
elif not has_range and amount is None:
|
||||
return Response(
|
||||
{"bad_request": "You must specify an order amount"},
|
||||
status.HTTP_400_BAD_REQUEST,
|
||||
@ -200,7 +200,7 @@ class OrderView(viewsets.ViewSet):
|
||||
status=status.HTTP_400_BAD_REQUEST,
|
||||
)
|
||||
|
||||
if order_id == None:
|
||||
if order_id is None:
|
||||
return Response(
|
||||
{"bad_request": "Order ID parameter not found in request"},
|
||||
status=status.HTTP_400_BAD_REQUEST,
|
||||
@ -260,9 +260,9 @@ class OrderView(viewsets.ViewSet):
|
||||
order.save()
|
||||
|
||||
# Add activity status of participants based on last_seen
|
||||
if order.taker_last_seen != None:
|
||||
if order.taker_last_seen is not None:
|
||||
data["taker_status"] = Logics.user_activity_status(order.taker_last_seen)
|
||||
if order.maker_last_seen != None:
|
||||
if order.maker_last_seen is not None:
|
||||
data["maker_status"] = Logics.user_activity_status(order.maker_last_seen)
|
||||
|
||||
# 3.b) Non participants can view details (but only if PUB)
|
||||
@ -415,11 +415,11 @@ class OrderView(viewsets.ViewSet):
|
||||
# add whether the dispute statement has been received
|
||||
if data["is_maker"]:
|
||||
data["statement_submitted"] = (
|
||||
order.maker_statement != None and order.maker_statement != ""
|
||||
order.maker_statement is not None and order.maker_statement != ""
|
||||
)
|
||||
elif data["is_taker"]:
|
||||
data["statement_submitted"] = (
|
||||
order.taker_statement != None and order.taker_statement != ""
|
||||
order.taker_statement is not None and order.taker_statement != ""
|
||||
)
|
||||
|
||||
# 9) If status is 'Failed routing', reply with retry amounts, time of next retry and ask for invoice at third.
|
||||
@ -690,7 +690,7 @@ class UserView(APIView):
|
||||
if bits_entropy < 128 or shannon_entropy < 0.7:
|
||||
context["bad_request"] = "The token does not have enough entropy"
|
||||
return Response(context, status=status.HTTP_400_BAD_REQUEST)
|
||||
except:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Hash the token_sha256, only 1 iteration. (this is the second SHA256 of the user token, aka RoboSats ID)
|
||||
@ -881,7 +881,7 @@ class InfoView(ListAPIView):
|
||||
status=Order.Status.PUB
|
||||
).aggregate(Sum("last_satoshis"))["last_satoshis__sum"]
|
||||
context["book_liquidity"] = (
|
||||
0 if context["book_liquidity"] == None else context["book_liquidity"]
|
||||
0 if context["book_liquidity"] is None else context["book_liquidity"]
|
||||
)
|
||||
|
||||
# Number of active users (logged in in last 30 minutes)
|
||||
@ -1002,7 +1002,7 @@ class PriceView(ListAPIView):
|
||||
"premium": last_tick.premium,
|
||||
"timestamp": last_tick.timestamp,
|
||||
}
|
||||
except:
|
||||
except Exception:
|
||||
payload[code] = None
|
||||
|
||||
return Response(payload, status.HTTP_200_OK)
|
||||
|
@ -2,7 +2,6 @@ from channels.generic.websocket import AsyncWebsocketConsumer
|
||||
from channels.db import database_sync_to_async
|
||||
from api.models import Order
|
||||
from chat.models import ChatRoom, Message
|
||||
from asgiref.sync import async_to_sync
|
||||
|
||||
import json
|
||||
|
||||
@ -12,7 +11,7 @@ class ChatRoomConsumer(AsyncWebsocketConsumer):
|
||||
def allow_in_chatroom(self):
|
||||
order = Order.objects.get(id=self.order_id)
|
||||
|
||||
if not order.status in [Order.Status.CHA, Order.Status.FSE]:
|
||||
if order.status not in [Order.Status.CHA, Order.Status.FSE]:
|
||||
print("Order is not in chat status")
|
||||
return False
|
||||
|
||||
@ -61,7 +60,7 @@ class ChatRoomConsumer(AsyncWebsocketConsumer):
|
||||
try:
|
||||
last_message = Message.objects.filter(order=order).latest()
|
||||
index = last_message.index + 1
|
||||
except:
|
||||
except Exception:
|
||||
index = 1
|
||||
|
||||
sender = self.scope["user"]
|
||||
|
@ -1,7 +1,6 @@
|
||||
from django.db import models
|
||||
from api.models import User, Order
|
||||
from django.utils import timezone
|
||||
import uuid
|
||||
|
||||
|
||||
class ChatRoom(models.Model):
|
||||
|
@ -37,7 +37,7 @@ def chatrooms_cleansing():
|
||||
chatroom = ChatRoom.objects.get(id=order.id)
|
||||
deleted_chatrooms.append(str(chatroom))
|
||||
chatroom.delete()
|
||||
except:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
results = {
|
||||
|
@ -1,3 +1,3 @@
|
||||
from django.test import TestCase
|
||||
# from django.test import TestCase
|
||||
|
||||
# Create your tests here.
|
||||
|
@ -1,6 +1,6 @@
|
||||
from django.urls import path
|
||||
# from django.urls import path
|
||||
|
||||
from . import views
|
||||
# from . import views
|
||||
|
||||
# urlpatterns = [
|
||||
# path('', views.index, name='index'),
|
||||
|
@ -1,4 +1,3 @@
|
||||
from operator import index
|
||||
from rest_framework import status, viewsets
|
||||
from chat.serializers import ChatSerializer, PostMessageSerializer
|
||||
from chat.models import Message, ChatRoom
|
||||
@ -41,7 +40,7 @@ class ChatView(viewsets.ViewSet):
|
||||
status.HTTP_400_BAD_REQUEST,
|
||||
)
|
||||
|
||||
if not order.status in [Order.Status.CHA, Order.Status.FSE]:
|
||||
if order.status not in [Order.Status.CHA, Order.Status.FSE]:
|
||||
return Response(
|
||||
{"bad_request": "Order is not in chat status"},
|
||||
status.HTTP_400_BAD_REQUEST,
|
||||
@ -111,7 +110,7 @@ class ChatView(viewsets.ViewSet):
|
||||
status.HTTP_400_BAD_REQUEST,
|
||||
)
|
||||
|
||||
if not order.status in [Order.Status.CHA, Order.Status.FSE]:
|
||||
if order.status not in [Order.Status.CHA, Order.Status.FSE]:
|
||||
return Response(
|
||||
{"bad_request": "Order is not in chat status"},
|
||||
status.HTTP_400_BAD_REQUEST,
|
||||
|
@ -21,15 +21,15 @@ def do_accounting():
|
||||
try:
|
||||
last_accounted_day = AccountingDay.objects.latest("day").day.date()
|
||||
accounted_yesterday = AccountingDay.objects.latest("day")
|
||||
except:
|
||||
except Exception:
|
||||
last_accounted_day = None
|
||||
accounted_yesterday = None
|
||||
|
||||
if last_accounted_day == today:
|
||||
return {"message": "no days to account for"}
|
||||
elif last_accounted_day != None:
|
||||
elif last_accounted_day is not None:
|
||||
initial_day = last_accounted_day + timedelta(days=1)
|
||||
elif last_accounted_day == None:
|
||||
elif last_accounted_day is None:
|
||||
initial_day = all_payments.earliest("created_at").created_at.date()
|
||||
|
||||
day = initial_day
|
||||
@ -54,11 +54,11 @@ def do_accounting():
|
||||
onchain_outflow = day_onchain_payments.filter(
|
||||
status__in=[OnchainPayment.Status.MEMPO, OnchainPayment.Status.CONFI]
|
||||
).aggregate(Sum("sent_satoshis"))["sent_satoshis__sum"]
|
||||
onchain_outflow = 0 if onchain_outflow == None else int(onchain_outflow)
|
||||
onchain_outflow = 0 if onchain_outflow is None else int(onchain_outflow)
|
||||
offchain_outflow = day_payments.filter(
|
||||
type=LNPayment.Types.NORM, status=LNPayment.Status.SUCCED
|
||||
).aggregate(Sum("num_satoshis"))["num_satoshis__sum"]
|
||||
offchain_outflow = 0 if offchain_outflow == None else int(offchain_outflow)
|
||||
offchain_outflow = 0 if offchain_outflow is None else int(offchain_outflow)
|
||||
routing_fees = day_payments.filter(
|
||||
type=LNPayment.Types.NORM, status=LNPayment.Status.SUCCED
|
||||
).aggregate(Sum("fee"))["fee__sum"]
|
||||
@ -71,12 +71,12 @@ def do_accounting():
|
||||
status=LNPayment.Status.SUCCED,
|
||||
).aggregate(Sum("num_satoshis"))["num_satoshis__sum"]
|
||||
|
||||
contracted = 0 if contracted == None else contracted
|
||||
inflow = 0 if inflow == None else inflow
|
||||
contracted = 0 if contracted is None else contracted
|
||||
inflow = 0 if inflow is None else inflow
|
||||
outflow = offchain_outflow + onchain_outflow
|
||||
routing_fees = 0 if routing_fees == None else routing_fees
|
||||
rewards_claimed = 0 if rewards_claimed == None else rewards_claimed
|
||||
mining_fees = 0 if mining_fees == None else mining_fees
|
||||
routing_fees = 0 if routing_fees is None else routing_fees
|
||||
rewards_claimed = 0 if rewards_claimed is None else rewards_claimed
|
||||
mining_fees = 0 if mining_fees is None else mining_fees
|
||||
|
||||
accounted_day = AccountingDay.objects.create(
|
||||
day=day,
|
||||
@ -154,7 +154,7 @@ def do_accounting():
|
||||
accounted_day.lifetime_rewards_claimed = Profile.objects.all().aggregate(
|
||||
Sum("claimed_rewards")
|
||||
)["claimed_rewards__sum"]
|
||||
if accounted_yesterday != None:
|
||||
if accounted_yesterday is not None:
|
||||
accounted_day.earned_rewards = (
|
||||
accounted_day.outstanding_earned_rewards
|
||||
- accounted_yesterday.outstanding_earned_rewards
|
||||
|
@ -1,3 +1,3 @@
|
||||
from django.test import TestCase
|
||||
# from django.test import TestCase
|
||||
|
||||
# Create your tests here.
|
||||
|
@ -1,3 +1,3 @@
|
||||
from django.shortcuts import render
|
||||
# from django.shortcuts import render
|
||||
|
||||
# Create your views here.
|
||||
|
@ -1,3 +1,3 @@
|
||||
from django.contrib import admin
|
||||
# from django.contrib import admin
|
||||
|
||||
# Register your models here.
|
||||
|
@ -1,3 +1,3 @@
|
||||
from django.db import models
|
||||
# from django.db import models
|
||||
|
||||
# Create your models here.
|
||||
|
@ -1,3 +1,3 @@
|
||||
from django.test import TestCase
|
||||
# from django.test import TestCase
|
||||
|
||||
# Create your tests here.
|
||||
|
@ -11,10 +11,13 @@ https://docs.djangoproject.com/en/4.0/ref/settings/
|
||||
"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import textwrap
|
||||
from pathlib import Path
|
||||
|
||||
from decouple import config
|
||||
|
||||
from .celery.conf import * # noqa
|
||||
|
||||
# Build paths inside the project like this: BASE_DIR / 'subdir'.
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
|
||||
@ -131,7 +134,6 @@ SPECTACULAR_SETTINGS = {
|
||||
"REDOC_DIST": "SIDECAR",
|
||||
}
|
||||
|
||||
from .celery.conf import *
|
||||
|
||||
MIDDLEWARE = [
|
||||
"django.middleware.security.SecurityMiddleware",
|
||||
|
Loading…
Reference in New Issue
Block a user