useWriteTransactionWithSessionKey

Description

This hook provides functionality to send either a single transaction or multiple transactions in batch using a session key. 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.Comment

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

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

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

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

  • writeContractWithSessionKey: A function to trigger the transaction sending using a session key without waiting for a result.Comment

  • writeContractWithSessionKeyAsync: A function to trigger the transaction sending using a session key and return a promise that resolves to the transaction hash.Comment

Example

import { useWriteContractWithSessionKey } from "@cometh/connect-react-hooks";
import { useState } from "react";
import { parseEther, Address } from "viem";
import { abi } from './contractABI';

export const SessionKeyContractWriter = () => {
  const { writeContractWithSessionKey, isLoading, isError, error, isSuccess, data } = useWriteContractWithSessionKey();
  const [recipient, setRecipient] = useState<Address>();
  const [amount, setAmount] = useState<string>("0");

  const handleWriteContract = async () => {
    if (recipient) {
      try {
        const hash = await writeContractWithSessionKey({
          abi,
          address: '0xYourContractAddress',
          functionName: 'transfer',
          args: [recipient, parseEther(amount)],
        });
        console.log("Contract write successful with session key! Hash:", hash);
      } catch (error) {
        console.error("Error writing to contract with session key:", 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 with Session Key
      </button>
      {isError && <p>Error: {error.message}</p>}
      {isSuccess && <p>Contract write successful! Hash: {data}</p>}
    </div>
  );
};

Last updated