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;
}) => {
// This example shows how to pass through BasicPermit's,
// but you can see how to use AllocationPermit's in the example app.
const { request } = await simulateContract(config, {
address: "YOUR_SALE_CONTRACT_ADDRESS",
abi: YourSaleContractABI,
functionName: "YOUR_PURCHASE_FUNCTION_NAME",
args: [
amount,
{
permit: {
entityID: purchasePermitResp.PermitJSON.EntityID,
saleUUID: purchasePermitResp.PermitJSON.SaleUUID,
wallet: purchasePermitResp.PermitJSON.Wallet,
expiresAt: BigInt(purchasePermitResp.PermitJSON.ExpiresAt),
payload: purchasePermitResp.PermitJSON.Payload,
},
},
purchasePermitResp.Signature,
] as const,
});
setTxHash(
await writeContractAsync(request, {
onError: (error: Error) => {
throw error;
},
})
);
},
[writeContractAsync, config]
);
return {
commitWithPermit,
awaitingTxReceipt,
txReceipt,
awaitingTxReceiptError,
};
};