-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathbuy-fractional-order-form.tsx
More file actions
280 lines (254 loc) · 8.2 KB
/
Copy pathbuy-fractional-order-form.tsx
File metadata and controls
280 lines (254 loc) · 8.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import { FormattedUnits } from "@/components/formatted-units";
import { Button } from "@/components/ui/button";
import {
Form,
FormControl,
FormField,
FormItem,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import {
DEFAULT_NUM_UNITS,
DEFAULT_NUM_UNITS_DECIMALS,
} from "@/configs/hypercerts";
import { HypercertFull } from "@/hypercerts/fragments/hypercert-full.fragment";
import { calculateBigIntPercentage } from "@/lib/calculateBigIntPercentage";
import { useBuyFractionalMakerAsk } from "@/marketplace/hooks";
import { MarketplaceOrder } from "@/marketplace/types";
import {
decodeFractionalOrderParams,
formatPrice,
getCurrencyByAddress,
getPricePerPercent,
getPricePerUnit,
} from "@/marketplace/utils";
import { zodResolver } from "@hookform/resolvers/zod";
import { parseClaimOrFractionId } from "@hypercerts-org/sdk";
import { useForm } from "react-hook-form";
import { parseUnits } from "viem";
import z from "zod";
const formSchema = z
.object({
percentageAmount: z.string(),
maxPercentageAmount: z.string(),
minPercentageAmount: z.string(),
pricePerPercent: z.string(),
minPricePerPercent: z.string(),
})
.superRefine((data, ctx) => {
if (!(Number(data.percentageAmount) <= Number(data.maxPercentageAmount))) {
ctx.addIssue({
path: ["percentageAmount"],
message: "Must be less than max percentage",
code: z.ZodIssueCode.custom,
});
}
})
.superRefine((data, ctx) => {
if (!(Number(data.percentageAmount) >= Number(data.minPercentageAmount))) {
ctx.addIssue({
path: ["percentageAmount"],
message: "Must be more than min percentage",
code: z.ZodIssueCode.custom,
});
}
})
.superRefine((data, ctx) => {
if (!(Number(data.pricePerPercent) >= Number(data.minPricePerPercent))) {
ctx.addIssue({
path: ["pricePerPercent"],
message: "Must be more than min price",
code: z.ZodIssueCode.custom,
});
}
});
export type BuyFractionalOrderFormValues = z.infer<typeof formSchema>;
export const BuyFractionalOrderForm = ({
order,
hypercert,
onBuyOrder,
onCompleted,
}: {
order: MarketplaceOrder;
hypercert: HypercertFull;
onBuyOrder: (orderId: string) => void;
onCompleted?: () => void;
}) => {
const { minUnitAmount, maxUnitAmount, minUnitsToKeep } =
decodeFractionalOrderParams(order.additionalParameters);
const fractionTokenId = BigInt(order.itemIds[0]);
const fraction = hypercert.fractions?.data?.find(
(fraction) =>
parseClaimOrFractionId(fraction.fraction_id || "").id === fractionTokenId,
);
const fractionUnits = BigInt(fraction?.units || 0);
const availableUnits = fractionUnits - BigInt(minUnitsToKeep);
const maxUnitAmountToBuy =
availableUnits > maxUnitAmount ? maxUnitAmount : availableUnits;
const getUnitsToBuy = (percentageAmount: string) => {
try {
const hypercertUnits = BigInt(hypercert.units || 0);
const percentageAsBigInt = parseUnits(
percentageAmount,
DEFAULT_NUM_UNITS_DECIMALS,
);
const unitsToBuy =
(hypercertUnits * percentageAsBigInt) /
(BigInt(100) * DEFAULT_NUM_UNITS);
return unitsToBuy < BigInt(0) ? BigInt(0) : unitsToBuy;
} catch (e) {
console.error(e);
return BigInt(0);
}
};
const getPercentageForUnits = (units: bigint) => {
return (units * BigInt(100)) / BigInt(hypercert?.units || 0);
};
const currency = getCurrencyByAddress(order.chainId, order.currency);
if (!currency) {
throw new Error("Currency not supported");
}
const minPercentageAmount = getPercentageForUnits(minUnitAmount).toString();
const maxPercentageAmount = calculateBigIntPercentage(
maxUnitAmountToBuy,
BigInt(hypercert.units || 0),
)?.toString();
const minPricePerPercent = getPricePerPercent(
order.price,
BigInt(hypercert.units || 0),
);
const form = useForm<BuyFractionalOrderFormValues>({
resolver: zodResolver(formSchema),
reValidateMode: "onChange",
mode: "onChange",
defaultValues: {
minPercentageAmount,
maxPercentageAmount,
percentageAmount: minPercentageAmount,
minPricePerPercent: minPricePerPercent.toString(),
pricePerPercent: minPricePerPercent.toString(),
},
});
const { mutateAsync: buyFractionalMakerAsk } = useBuyFractionalMakerAsk();
const onSubmit = async (values: BuyFractionalOrderFormValues) => {
const hypercertUnits = BigInt(hypercert.units || 0);
if (!hypercertUnits) {
throw new Error("Invalid hypercert units");
}
const unitAmount = getUnitsToBuy(values.percentageAmount);
const pricePerUnit = getPricePerUnit(
values.pricePerPercent,
hypercertUnits,
).toString();
onBuyOrder(order.orderNonce);
try {
await buyFractionalMakerAsk({
order,
unitAmount,
pricePerUnit,
hypercertName: hypercert?.metadata?.name,
totalUnitsInHypercert: hypercertUnits,
});
onCompleted?.();
} catch (error) {
console.error("Error buying fractional order:", error);
}
};
const percentageAmount = form.watch("percentageAmount");
const pricePerPercent = form.watch("pricePerPercent");
const unitsToBuy = getUnitsToBuy(percentageAmount);
const pricePerUnit = getPricePerUnit(
pricePerPercent,
BigInt(hypercert.units || 0),
);
const totalPrice = formatPrice(
order.chainId,
unitsToBuy * pricePerUnit,
currency.address,
true,
);
const formattedMinPrice = formatPrice(
order.chainId,
BigInt(minPricePerPercent),
currency.address,
);
const disabled = !form.formState.isValid || unitsToBuy === BigInt(0);
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="percentageAmount"
render={({ field }) => (
<FormItem>
<h5 className="uppercase text-sm text-slate-500 font-medium tracking-wider">
% to buy
</h5>
<FormControl>
<Input
{...field}
onChange={(e) => {
const value = e.target.value;
if (value === "" || /^\d*\.?\d*$/.test(value)) {
field.onChange(value);
}
}}
/>
</FormControl>
<div className="text-sm text-slate-500">
You will buy{" "}
<b>
<FormattedUnits>{unitsToBuy.toString()}</FormattedUnits>
</b>{" "}
units , for a total of <b>{totalPrice}</b>. (min:{" "}
{minPercentageAmount}%, max: {maxPercentageAmount}%)
</div>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="pricePerPercent"
render={({ field }) => (
<FormItem>
<h5 className="uppercase text-sm text-slate-500 font-medium tracking-wider">
Price per %
</h5>
<FormControl>
<Input
{...field}
value={formatPrice(
order.chainId,
BigInt(field.value),
currency.address,
)}
onChange={(e) => {
const value = e.target.value;
if (value === "" || /^\d*\.?\d*$/.test(value)) {
field.onChange(
parseUnits(value, currency.decimals).toString(),
);
}
}}
/>
</FormControl>
<div className="text-sm text-slate-500">
You can voluntarily increase the price. (min:{" "}
<b>
{formattedMinPrice} {currency.symbol}
</b>
).
</div>
<FormMessage />
</FormItem>
)}
/>
<Button variant="outline" type="submit" disabled={disabled}>
Execute order
</Button>
</form>
</Form>
);
};