Skip to content

Commit

Permalink
Store status notifications
Browse files Browse the repository at this point in the history
  • Loading branch information
KoalaSat committed Aug 26, 2024
1 parent 27b8490 commit febb2c8
Show file tree
Hide file tree
Showing 12 changed files with 123 additions and 121 deletions.
6 changes: 2 additions & 4 deletions api/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from api.logics import Logics
from api.models import Currency, LNPayment, MarketTick, OnchainPayment, Order, Robot
from api.utils import objects_to_hyperlinks
from api.tasks import send_notification
from api.tasks import send_status_notification

admin.site.unregister(Group)
admin.site.unregister(User)
Expand Down Expand Up @@ -164,7 +164,7 @@ def cancel_public_order(self, request, queryset):
f"Order {order.id} successfully closed",
messages.SUCCESS,
)
send_notification.delay(
send_status_notification.delay(
order_id=order.id, message="coordinator_cancelled"
)
else:
Expand Down Expand Up @@ -210,7 +210,6 @@ def maker_wins(self, request, queryset):
f"Dispute of order {order.id} solved successfully on favor of the maker",
messages.SUCCESS,
)
send_notification.delay(order_id=order.id, message="dispute_closed")

else:
self.message_user(
Expand Down Expand Up @@ -249,7 +248,6 @@ def taker_wins(self, request, queryset):
f"Dispute of order {order.id} solved successfully on favor of the taker",
messages.SUCCESS,
)
send_notification.delay(order_id=order.id, message="dispute_closed")

else:
self.message_user(
Expand Down
63 changes: 26 additions & 37 deletions api/logics.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from api.lightning.node import LNNode
from api.models import Currency, LNPayment, MarketTick, OnchainPayment, Order
from api.tasks import send_devfund_donation, send_notification
from api.tasks import send_devfund_donation, send_status_notification
from api.utils import get_minning_fee, validate_onchain_address, location_country
from chat.models import Message

Expand Down Expand Up @@ -279,10 +279,9 @@ def order_expires(cls, order):

elif order.status in [Order.Status.PUB, Order.Status.PAU]:
cls.return_bond(order.maker_bond)
order.update_status(Order.Status.EXP)
order.expiry_reason = Order.ExpiryReasons.NTAKEN
order.save(update_fields=["expiry_reason"])
send_notification.delay(order_id=order.id, message="order_expired_untaken")
order.update_status(Order.Status.EXP)

order.log("Order expired while public or paused")
order.log("Maker bond was <b>unlocked</b>")
Expand Down Expand Up @@ -352,7 +351,9 @@ def order_expires(cls, order):
pass
taker_bond = order.taker_bond
cls.publish_order(order)
send_notification.delay(order_id=order.id, message="order_published")
send_status_notification.delay(
order_id=order.id, status=Order.Status.PUB
)
# Reward maker with part of the taker bond
cls.add_slashed_rewards(order, taker_bond, order.maker_bond)

Expand Down Expand Up @@ -389,7 +390,9 @@ def order_expires(cls, order):
cls.return_escrow(order)
taker_bond = order.taker_bond
cls.publish_order(order)
send_notification.delay(order_id=order.id, message="order_published")
send_status_notification.delay(
order_id=order.id, status=Order.Status.PUB
)
# Reward maker with part of the taker bond
cls.add_slashed_rewards(order, taker_bond, order.maker_bond)

Expand Down Expand Up @@ -498,7 +501,6 @@ def automatic_dispute_resolution(cls, order):
seconds=order.t_to_expire(Order.Status.DIS)
)
order.save(update_fields=["is_disputed", "expires_at"])
send_notification.delay(order_id=order.id, message="dispute_opened")

return True

Expand Down Expand Up @@ -548,7 +550,6 @@ def open_dispute(cls, order, user=None):
).append(str(order.id))
robot.save(update_fields=["num_disputes", "orders_disputes_started"])

send_notification.delay(order_id=order.id, message="dispute_opened")
order.log(
f"Dispute was opened {f'by Robot({user.robot.id},{user.username})' if user else ''}"
)
Expand Down Expand Up @@ -704,19 +705,19 @@ def payout_amount(cls, order, user):

