Skip to content

Commit

Permalink
hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
malerba118 committed Feb 14, 2022
1 parent f02a505 commit 44d4b19
Showing 1 changed file with 61 additions and 0 deletions.
61 changes: 61 additions & 0 deletions hooks/useCommentsContract.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import * as wagmi from "wagmi";
import { useProvider, useSigner } from "wagmi";
// Import our contract ABI
import CommentsContract from "../artifacts/contracts/Comments.sol/Comments.json";

export interface Comment {
id: string;
topic: string;
message: string;
creator_address: string;
created_at: number;
}

export enum EventType {
CommentAdded = "CommentAdded",
}

const useCommentsContract = () => {
// An ethers.Signer instance associated with the signed-in wallet.
// https://docs.ethers.io/v5/api/signer/
const [signer] = useSigner();
// An ethers.Provider instance associated with the connected blockchain network.
// (eg localhost, polygon-mumbai, ethereum-mainnet)
// https://docs.ethers.io/v5/api/providers/
const provider = useProvider();

// This returns a new ethers.Contract ready to interact with our comments API.
// We need to pass in the address of our deployed contract as well as its abi.
// We also pass in the signer if there is a signed in wallet, or if there's
// no signed in wallet then we'll pass in the connected provider.
const contract = wagmi.useContract({
addressOrName: "0x5FbDB2315678afecb367f032d93F642f64180aa3",
contractInterface: CommentsContract.abi,
signerOrProvider: signer.data || provider,
});

// Wrapper to add types to our getComments function.
const getComments = async (topic: string): Promise<Comment[]> => {
return contract.getComments(topic).then((comments) => {
// Each comment is represented as array by default so we convert to object
return comments.map((c) => ({ ...c }));
});
};

// Wrapper to add types to our addComment function.
const addComment = async (topic: string, message: string): Promise<void> => {
// Create a new transaction
const tx = await contract.addComment(topic, message);
// Wait for transaction to be mined
await tx.wait();
};

return {
contract,
chainId: contract.provider.network?.chainId,
getComments,
addComment,
};
};

export default useCommentsContract;

0 comments on commit 44d4b19

Please sign in to comment.