-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathuse-buy-fraction.ts
96 lines (86 loc) · 2.82 KB
/
use-buy-fraction.ts
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
import { useGetCurrentERC20Allowance } from "@/hooks/use-get-current-erc20-allowance";
import type { HypercertExchangeClient } from "@hypercerts-org/marketplace-sdk";
import { useState } from "react";
import type { Address } from "viem";
import { waitForTransactionReceipt } from "viem/actions";
import type { UsePublicClientReturnType } from "wagmi";
export enum TransactionStatuses {
PreparingOrder = "preparingOrder",
Approval = "approval",
SignForBuy = "signForBuy",
Pending = "pending",
Confirmed = "confirmed",
Failed = "failed",
}
const useHandleBuyFraction = (
publicClient: UsePublicClientReturnType,
hypercertExhangeClient: HypercertExchangeClient
) => {
const [transactionStatus, setTransactionStatus] =
useState<keyof typeof TransactionStatuses>("Pending");
const [transactionHash, setTransactionHash] = useState<Address | null>(null);
const currentAllowance = useGetCurrentERC20Allowance();
const handleBuyFraction = async (
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
order: any,
amount: bigint,
address: Address,
hypercertId: string | undefined,
comment: string | undefined,
amountInDollars: number
) => {
if (!publicClient) {
throw new Error("No public client found");
}
if (!order) {
throw new Error("No order found");
}
console.log({ order, amount, address, hypercertId, comment });
console.log(order.price);
const takerOrder = hypercertExhangeClient.createFractionalSaleTakerBid(
order,
address,
amount,
order.price
);
try {
setTransactionStatus("PreparingOrder");
const { call } = hypercertExhangeClient.executeOrder(
order,
takerOrder,
order.signature
);
setTransactionStatus("SignForBuy");
const myAmount = BigInt(order.price) * amount;
console.log(`myAmount: ${myAmount}`);
const tx = await call({ value: myAmount });
console.log(`amountInDollars: ${amountInDollars}`);
fetch("/api/contributions", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
sender: address,
txId: tx.hash as `0x${string}`,
hypercertId: hypercertId,
amount: amountInDollars,
comment: comment,
}),
});
setTransactionHash(tx.hash as Address);
setTransactionStatus("Pending");
const txnReceipt = await waitForTransactionReceipt(publicClient, {
hash: tx.hash as `0x${string}`,
});
console.log({ txnReceipt });
setTransactionStatus("Confirmed");
return txnReceipt;
} catch (e) {
console.error(e);
setTransactionStatus("Failed");
}
};
return { handleBuyFraction, transactionStatus, transactionHash };
};
export { useHandleBuyFraction };