Skip to content

Send a Transaction

Sending transactions is a fundamental operation in blockchain applications. This guide demonstrates how to send a transaction using the wagmi library in a React component.

Basic Transaction Example

Below is a basic example of how to send a transaction using wagmi:

tsx
import { useSendTransaction } from "wagmi";
import { parseEther } from "viem";

const Example = () => {
  const { data: hash, isPending, sendTransaction } = useSendTransaction();

  const address = "0xA0Cf…251e"; // Replace with the recipient address
  const amount = 0.05; // Amount in Celo

  const onPress = async (e) => {
    e.preventDefault();
    await sendTransaction({
      to: address,
      value: parseEther(amount.toString()),
    });
  };

  return (
    <button type="submit" onClick={onPress}>
      Send transaction
    </button>
  );
};
tsx
import { useSendTransaction } from "wagmi";
import { encodeFunctionData, erc20Abi, parseUnits } from "viem";

const Example = () => {
  const { data: hash, isPending, sendTransaction } = useSendTransaction();

  const address = "0xA0Cf…251e"; // Replace with the recipient address
  const amount = 0.05; // Amount in usdc
  const USDC_CONTRACT_ADDRESS = "0xcebA9300f2b948710d2653dD7B07f33A8B32118C"; //mainnet
  const USDC_ADAPTOR = "0x2F25deB3848C207fc8E0c34035B3Ba7fC157602B"; //mainnet

  const onPress = async (e) => {
    e.preventDefault();

    const data = encodeFunctionData({
      abi: erc20Abi,
      functionName: "transfer",
      args: [
        address,
        // Different tokens can have different decimals, cUSD (18), USDC (6)
        parseUnits(amount, 6),
      ],
    });

    await sendTransaction({
      account: account.address,
      to: USDC_CONTRACT_ADDRESS,
      feeCurrency: USDC_ADAPTOR, // use USDC to pay for gas
      data: data,
    });
  };

  return (
    <button type="submit" onClick={onPress}>
      Send transaction
    </button>
  );
};
tsx
import { useSendTransaction } from "wagmi";
import { encodeFunctionData, erc20Abi, parseUnits } from "viem";

const Example = () => {
  const { data: hash, isPending, sendTransaction } = useSendTransaction();

  const address = "0xA0Cf…251e"; // Replace with the recipient address
  const amount = 0.05; // Amount in cUSD
  const CUSD_CONTRACT_ADDRESS = "0x765DE816845861e75A25fCA122bb6898B8B1282a"; //mainnet

  const onPress = async (e) => {
    e.preventDefault();

    const data = encodeFunctionData({
      abi: erc20Abi,
      functionName: "transfer",
      args: [
        address,
        // Different tokens can have different decimals, cUSD (18), USDC (6)
        parseUnits(amount, 18),
      ],
    });

    await sendTransaction({
      account: account.address,
      to: CUSD_CONTRACT_ADDRESS,
      feeCurrency: CUSD_CONTRACT_ADDRESS, // use cUSD to pay for gas
      data: data,
    });
  };

  return (
    <button type="submit" onClick={onPress}>
      Send transaction
    </button>
  );
};
 Mainnet

 Name                 Symbol Token Address                              Adapter                                    Decimals Uses Adapter?
 ──────────────────── ────── ────────────────────────────────────────── ────────────────────────────────────────── ──────── ─────────────
 Tether USD           USD₮   0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e 0x0E2A3e05bc9A16F5292A6170456A710cb89C6f72 6        true
 PUSO                 PUSO   0x105d4A9306D2E55a71d2Eb95B81553AE1dC20d7B -                                          18       false
 USDC                 USDC   0xcebA9300f2b948710d2653dD7B07f33A8B32118C 0x2F25deB3848C207fc8E0c34035B3Ba7fC157602B 6        true
 Celo Kenyan Shilling cKES   0x456a3D042C0DbD3db53D5489e98dFb038553B0d0 -                                          18       false
 ECO CFA              eXOF   0x73F93dcc49cB8A239e2032663e9475dd5ef29A08 -                                          18       false
 Celo Dollar          cUSD   0x765DE816845861e75A25fCA122bb6898B8B1282a -                                          18       false
 Celo Colombian Peso  cCOP   0x8A567e2aE79CA692Bd748aB832081C45de4041eA -                                          18       false
 Celo Euro            cEUR   0xD8763CBa276a3738E6DE85b4b3bF5FDed6D6cA73 -                                          18       false
 Celo Brazilian Real  cREAL  0xe8537a3d056DA446677B9E9d6c5dB704EaAb4787 -                                          18       false
 Celo Ghanian Cedi    cGHS   0xfAeA5F3404bbA20D3cc2f8C4B0A888F55a3c7313 -                                          18       false

 Alfajores Testnet

  Name                 Symbol  Token Address                              Adapter                                    Decimals Uses Adapter?
 ──────────────────── ──────── ────────────────────────────────────────── ────────────────────────────────────────── ──────── ─────────────
 Celo Euro            cEUR     0x10c892A6EC43a53E45D0B916B4b7D383B1b78C0F -                                          18       false
 Celo Kenyan Shilling cKES     0x1E0433C1769271ECcF4CFF9FDdD515eefE6CdF92 -                                          18       false
 USDC                 USDC     0x2F25deB3848C207fc8E0c34035B3Ba7fC157602B 0x4822e58de6f5e485eF90df51C41CE01721331dC0 6        true
 Celo Dollar          cUSD     0x874069Fa1Eb16D44d622F2e0Ca25eeA172369bC1 -                                          18       false
 ECO CFA              eXOF     0xB0FA15e002516d0301884059c0aaC0F0C72b019D -                                          18       false
 TetherToken          USD₮     0xC4f86E9B4A588D501c1c3e25628dFd50Bc8D615e -                                          18       false
 Celo Brazilian Real  cREAL    0xE4D517785D091D3c54818832dB6094bcc2744545 -                                          18       false

