Skip to content

Commit

Permalink
Add cancel_status to POST /api/order
Browse files Browse the repository at this point in the history
  • Loading branch information
aftermath2 committed Jun 17, 2024
1 parent 997e9ae commit eb692bd
Show file tree
Hide file tree
Showing 10 changed files with 97 additions and 10 deletions.
12 changes: 11 additions & 1 deletion api/logics.py
Original file line number Diff line number Diff line change
Expand Up @@ -991,7 +991,17 @@ def is_penalized(user):
return False, None

@classmethod
def cancel_order(cls, order, user, state=None):
def cancel_order(cls, order, user, cancel_status=None):
# If cancel status is specified, do no cancel the order
# if it is not the correct one.
# This prevents the client from cancelling an order that
# recently changed status.
if cancel_status is not None:
if order.status != cancel_status:
return False, {
"bad_request": f"Current order status is {order.status}, not {cancel_status}."
}

# Do not change order status if an is in order
# any of these status
do_not_cancel = [
Expand Down
4 changes: 4 additions & 0 deletions api/oas_schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,10 @@ class OrderViewSchema:
- `17` - Maker lost dispute
- `18` - Taker lost dispute
The client can use `cancel_status` to cancel the order only
if it is in the specified status. The server will
return an error without cancelling the trade otherwise.
Note that there are penalties involved for cancelling a order
mid-trade so use this action carefully:
Expand Down
7 changes: 7 additions & 0 deletions api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -628,6 +628,13 @@ class UpdateOrderSerializer(serializers.Serializer):
mining_fee_rate = serializers.DecimalField(
max_digits=6, decimal_places=3, allow_null=True, required=False, default=None
)
cancel_status = serializers.ChoiceField(
choices=Order.Status.choices,
allow_null=True,
allow_blank=True,
default=None,
help_text="Status the order should have for it to be cancelled.",
)


class ClaimRewardSerializer(serializers.Serializer):
Expand Down
3 changes: 2 additions & 1 deletion api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,7 @@ def take_update_confirm_dispute_cancel(self, request, format=None):
mining_fee_rate = serializer.data.get("mining_fee_rate")
statement = serializer.data.get("statement")
rating = serializer.data.get("rating")
cancel_status = serializer.data.get("cancel_status")

# 1) If action is take, it is a taker request!
if action == "take":
Expand Down Expand Up @@ -582,7 +583,7 @@ def take_update_confirm_dispute_cancel(self, request, format=None):

# 3) If action is cancel
elif action == "cancel":
valid, context = Logics.cancel_order(order, request.user)
valid, context = Logics.cancel_order(order, request.user, cancel_status)
if not valid:
return Response(context, status.HTTP_400_BAD_REQUEST)

Expand Down
3 changes: 3 additions & 0 deletions docs/assets/schemas/api-latest.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1950,6 +1950,9 @@ components:
format: decimal
pattern: ^-?\d{0,3}(?:\.\d{0,3})?$
nullable: true
cancel_status:
allOf:
- $ref: '#/components/schemas/StatusEnum'
required:
- action
Version:
Expand Down
18 changes: 13 additions & 5 deletions frontend/src/components/TradeBox/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ const TradeBox = ({ baseUrl, onStartAgain }: TradeBoxProps): JSX.Element => {
mining_fee_rate?: number;
statement?: string;
rating?: number;
cancel_status?: number;
}

const renewOrder = function (): void {
Expand Down Expand Up @@ -203,6 +204,7 @@ const TradeBox = ({ baseUrl, onStartAgain }: TradeBoxProps): JSX.Element => {
mining_fee_rate,
statement,
rating,
cancel_status
}: SubmitActionProps): void {
const robot = garage.getSlot()?.getRobot();
const currentOrder = garage.getSlot()?.order;
Expand All @@ -219,6 +221,7 @@ const TradeBox = ({ baseUrl, onStartAgain }: TradeBoxProps): JSX.Element => {
mining_fee_rate,
statement,
rating,
cancel_status
},
{ tokenSHA256: robot?.tokenSHA256 },
)
Expand All @@ -244,9 +247,14 @@ const TradeBox = ({ baseUrl, onStartAgain }: TradeBoxProps): JSX.Element => {
});
};