if context["invoice_amount"] < MIN_SWAP_AMOUNT:
context["swap_allowed"] = False
context[
"swap_failure_reason"
] = f"Order amount is smaller than the minimum swap available of {MIN_SWAP_AMOUNT} Sats"
context["swap_failure_reason"] = (
f"Order amount is smaller than the minimum swap available of {MIN_SWAP_AMOUNT} Sats"
)
order.log(
f"Onchain payment option was not offered: amount is smaller than the minimum swap available of {MIN_SWAP_AMOUNT} Sats",
level="WARN",
)
return True, context
elif context["invoice_amount"] > MAX_SWAP_AMOUNT:
context["swap_allowed"] = False
context[
"swap_failure_reason"
] = f"Order amount is bigger than the maximum swap available of {MAX_SWAP_AMOUNT} Sats"
context["swap_failure_reason"] = (
f"Order amount is bigger than the maximum swap available of {MAX_SWAP_AMOUNT} Sats"
)
order.log(
f"Onchain payment option was not offered: amount is bigger than the maximum swap available of {MAX_SWAP_AMOUNT} Sats",
level="WARN",
Expand All @@ -741,9 +742,9 @@ def payout_amount(cls, order, user):
)
if not valid:
context["swap_allowed"] = False
context[
"swap_failure_reason"
] = "Not enough onchain liquidity available to offer a swap"
context["swap_failure_reason"] = (
"Not enough onchain liquidity available to offer a swap"
)
order.log(
"Onchain payment option was not offered: onchain liquidity available to offer a swap",
level="WARN",
Expand Down Expand Up @@ -948,7 +949,6 @@ def move_state_updated_payout_method(cls, order):
order.expires_at = timezone.now() + timedelta(
seconds=order.t_to_expire(Order.Status.CHA)
)
send_notification.delay(order_id=order.id, message="fiat_exchange_starts")

# If the order status is 'Waiting for both'. Move forward to 'waiting for escrow'
elif order.status == Order.Status.WF2:
Expand All @@ -962,9 +962,7 @@ def move_state_updated_payout_method(cls, order):
order.expires_at = timezone.now() + timedelta(
seconds=order.t_to_expire(Order.Status.CHA)
)
send_notification.delay(
order_id=order.id, message="fiat_exchange_starts"
)
order.update_status(Order.Status.CHA)
else:
order.update_status(Order.Status.WFE)

Expand Down Expand Up @@ -1032,10 +1030,6 @@ def cancel_order(cls, order, user, state=None):
# Return the maker bond (Maker gets returned the bond for cancelling public order)
if cls.return_bond(order.maker_bond):
order.update_status(Order.Status.UCA)
send_notification.delay(
order_id=order.id, message="public_order_cancelled"
)

order.log("Order cancelled by maker while public or paused")
order.log("Maker bond was <b>unlocked</b>")

Expand All @@ -1050,9 +1044,6 @@ def cancel_order(cls, order, user, state=None):
if cls.return_bond(order.maker_bond):
cls.cancel_bond(order.taker_bond)
order.update_status(Order.Status.UCA)
send_notification.delay(
order_id=order.id, message="public_order_cancelled"
)

order.log("Order cancelled by maker before the taker locked the bond")
order.log("Maker bond was <b>unlocked</b>")
Expand Down Expand Up @@ -1113,7 +1104,9 @@ def cancel_order(cls, order, user, state=None):
if valid:
taker_bond = order.taker_bond
cls.publish_order(order)
send_notification.delay(order_id=order.id, message="order_published")
send_status_notification.delay(
order_id=order.id, status=Order.Status.PUB
)
# Reward maker with part of the taker bond
cls.add_slashed_rewards(order, taker_bond, order.maker_bond)

Expand Down Expand Up @@ -1179,7 +1172,6 @@ def collaborative_cancel(cls, order):
cls.return_bond(order.taker_bond)
cls.return_escrow(order)
order.update_status(Order.Status.CCA)
send_notification.delay(order_id=order.id, message="collaborative_cancelled")

order.log("Order was collaboratively cancelled")
order.log("Maker bond was <b>unlocked</b>")
Expand All @@ -1190,7 +1182,7 @@ def collaborative_cancel(cls, order):

@classmethod
def publish_order(cls, order):
order.status = Order.Status.PUB
order.update_status(Order.Status.PUB)
order.expires_at = order.created_at + timedelta(
seconds=order.t_to_expire(Order.Status.PUB)
)
Expand Down Expand Up @@ -1322,7 +1314,6 @@ def finalize_contract(cls, order):
order.expires_at = timezone.now() + timedelta(
seconds=order.t_to_expire(Order.Status.WF2)
)
order.status = Order.Status.WF2
order.save(
update_fields=[
"status",
Expand All @@ -1349,7 +1340,7 @@ def finalize_contract(cls, order):
)
except Exception:
pass
send_notification.delay(order_id=order.id, message="order_taken_confirmed")
order.update_status(Order.Status.WF2)
order.log(
f"<b>Contract formalized.</b> Maker: Robot({order.maker.robot.id},{order.maker}). Taker: Robot({order.taker.robot.id},{order.taker}). API median price {order.currency.exchange_rate} {dict(Currency.currency_choices)[order.currency.currency]}/BTC. Premium is {order.premium}%. Contract size {order.last_satoshis} Sats"
)
Expand Down Expand Up @@ -1451,7 +1442,7 @@ def trade_escrow_received(order):
seconds=order.t_to_expire(Order.Status.CHA)
)
order.save(update_fields=["expires_at"])
send_notification.delay(order_id=order.id, message="fiat_exchange_starts")
order.update_status(Order.Status.CHA)

@classmethod
def gen_escrow_hold_invoice(cls, order, user):
Expand Down Expand Up @@ -1619,11 +1610,10 @@ def pay_buyer(cls, order):
order.payout.status = LNPayment.Status.FLIGHT
order.payout.save(update_fields=["status"])

order.update_status(Order.Status.PAY)
order.contract_finalization_time = timezone.now()
order.save(update_fields=["contract_finalization_time"])
order.update_status(Order.Status.PAY)

send_notification.delay(order_id=order.id, message="trade_successful")
order.log("<b>Paying buyer invoice</b>")
return True

Expand All @@ -1636,11 +1626,10 @@ def pay_buyer(cls, order):
order.payout_tx.status = OnchainPayment.Status.QUEUE
order.payout_tx.save(update_fields=["status"])

order.update_status(Order.Status.SUC)
order.contract_finalization_time = timezone.now()
order.save(update_fields=["contract_finalization_time"])
order.update_status(Order.Status.SUC)

send_notification.delay(order_id=order.id, message="trade_successful")
order.log("<b>Paying buyer onchain address</b>")
return True

Expand Down
6 changes: 3 additions & 3 deletions api/management/commands/follow_invoices.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from api.lightning.node import LNNode
from api.logics import Logics
from api.models import LNPayment, OnchainPayment, Order
from api.tasks import follow_send_payment, send_notification
from api.tasks import follow_send_payment, send_status_notification


def is_same_status(a: LNPayment.Status, b: LNPayment.Status) -> bool:
Expand Down Expand Up @@ -229,8 +229,8 @@ def update_order_status(self, lnpayment):
if hasattr(lnpayment, "order_made"):
lnpayment.order_made.log("Maker bond <b>locked</b>")
Logics.publish_order(lnpayment.order_made)
send_notification.delay(
order_id=lnpayment.order_made.id, message="order_published"
send_status_notification.delay(
order_id=lnpayment.order_made.id, status=Order.Status.PUB
)
return

Expand Down
7 changes: 3 additions & 4 deletions api/management/commands/telegram_watcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
from django.db import transaction

from api.models import Robot
from api.notifications import Notifications
from api.utils import get_session
from api.tasks import send_telegram_notification


class Command(BaseCommand):
Expand All @@ -17,7 +17,6 @@ class Command(BaseCommand):
bot_token = config("TELEGRAM_TOKEN")
updates_url = f"https://api.telegram.org/bot{bot_token}/getUpdates"
session = get_session()
notifications = Notifications()

def handle(self, *args, **options):
offset = 0
Expand Down Expand Up @@ -49,15 +48,15 @@ def handle(self, *args, **options):
continue
parts = message.split(" ")
if len(parts) < 2:
self.notifications.send_telegram_message(
send_telegram_notification.delay(
result["message"]["from"]["id"],
'You must enable the notifications bot using the RoboSats client. Click on your "Robot robot" -> "Enable Telegram" and follow the link or scan the QR code.',
)
continue
token = parts[-1]
robot = Robot.objects.filter(telegram_token=token).first()
if not robot:
self.notifications.send_telegram_message(
send_telegram_notification.delay(
result["message"]["from"]["id"],
f'Wops, invalid token! There is no Robot with telegram chat token "{token}"',
)
Expand Down
5 changes: 2 additions & 3 deletions api/models/order.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from django.utils import timezone
from api.tasks import send_notification
from api.tasks import send_status_notification

if config("TESTING", cast=bool, default=False):
import random
Expand Down Expand Up @@ -350,8 +350,7 @@ def update_status(self, new_status):
self.log(
f"Order state went from {old_status}: <i>{Order.Status(old_status).label}</i> to {new_status}: <i>{Order.Status(new_status).label}</i>"
)
if new_status == Order.Status.FAI:
send_notification.delay(order_id=self.id, message="lightning_failed")
send_status_notification.delay(order_id=self.id, status=self.status)


@receiver(pre_delete, sender=Order)
Expand Down
17 changes: 12 additions & 5 deletions api/notifications.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,18 @@ def send_telegram_message(self, chat_id, title, description=""):
except Exception:
pass

def status_change(self, order):
Notification.objects.create(
title="", description="", robot=order.maker.robot, order=order
)

if order.taker:
Notification.objects.create(
title="", description="", robot=order.taker.robot, order=order
)

return

def welcome(self, user):
"""User enabled Telegram Notifications"""
lang = user.robot.telegram_lang_code
Expand Down Expand Up @@ -215,11 +227,6 @@ def new_chat_message(self, order, chat_message):

return

def coordinator_cancelled(self, order):
title = f"🛠️ Your order with ID {order.id} has been cancelled by the coordinator {config('COORDINATOR_ALIAS', cast=str, default='NoAlias')} for the upcoming maintenance stop."
self.send_message(order, order.maker.robot, title)
return

def dispute_closed(self, order):
lang = order.maker.robot.telegram_lang_code
if order.status == Order.Status.MLD:
Expand Down
Loading

0 comments on commit febb2c8

Please sign in to comment.