useWriteContract

Description

This hook provides functionality to send either a single transaction or multiple transactions in batch. It uses the smart account client to process and send these transactions.

It supports both synchronous and asynchronous methods for sending transactions, making it versatile for various use cases.

Returns

  • data (Hash | undefined): The hash of the transaction if it was successfully sent, otherwise undefined.

  • error (Error | null): An error object if the transaction failed, otherwise null.

  • isPending (boolean): A boolean indicating whether the transaction is currently pending.

  • isSuccess (boolean): A boolean indicating whether the transaction was successfully sent.

  • isError (boolean): A boolean indicating whether an error occurred during the transaction process.

  • writeContract (SendTransactionMutate): A function that sends the transaction(s) without waiting for a result.

  • writeContractAsync (SendTransactionMutateAsync): A function that sends the transaction(s) and returns a promise that resolves to the transaction hash.

Example

import { useWriteContract } from "@cometh/connect-react-hooks";
import { useState } from "react";
import { parseEther, Address } from "viem";
import { abi } from './contractABI';
 
export const ContractWriter = () => {
    const { writeContract, isLoading, isError, error, isSuccess, data } = useWriteContract();
    const [recipient, setRecipient] = useState<Address>();
    const [amount, setAmount] = useState<string>("0");

    const handleWriteContract = async () => {
        if (recipient) {
            try {
                const hash = await writeContract({
                    abi,
                    address: '0xYourContractAddress',
                    functionName: 'transfer',
                    args: [recipient, parseEther(amount)],
                });
                console.log("Contract write successful! Hash:", hash);
            } catch (error) {
                console.error("Error writing to contract:", error);
            }
        }
    };

    return (
        <div>
            <input
                placeholder="Recipient address"
                onChange={(e) => setRecipient(e.target.value as Address)}
            />
            <input
                type="number"
                placeholder="Amount in ETH"
                onChange={(e) => setAmount(e.target.value)}
            />
            <button onClick={handleWriteContract} disabled={isLoading}>
                Write to Contract
            </button>
            {isError && <p>Error: {error.message}</p>}
            {isSuccess && <p>Contract write successful! Hash: {data}</p>}
        </div>
    );
};

Last updated