From 98ed65304289f1a189d36828215ba7ff9c8cc081 Mon Sep 17 00:00:00 2001 From: damilare0813 Date: Thu, 19 Nov 2026 23:01:26 +0100 Subject: [PATCH] feat(trading): add limit order flows (closes #1301) --- src/components/common/LimitOrderForm.tsx | 127 +++++++++++++++++++ src/components/common/OpenOrdersTable.tsx | 75 +++++++++++ src/hooks/useLimitOrders.ts | 53 ++++++++ src/lib/queryKeys.ts | 4 + src/pages/CreatorDetailPage.tsx | 47 ++++++- src/services/orders.ts | 72 +++++++++++ src/utils/__tests__/limitOrder.utils.test.ts | 17 +++ src/utils/limitOrder.utils.ts | 21 +++ 8 files changed, 415 insertions(+), 1 deletion(-) create mode 100644 src/components/common/LimitOrderForm.tsx create mode 100644 src/components/common/OpenOrdersTable.tsx create mode 100644 src/hooks/useLimitOrders.ts create mode 100644 src/services/orders.ts create mode 100644 src/utils/__tests__/limitOrder.utils.test.ts create mode 100644 src/utils/limitOrder.utils.ts diff --git a/src/components/common/LimitOrderForm.tsx b/src/components/common/LimitOrderForm.tsx new file mode 100644 index 00000000..765fec83 --- /dev/null +++ b/src/components/common/LimitOrderForm.tsx @@ -0,0 +1,127 @@ +import { useState } from 'react'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'; +import type { LimitOrderExpiry, LimitOrderSide } from '@/services/orders'; +import { validateLimitOrderPrice } from '@/utils/limitOrder.utils'; + +interface LimitOrderFormProps { + currentPrice: number; + availableHoldings: number; + isSubmitting?: boolean; + onSubmit: (input: { + side: LimitOrderSide; + targetPrice: number; + quantity: number; + expiresIn: LimitOrderExpiry; + }) => void; +} + +export default function LimitOrderForm({ + currentPrice, + availableHoldings, + isSubmitting, + onSubmit, +}: LimitOrderFormProps) { + const [side, setSide] = useState('buy'); + const [targetPrice, setTargetPrice] = useState(''); + const [quantity, setQuantity] = useState('1'); + const [expiresIn, setExpiresIn] = useState('24h'); + const [touched, setTouched] = useState(false); + const priceError = touched + ? validateLimitOrderPrice(side, Number(targetPrice), currentPrice) + : null; + const quantityValue = Number(quantity); + const quantityError = + touched && + (!Number.isInteger(quantityValue) || + quantityValue <= 0 || + (side === 'sell' && quantityValue > availableHoldings)) + ? side === 'sell' && quantityValue > availableHoldings + ? 'Quantity exceeds your holdings.' + : 'Enter a whole quantity greater than zero.' + : null; + + function submit() { + setTouched(true); + if (priceError || quantityError || !targetPrice) return; + onSubmit({ + side, + targetPrice: Number(targetPrice), + quantity: quantityValue, + expiresIn, + }); + } + + return ( +
+ setSide(value as LimitOrderSide)} + > + + Buy + Sell + + +
+ + +
+

Current price: {currentPrice}

