Skip to content

Commit

Permalink
Refactor and added docstring to task functions
Browse files Browse the repository at this point in the history
  • Loading branch information
imsudonym committed Jan 21, 2025
1 parent 5211e84 commit c9d0fd5
Show file tree
Hide file tree
Showing 21 changed files with 365 additions and 208 deletions.
5 changes: 5 additions & 0 deletions rampp2p/serializers/serializer_ad.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,11 @@ def get_appeal_cooldown(self, obj):
return str(obj.appeal_cooldown_choice)

class BaseAdSerializer(serializers.ModelSerializer):
"""
Base serializer for ads.
This serializer provides the base fields and methods for serializing ad data.
"""
fiat_currency = FiatCurrencySerializer()
crypto_currency = CryptoCurrencySerializer()
appeal_cooldown = serializers.SerializerMethodField()
Expand Down
14 changes: 3 additions & 11 deletions rampp2p/serializers/serializer_appeal.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,5 @@
from rest_framework import serializers
from django.db.models import Q
# from rampp2p.models import (
# Appeal,
# Peer,
# Order,
# Status,
# AdSnapshot,
# PriceType
# )
import rampp2p.models as models
import json

Expand All @@ -21,7 +13,7 @@ def to_representation(self, obj):
def to_internal_value(self, data):
return json.dumps(data)

class AppealCreateSerializer(serializers.ModelSerializer):
class BaseAppealSerializer(serializers.ModelSerializer):
owner = serializers.PrimaryKeyRelatedField(queryset=models.Peer.objects.all())
order = serializers.PrimaryKeyRelatedField(queryset=models.Order.objects.all())
reasons = ListTextField()
Expand All @@ -35,15 +27,15 @@ class Meta:
'reasons'
]

class AppealSerializer(AppealCreateSerializer):
class AppealSerializer(BaseAppealSerializer):
owner = serializers.SerializerMethodField()
type = serializers.SerializerMethodField()
order = serializers.SerializerMethodField()
read_at = serializers.SerializerMethodField()

class Meta:
model = models.Appeal
fields = AppealCreateSerializer.Meta.fields + [
fields = BaseAppealSerializer.Meta.fields + [
'resolved_at',
'created_at',
'read_at'
Expand Down
6 changes: 3 additions & 3 deletions rampp2p/serializers/serializer_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class Meta:
'address_path'
]

class ContractSerializer(serializers.ModelSerializer):
class BaseContractSerializer(serializers.ModelSerializer):
order = serializers.PrimaryKeyRelatedField(queryset=models.Order.objects.all())
class Meta:
model = models.Contract
Expand All @@ -25,14 +25,14 @@ class Meta:
'created_at'
]