For a full example, visit the Wagmi documentation.

Wait for Transaction Receipt (Optional)

To enhance user experience, you can wait for the transaction receipt to confirm the transaction's success:

tsx
import {
  useSendTransaction,
  useWaitForTransactionReceipt, 
} from "wagmi";
import { parseEther } from "viem";

const Example = () => {
  const { data: hash, isPending, sendTransaction } = useSendTransaction();

  const address = "0xA0Cf…251e";
  const amount = "0.05";

  const onPress = async (e) => {
    e.preventDefault();

    await sendTransaction({
      to: address,
      value: parseEther(amount.toString()),
    });
  };

  const { 
    isLoading: isConfirming, 
    isSuccess: isConfirmed, 
  } =
    useWaitForTransactionReceipt({ 
      hash, 
    }); 

  return (
    <>
      <button type="submit" onClick={onPress}>
        Send transaction
      </button>
      {isConfirming && <div>Waiting for confirmation...</div>}
      {isConfirmed && <div>Transaction confirmed.</div>}
    </>
  );
};

Explanation

  • useSendTransaction: This hook is used to initiate a transaction. It provides the sendTransaction function, which is called with the transaction details, such as the recipient address and the amount.

  • useWaitForTransactionReceipt: This optional hook is used to wait for the transaction receipt, providing feedback on the transaction's confirmation status. It helps in tracking whether the transaction has been successfully mined.

  • Transaction Details: The transaction details include the recipient address and the amount to be sent. The parseEther function is used to convert the Ether amount into the appropriate format for the transaction.

  • UI Feedback: The component provides feedback to the user about the transaction status, such as when the transaction is pending or confirmed. This enhances user interaction and transparency.

Notes

  • Ensure wagmi is correctly configured. Follow our quickstart guide to know how.

  • Address Replacement: Ensure you replace the placeholder address with the actual recipient address to avoid sending transactions to unintended recipients.

  • Error Handling: Implement error handling to manage any issues that may arise during the transaction process, such as network errors or insufficient funds.

  • Security Considerations: Always validate and sanitize user inputs to prevent potential security vulnerabilities, especially when dealing with financial transactions.

  • Further Reading: For more detailed information on using wagmi and handling Celo transactions, refer to the Wagmi documentation.

This guide should help you understand how to effectively send transactions and manage their confirmation using the wagmi library. Adjust the code and explanations as needed to fit your specific application requirements.