const cancel = function (): void {
const cancel = function (no_confirmation?: boolean) {
const currentOrder = garage.getSlot()?.order;

setLoadingButtons({ ...noLoadingButtons, cancel: true });
submitAction({ action: 'cancel' });
submitAction({
action: 'cancel',
cancel_status: no_confirmation ? currentOrder?.status : undefined
});
};

const openDispute = function (): void {
Expand Down Expand Up @@ -760,14 +768,14 @@ const TradeBox = ({ baseUrl, onStartAgain }: TradeBoxProps): JSX.Element => {
onClose={() => {
setOpen(closeAll);
}}
onCancelClick={cancel}
onCancelClick={() => cancel()}
/>
<ConfirmCollabCancelDialog
open={open.confirmCollabCancel}
onClose={() => {
setOpen(closeAll);
}}
onCollabCancelClick={cancel}
onCollabCancelClick={() => cancel()}
loading={loadingButtons.cancel}
peerAskedCancel={garage.getSlot()?.order?.pending_cancel ?? false}
/>
Expand Down Expand Up @@ -834,7 +842,7 @@ const TradeBox = ({ baseUrl, onStartAgain }: TradeBoxProps): JSX.Element => {
<Grid item>
<CancelButton
order={garage.getSlot()?.order ?? null}
onClickCancel={cancel}
onClickCancel={() => cancel(true)}
openCancelDialog={() => {
setOpen({ ...closeAll, confirmCancel: true });
}}
Expand Down
1 change: 0 additions & 1 deletion robosats/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
from django.utils.deprecation import MiddlewareMixin
from django.http import JsonResponse
from rest_framework.authtoken.models import Token
from rest_framework.exceptions import AuthenticationFailed

from api.nick_generator.nick_generator import NickGenerator
from api.utils import base91_to_hex, hex_to_base91, is_valid_token, validate_pgp_keys
Expand Down
3 changes: 3 additions & 0 deletions robosats/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,9 @@
}
},
"REDOC_DIST": "SIDECAR",
"ENUM_NAME_OVERRIDES": {
"StatusEnum": "api.models.order.Order.Status",
}
}


Expand Down
52 changes: 52 additions & 0 deletions tests/test_trade_pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -670,6 +670,58 @@ def test_cancel_public_order(self):
data["bad_request"], "This order has been cancelled by the maker"
)

def test_cancel_order_cancel_status(self):
"""
Tests the cancellation of a public order using cancel_status.
"""
trade = Trade(self.client)
trade.publish_order()
data = trade.response.json()

self.assertEqual(trade.response.status_code, 200)
self.assertResponse(trade.response)

self.assertEqual(data["status_message"], Order.Status(Order.Status.PUB).label)

# Cancel order if the order status is public
trade.cancel_order(cancel_status=Order.Status.PUB)

self.assertEqual(trade.response.status_code, 400)
self.assertResponse(trade.response)

self.assertEqual(
data["bad_request"], "This order has been cancelled by the maker"
)

def test_cancel_order_different_cancel_status(self):
"""
Tests the cancellation of a paused order with a different cancel_status.
"""
trade = Trade(self.client)
trade.publish_order()
trade.pause_order()
data = trade.response.json()

self.assertEqual(trade.response.status_code, 200)
self.assertResponse(trade.response)

self.assertEqual(data["status_message"], Order.Status(Order.Status.PAU).label)

# Try to cancel order if it is public
trade.cancel_order(cancel_status=Order.Status.PUB)
data = trade.response.json()

self.assertEqual(trade.response.status_code, 400)
self.assertResponse(trade.response)

self.assertEqual(
data["bad_request"],
f"Current order status is {Order.Status.PAU}, not {Order.Status.PUB}."
)

# Cancel order to avoid leaving pending HTLCs after a successful test
trade.cancel_order()

def test_collaborative_cancel_order_in_chat(self):
"""
Tests the collaborative cancellation of an order in the chat state
Expand Down
4 changes: 2 additions & 2 deletions tests/utils/trade.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,11 +112,11 @@ def get_order(self, robot_index=1, first_encounter=False):
self.response = self.client.get(path + params, **headers)

@patch("api.tasks.send_notification.delay", send_notification)
def cancel_order(self, robot_index=1):
def cancel_order(self, robot_index=1, cancel_status=None):
path = reverse("order")
params = f"?order_id={self.order_id}"
headers = self.get_robot_auth(robot_index)
body = {"action": "cancel"}
body = {"action": "cancel", "cancel_status": cancel_status}
self.response = self.client.post(path + params, body, **headers)

def pause_order(self, robot_index=1):
Expand Down

0 comments on commit eb692bd

Please sign in to comment.