class ContractDetailSerializer(ContractSerializer):
class ContractSerializer(BaseContractSerializer):
members = ContractMemberSerializer(many=True, read_only=True)
pubkeys = serializers.SerializerMethodField()
addresses = serializers.SerializerMethodField()
timestamp = serializers.SerializerMethodField()
class Meta:
model = models.Contract
fields = ContractSerializer.Meta.fields + [
fields = BaseContractSerializer.Meta.fields + [
'members',
'pubkeys',
'addresses',
Expand Down
56 changes: 25 additions & 31 deletions rampp2p/serializers/serializer_feedback.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,13 @@
from rest_framework import serializers
from rampp2p.models import (
Arbiter,
Peer,
Order,
OrderFeedback,
ArbiterFeedback
)
import rampp2p.models as models

class FeedbackCreateSerializer(serializers.ModelSerializer):
from_peer = serializers.PrimaryKeyRelatedField(queryset=Peer.objects.all())
to_peer = serializers.PrimaryKeyRelatedField(queryset=Peer.objects.all())
order = serializers.PrimaryKeyRelatedField(queryset=Order.objects.all())
from_peer = serializers.PrimaryKeyRelatedField(queryset=models.Peer.objects.all())
to_peer = serializers.PrimaryKeyRelatedField(queryset=models.Peer.objects.all())
order = serializers.PrimaryKeyRelatedField(queryset=models.Order.objects.all())

class Meta:
model = OrderFeedback
model = models.OrderFeedback
fields = [
"id",
"from_peer",
Expand All @@ -31,10 +25,10 @@ class Meta:
class FeedbackSerializer(serializers.ModelSerializer):
from_peer = serializers.SerializerMethodField()
to_peer = serializers.SerializerMethodField()
order = serializers.PrimaryKeyRelatedField(queryset=Order.objects.all())
order = serializers.PrimaryKeyRelatedField(queryset=models.Order.objects.all())

class Meta:
model = OrderFeedback
model = models.OrderFeedback
fields = [
"id",
"from_peer",
Expand All @@ -45,25 +39,25 @@ class Meta:
"created_at"
]

def get_from_peer(self, instance: OrderFeedback):
def get_from_peer(self, obj):
return {
'id': instance.from_peer.id,
'name': instance.from_peer.name
'id': obj.from_peer.id,
'name': obj.from_peer.name
}

def get_to_peer(self, instance: OrderFeedback):
def get_to_peer(self, obj):
return {
'id': instance.to_peer.id,
'name': instance.to_peer.name
'id': obj.to_peer.id,
'name': obj.to_peer.name
}

class ArbiterFeedbackCreateSerializer(serializers.ModelSerializer):
from_peer = serializers.PrimaryKeyRelatedField(queryset=Peer.objects.all())
to_arbiter = serializers.PrimaryKeyRelatedField(queryset=Arbiter.objects.all())
order = serializers.PrimaryKeyRelatedField(queryset=Order.objects.all())
from_peer = serializers.PrimaryKeyRelatedField(queryset=models.Peer.objects.all())
to_arbiter = serializers.PrimaryKeyRelatedField(queryset=models.Arbiter.objects.all())
order = serializers.PrimaryKeyRelatedField(queryset=models.Order.objects.all())

class Meta:
model = ArbiterFeedback
model = models.ArbiterFeedback
fields = [
"from_peer",
"to_arbiter",
Expand All @@ -76,10 +70,10 @@ class Meta:
class ArbiterFeedbackSerializer(serializers.ModelSerializer):
peer = serializers.SerializerMethodField()
arbiter = serializers.SerializerMethodField()
order = serializers.PrimaryKeyRelatedField(queryset=Order.objects.all())
order = serializers.PrimaryKeyRelatedField(queryset=models.Order.objects.all())

class Meta:
model = ArbiterFeedback
model = models.ArbiterFeedback
fields = [
"id",
"peer",
Expand All @@ -90,14 +84,14 @@ class Meta:
"created_at"
]

def get_peer(self, instance: ArbiterFeedback):
def get_peer(self, obj):
return {
'id': instance.from_peer.id,
'name': instance.from_peer.name
'id': obj.from_peer.id,
'name': obj.from_peer.name
}

def get_arbiter(self, instance: ArbiterFeedback):
def get_arbiter(self, obj):
return {
'id': instance.to_arbiter.id,
'name': instance.to_arbiter.name
'id': obj.to_arbiter.id,
'name': obj.to_arbiter.name
}
2 changes: 0 additions & 2 deletions rampp2p/serializers/serializer_order.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,6 @@ class WriteOrderSerializer(serializers.ModelSerializer):
ad_snapshot = serializers.PrimaryKeyRelatedField(required=True, queryset=models.AdSnapshot.objects.all())
owner = serializers.PrimaryKeyRelatedField(required=True, queryset=models.Peer.objects.all())
arbiter = serializers.PrimaryKeyRelatedField(queryset=models.Arbiter.objects.all(), required=False)
# locked_price = serializers.DecimalField(max_digits=10, decimal_places=2, required=True)
trade_amount = serializers.IntegerField(required=True)
payment_methods = serializers.PrimaryKeyRelatedField(queryset=models.PaymentMethod.objects.all(), required=False, many=True)
is_cash_in = serializers.BooleanField(required=True)
Expand All @@ -231,7 +230,6 @@ class Meta:
'ad_snapshot',
'owner',
'arbiter',
# 'locked_price',
'trade_amount',
'payment_methods',
'chat_session_ref',
Expand Down
26 changes: 0 additions & 26 deletions rampp2p/serializers/serializer_payment.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from rest_framework import serializers
import rampp2p.models as models
from django.db.models import Q

import logging
logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -49,35 +48,10 @@ def get_values(self, obj):
return PaymentMethodFieldSerializer(payment_method_fields, many=True).data

def get_dynamic_values(self, obj):
'''
dynamic_fields = []
if self.context and 'order_id' in self.context:
order_id = self.context['order_id']
logger.warn(f'get_dynamic_values[order_id]: {order_id}')
order = models.Order.objects.filter(id=order_id)
logger.warn(f'order.exists: {order.exists()}')
if not order.exists():
return dynamic_fields
order = order.first()
queryset = obj.payment_type.dynamic_fields.all()
for field in queryset:
value = None
if field.model_ref == models.DynamicPaymentTypeField.ModelRef.ORDER:
if field.field_ref == models.DynamicPaymentTypeField.FieldRef.ID:
value = order.id
if field.field_ref == models.DynamicPaymentTypeField.FieldRef.TRACKING_ID:
value = order.tracking_id
dynamic_fields.append({ 'fieldname': field.fieldname, 'value': value })
return dynamic_fields
'''
dynamic_fields = obj.payment_type.dynamic_fields.all()
serialized_data = DynamicPaymentTypeFieldSerializer(dynamic_fields, many=True)
return serialized_data.data


class RelatedPaymentMethodSerializer(serializers.ModelSerializer):
payment_type = serializers.SerializerMethodField()
class Meta:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,19 @@
logger = logging.getLogger(__name__)

@shared_task(queue='rampp2p__contract_execution')
def execute_subprocess(command, **kwargs):
def execute_subprocess(command):
"""
Executes a subprocess command.
This function runs a subprocess command and captures its output and error streams.
It also removes control characters from the JSON output.
Args:
command (str): The command to be executed.
Returns:
dict: A dictionary containing the result and stderr output of the command.
"""
# execute subprocess
logger.warning(f'executing: {command}')
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Expand Down Expand Up @@ -41,6 +53,21 @@ def execute_subprocess(command, **kwargs):

@shared_task(queue='rampp2p__contract_execution')
def contract_handler(response: Dict, **kwargs):
"""
Handles the contract creation response.
This function processes the response from the contract creation subprocess.
If the contract creation is successful, it updates the contract address and subscribes to it
for incoming/outgoing transactions.
It also sends the result through a websocket channel.
Args:
response (Dict): The response from the contract creation subprocess.
**kwargs: Additional keyword arguments, including the order ID.
Returns:
None
"""
data = response.get('result')
order_id = kwargs.get('order_id')
success = response.get('result').get('success')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,17 @@
import logging
logger = logging.getLogger(__name__)

@shared_task(queue='rampp2p__market_rates')
def update_market_rates():
@shared_task(queue='rampp2p__marketprices')
def update_market_prices():
"""
Updates the market prices for subscribed fiat currencies.
This function fetches the latest market prices for Bitcoin Cash (BCH) from CoinGecko and Fullstack.cash.
It updates the MarketPrice model with the fetched prices and sends the updated prices through a websocket channel.
Returns:
None
"""
# get subscribed fiat currencies
currencies = models.FiatCurrency.objects.all().values_list('symbol', flat=True)

Expand Down Expand Up @@ -39,13 +48,37 @@ def update_market_rates():
send_market_price(data, currency)

def get_latest_bch_prices_coingecko(currencies):
"""
Fetches the latest BCH prices from CoinGecko.
This function sends a request to the CoinGecko API to retrieve the latest BCH prices
for the specified fiat currencies.
Args:
currencies (list): A list of fiat currency symbols.
Returns:
dict: A dictionary containing the latest BCH prices for the specified currencies.
"""
coin_id = "bitcoin-cash"
query = { "ids": coin_id, "vs_currencies": ','.join(currencies) }
response = requests.get("https://api.coingecko.com/api/v3/simple/price/", params=query)
data = response.json()
return data.get(coin_id)

def get_latest_bch_prices_fullstackcash(currencies):
"""
Fetches the latest BCH prices from Fullstack.cash.
This function sends a request to the Fullstack.cash API to retrieve the latest BCH prices
for the specified fiat currencies.
Args:
currencies (list): A list of fiat currency symbols.
Returns:
dict: A dictionary containing the latest BCH prices for the specified currencies.
"""
response = requests.get("https://api.fullstack.cash/v5/price/rates")
data = response.json()

Expand Down
11 changes: 10 additions & 1 deletion rampp2p/tasks/order_tasks.py → rampp2p/tasks/task_order.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,16 @@

@shared_task(queue='rampp2p__cancel_expired_orders')
def cancel_expired_orders():
# find expired orders with status SUBMITTED
"""
Cancels expired orders with status SUBMITTED or CONFIRMED.
This function finds orders that have expired and updates their status to CANCELED.
It also marks the orders as read by all parties.
Returns:
None
"""
# find expired orders with status SUBMITTED or CONFIRMED
latest_status_subquery = Status.objects.filter(order=OuterRef('pk'),).order_by('-created_at').values('status')[:1]
queryset = Order.objects.annotate(latest_status=Subquery(latest_status_subquery))
target_orders = queryset.filter(
Expand Down
Loading

0 comments on commit c9d0fd5

Please sign in to comment.