Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions init

Large diffs are not rendered by default.

11 changes: 11 additions & 0 deletions postcss.configs.mjs

Large diffs are not rendered by default.

127 changes: 127 additions & 0 deletions src/components/common/LimitOrderForm.tsx
Original file line number Diff line number Diff line change
@@ -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<LimitOrderSide>('buy');
const [targetPrice, setTargetPrice] = useState('');
const [quantity, setQuantity] = useState('1');
const [expiresIn, setExpiresIn] = useState<LimitOrderExpiry>('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 (
<div className="space-y-4" data-testid="limit-order-form">
<Tabs
value={side}
onValueChange={value => setSide(value as LimitOrderSide)}
>
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="buy">Buy</TabsTrigger>
<TabsTrigger value="sell">Sell</TabsTrigger>
</TabsList>
</Tabs>
<div className="grid gap-3 sm:grid-cols-2">
<label className="space-y-1 text-sm text-white/70">
Target price
<Input
aria-label="Target price"
type="number"
min="0"
step="any"
value={targetPrice}
onChange={event => setTargetPrice(event.target.value)}
/>
</label>
<label className="space-y-1 text-sm text-white/70">
Quantity
<Input
aria-label="Quantity"
type="number"
min="1"
step="1"
value={quantity}
onChange={event => setQuantity(event.target.value)}
/>
</label>
</div>
<p className="text-xs text-white/55">Current price: {currentPrice}</p>
<label className="block space-y-1 text-sm text-white/70">
Expires in
<select
aria-label="Expires in"
value={expiresIn}
onChange={event =>
setExpiresIn(event.target.value as LimitOrderExpiry)
}
className="h-9 w-full rounded-md border border-white/10 bg-white/[0.04] px-3 text-sm text-white"
>
<option value="1h">1 hour</option>
<option value="24h">24 hours</option>
<option value="7d">7 days</option>
</select>
</label>
{priceError && (
<p role="alert" className="text-sm text-rose-300">
{priceError}
</p>
)}
{quantityError && (
<p role="alert" className="text-sm text-rose-300">
{quantityError}
</p>
)}
<Button
type="button"
onClick={submit}
disabled={isSubmitting}
className="w-full"
>
{isSubmitting ? 'Placing order…' : 'Place limit order'}
</Button>
</div>
);
}
75 changes: 75 additions & 0 deletions src/components/common/OpenOrdersTable.tsx
Original file line number Diff line number Diff line change
@@ -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 <p className="text-sm text-white/55">No open limit orders.</p>;
return (
<div className="overflow-x-auto">
<table className="w-full text-left text-sm">
<thead className="text-white/50">
<tr>
<th className="py-2">Side</th>
<th>Target</th>
<th>Quantity</th>
<th>Expires</th>
<th />
</tr>
</thead>
<tbody>
{activeOrders.map(order => (
<tr key={order.id} className="border-t border-white/10">
<td className="py-2 capitalize">{order.side}</td>
<td>{order.targetPrice}</td>
<td>{order.quantity}</td>
<td>{remaining(order.expiresAt, now)}</td>
<td className="text-right">
<Button
variant="outline"
size="sm"
disabled={isCancelling}
onClick={() => onCancel(order.id)}
>
Cancel
</Button>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
53 changes: 53 additions & 0 deletions src/hooks/useLimitOrders.ts
Original file line number Diff line number Diff line change
@@ -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<LimitOrder[]>({
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<CreateLimitOrderInput, 'creatorId' | 'walletAddress'>
) =>
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 ?? ''
),
}),
});
}
4 changes: 4 additions & 0 deletions src/lib/queryKeys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,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,
Expand Down
62 changes: 61 additions & 1 deletion src/pages/CreatorDetailPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,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';
import ShareQrModal from '@/components/common/ShareQrModal';
import { buildCreatorProfileReferralLink } from '@/utils/referral.utils';
import { QrCode } from 'lucide-react';
Expand Down Expand Up @@ -400,6 +407,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 || '',
Expand Down Expand Up @@ -886,10 +896,13 @@ function CreatorDetailPageContent() {

<div className="rounded-2xl border border-white/10 bg-white/[0.03] p-4 sm:p-5">
<Tabs defaultValue="buy" className="w-full">
<TabsList className="grid w-full grid-cols-2 bg-white/5 mb-4">
<TabsList className="grid w-full grid-cols-3 bg-white/5 mb-4">
<TabsTrigger value="buy" data-testid="invest-tab-buy">
Buy
</TabsTrigger>
<TabsTrigger value="limit" data-testid="invest-tab-limit">
Limit
</TabsTrigger>
<TabsTrigger
value="subscribe"
data-testid="invest-tab-subscribe"
Expand Down Expand Up @@ -1136,6 +1149,53 @@ function CreatorDetailPageContent() {
</div>
</TabsContent>

<TabsContent value="limit" className="space-y-6">
<div>
<p className="text-sm text-white/80">
Set a target price and your order will execute when
the market reaches it.
</p>
<div className="mt-4 max-w-xl">
<LimitOrderForm
currentPrice={
resolveCreatorKeyPriceStroops(creator) ?? 0
}
availableHoldings={holdingsCount}
isSubmitting={createLimitOrderMutation.isPending}
onSubmit={input => {
createLimitOrderMutation.mutate(input, {
onSuccess: () =>
showToast.success('Limit order placed'),
onError: error =>
showToast.error(
getSignatureErrorMessage(error)
),
});
}}
/>
</div>
</div>
<div className="border-t border-white/10 pt-4">
<h3 className="mb-3 text-sm font-semibold text-white">
Open orders
</h3>
<OpenOrdersTable
orders={limitOrdersQuery.data ?? []}
isCancelling={cancelLimitOrderMutation.isPending}
onCancel={orderId =>
cancelLimitOrderMutation.mutate(orderId, {
onSuccess: () =>
showToast.success('Limit order cancelled'),
onError: error =>
showToast.error(
getSignatureErrorMessage(error)
),
})
}
/>
</div>
</TabsContent>

<TabsContent value="subscribe" className="space-y-4">
<SubscriptionInvestmentPanel
creatorId={creator.id}
Expand Down
Loading
Loading