+ + {priceError && ( +

+ {priceError} +

+ )} + {quantityError && ( +

+ {quantityError} +

+ )} + +
+ ); +} diff --git a/src/components/common/OpenOrdersTable.tsx b/src/components/common/OpenOrdersTable.tsx new file mode 100644 index 00000000..55de0758 --- /dev/null +++ b/src/components/common/OpenOrdersTable.tsx @@ -0,0 +1,75 @@ +import { useEffect, useState } from 'react'; +import { Button } from '@/components/ui/button'; +import type { LimitOrder } from '@/services/orders'; + +function remaining(expiresAt: string, now: number) { + const seconds = Math.max( + 0, + Math.ceil((new Date(expiresAt).getTime() - now) / 1000) + ); + if (seconds === 0) return 'Expired'; + const days = Math.floor(seconds / 86400); + const hours = Math.floor((seconds % 86400) / 3600); + const minutes = Math.floor((seconds % 3600) / 60); + return days + ? `${days}d ${hours}h` + : hours + ? `${hours}h ${minutes}m` + : `${minutes}m`; +} + +export default function OpenOrdersTable({ + orders, + onCancel, + isCancelling, +}: { + orders: LimitOrder[]; + onCancel: (id: string) => void; + isCancelling?: boolean; +}) { + const [now, setNow] = useState(() => Date.now()); + useEffect(() => { + const timer = window.setInterval(() => setNow(Date.now()), 30_000); + return () => window.clearInterval(timer); + }, []); + const activeOrders = orders.filter( + order => new Date(order.expiresAt).getTime() > now + ); + if (!activeOrders.length) + return

No open limit orders.

; + return ( +
+ + + + + + + + + + + {activeOrders.map(order => ( + + + + + + + + ))} + +
SideTargetQuantityExpires +
{order.side}{order.targetPrice}{order.quantity}{remaining(order.expiresAt, now)} + +
+
+ ); +} diff --git a/src/hooks/useLimitOrders.ts b/src/hooks/useLimitOrders.ts new file mode 100644 index 00000000..38dbf88b --- /dev/null +++ b/src/hooks/useLimitOrders.ts @@ -0,0 +1,53 @@ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import { queryKeys } from '@/lib/queryKeys'; +import { + cancelLimitOrder, + createLimitOrder, + listOpenOrders, + type CreateLimitOrderInput, + type LimitOrder, +} from '@/services/orders'; + +export function useLimitOrders(creatorId: string, walletAddress?: string) { + return useQuery({ + queryKey: queryKeys.limitOrders.list(creatorId, walletAddress ?? ''), + queryFn: () => listOpenOrders(creatorId, walletAddress!), + enabled: Boolean(creatorId && walletAddress), + refetchInterval: 30_000, + }); +} + +export function useCreateLimitOrder(creatorId: string, walletAddress?: string) { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: ( + input: Omit + ) => + createLimitOrder({ + ...input, + creatorId, + walletAddress: walletAddress!, + }), + onSuccess: () => + queryClient.invalidateQueries({ + queryKey: queryKeys.limitOrders.list( + creatorId, + walletAddress ?? '' + ), + }), + }); +} + +export function useCancelLimitOrder(creatorId: string, walletAddress?: string) { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: (orderId: string) => cancelLimitOrder(orderId), + onSuccess: () => + queryClient.invalidateQueries({ + queryKey: queryKeys.limitOrders.list( + creatorId, + walletAddress ?? '' + ), + }), + }); +} diff --git a/src/lib/queryKeys.ts b/src/lib/queryKeys.ts index aac480b6..4c12998f 100644 --- a/src/lib/queryKeys.ts +++ b/src/lib/queryKeys.ts @@ -238,6 +238,10 @@ export const queryKeys = { history: (address: string) => ['atomic-swap', 'history', address] as const, }, + limitOrders: { + list: (creatorId: string, walletAddress: string) => + ['limitOrders', creatorId, walletAddress] as const, + }, bundles: { all: (creatorId: string) => ['bundles', creatorId] as const, list: (creatorId: string) => ['bundles', creatorId, 'list'] as const, diff --git a/src/pages/CreatorDetailPage.tsx b/src/pages/CreatorDetailPage.tsx index ad92e0c1..3d0bb407 100644 --- a/src/pages/CreatorDetailPage.tsx +++ b/src/pages/CreatorDetailPage.tsx @@ -138,6 +138,13 @@ import { useAccount } from 'wagmi'; import { useKeyMarketMaker } from '@/hooks/useKeyMarketMaker'; import { MarketMakerChip, MMBadge } from '@/components/common/MarketMakerChip'; import ReportKeyModal from '@/components/common/ReportKeyModal'; +import LimitOrderForm from '@/components/common/LimitOrderForm'; +import OpenOrdersTable from '@/components/common/OpenOrdersTable'; +import { + useCancelLimitOrder, + useCreateLimitOrder, + useLimitOrders, +} from '@/hooks/useLimitOrders'; /** Series shown in the key detail price panel (#1220 adds the depth tab). */ type PriceChartTab = 'primary' | 'secondary' | 'depth' | 'revenue'; @@ -399,6 +406,9 @@ function CreatorDetailPageContent() { ); const tradeMutation = useTradeMutation(connectedWalletAddress ?? ''); + const limitOrdersQuery = useLimitOrders(id || '', userAddress); + const createLimitOrderMutation = useCreateLimitOrder(id || '', userAddress); + const cancelLimitOrderMutation = useCancelLimitOrder(id || '', userAddress); const { data: tradeCooldownStatus } = useTradeCooldownStatus( id || '', @@ -873,10 +883,13 @@ function CreatorDetailPageContent() {
- + Buy + + Limit + Subscribe @@ -1106,6 +1119,38 @@ function CreatorDetailPageContent() {
+ +
+

+ Set a target price and your order will execute when the market reaches it. +

+
+ { + createLimitOrderMutation.mutate(input, { + onSuccess: () => showToast.success('Limit order placed'), + onError: error => showToast.error(getSignatureErrorMessage(error)), + }); + }} + /> +
+
+
+

Open orders

+ cancelLimitOrderMutation.mutate(orderId, { + onSuccess: () => showToast.success('Limit order cancelled'), + onError: error => showToast.error(getSignatureErrorMessage(error)), + })} + /> +
+
+ { + try { + const response = await this.api.post>( + '/orders', + input + ); + return response.data.data; + } catch (error) { + throw this.handleError(error); + } + } + + async cancelLimitOrder(orderId: string): Promise { + try { + await this.api.delete(`/orders/${encodeURIComponent(orderId)}`); + } catch (error) { + throw this.handleError(error); + } + } + + async listOpenOrders( + creatorId: string, + walletAddress: string + ): Promise { + try { + const response = await this.api.get>( + '/orders', + { + params: { creatorId, walletAddress, status: 'open' }, + } + ); + return Array.isArray(response.data.data) ? response.data.data : []; + } catch (error) { + throw this.handleError(error); + } + } +} + +export const ordersService = new OrdersService(); + +export const createLimitOrder = (input: CreateLimitOrderInput) => + ordersService.createLimitOrder(input); +export const cancelLimitOrder = (orderId: string) => + ordersService.cancelLimitOrder(orderId); +export const listOpenOrders = (creatorId: string, walletAddress: string) => + ordersService.listOpenOrders(creatorId, walletAddress); diff --git a/src/utils/__tests__/limitOrder.utils.test.ts b/src/utils/__tests__/limitOrder.utils.test.ts new file mode 100644 index 00000000..0160f281 --- /dev/null +++ b/src/utils/__tests__/limitOrder.utils.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from 'vitest'; +import { validateLimitOrderPrice } from '../limitOrder.utils'; + +describe('validateLimitOrderPrice', () => { + it('rejects a buy at or above the current price', () => { + expect(validateLimitOrderPrice('buy', 10, 10)).toMatch(/below/); + expect(validateLimitOrderPrice('buy', 11, 10)).toMatch(/below/); + }); + it('rejects a sell at or below the current price', () => { + expect(validateLimitOrderPrice('sell', 10, 10)).toMatch(/above/); + expect(validateLimitOrderPrice('sell', 9, 10)).toMatch(/above/); + }); + it('accepts targets on the correct side of the market', () => { + expect(validateLimitOrderPrice('buy', 9, 10)).toBeNull(); + expect(validateLimitOrderPrice('sell', 11, 10)).toBeNull(); + }); +}); diff --git a/src/utils/limitOrder.utils.ts b/src/utils/limitOrder.utils.ts new file mode 100644 index 00000000..6bc91619 --- /dev/null +++ b/src/utils/limitOrder.utils.ts @@ -0,0 +1,21 @@ +import type { LimitOrderSide } from '@/services/orders'; + +export function validateLimitOrderPrice( + side: LimitOrderSide, + targetPrice: number, + currentPrice: number +): string | null { + if (!Number.isFinite(targetPrice) || targetPrice <= 0) { + return 'Enter a target price greater than zero.'; + } + if (!Number.isFinite(currentPrice) || currentPrice <= 0) { + return 'The current price is unavailable.'; + } + if (side === 'buy' && targetPrice >= currentPrice) { + return 'Buy target price must be below the current price.'; + } + if (side === 'sell' && targetPrice <= currentPrice) { + return 'Sell target price must be above the current price.'; + } + return null; +}