import { GeneratePurchasePermitResponse } from "@echoxyz/sonar-core";
import { useCallback, useState } from "react";
import { useWriteContract, useWaitForTransactionReceipt } from "wagmi";
import { useConfig } from "wagmi";
import { simulateContract } from "wagmi/actions";
import { YourSaleContractABI } from "./YourSaleContractABI";
export const useSaleContract = (walletAddress: `0x${string}`) => {
const { writeContractAsync } = useWriteContract();
const config = useConfig();
const [txHash, setTxHash] = useState<`0x${string}` | undefined>(undefined);
// Track the state of the transaction receipt
const {
data: txReceipt,
isFetching: awaitingTxReceipt,
error: awaitingTxReceiptError,
} = useWaitForTransactionReceipt({
hash: txHash,
});
// This function is used to construct the transaction,
// simulate it, and then submit it after the user has signed it
const commitWithPermit = useCallback(
async ({
purchasePermitResp,
amount,
}: {
purchasePermitResp: GeneratePurchasePermitResponse;
amount: bigint;
}) => {
if (!("MinPrice" in purchasePermitResp.PermitJSON)) {
throw new Error("Invalid purchase permit response");
}
const permit = purchasePermitResp.PermitJSON;
const { request } = await simulateContract(config, {
address: "YOUR_SALE_CONTRACT_ADDRESS",
abi: YourSaleContractABI,
functionName: "YOUR_PURCHASE_FUNCTION_NAME",
args: [
amount,
{
entityID: permit.EntityID,
saleUUID: permit.SaleUUID,
wallet: permit.Wallet,
expiresAt: BigInt(permit.ExpiresAt),
minAmount: BigInt(permit.MinAmount),
maxAmount: BigInt(permit.MaxAmount),
minPrice: BigInt(permit.MinPrice),
maxPrice: BigInt(permit.MaxPrice),
payload: permit.Payload,
},
purchasePermitResp.Signature,
] as const,
});
setTxHash(
await writeContractAsync(request, {
onError: (error: Error) => {
throw error;
},
})
);
},
[writeContractAsync, config]
);
return {
commitWithPermit,
awaitingTxReceipt,
txReceipt,
awaitingTxReceiptError,
};
};