"use client";
import { getAccount, getPublicClient, switchChain, writeContract } from "@wagmi/core";
import {
Abi,
AbiItemArgs,
Address,
createWalletClient,
custom,
encodeFunctionData,
Hash,
Hex,
} from "viem";
import { Config } from "Wagmi";
import { eip712WalletActions, getGeneralPaymasterInput } from "viem/zksync";
import { sophonTestnet, sophonMainnet } from "viem/chains";
export default async function sendTransaction(
wagmiConfig: Config,
chainId: number,
address: Address,
abi: Abi,
functionName: string,
args: AbiItemArgs,
value?: bigint
): Promise<Hash> {
const account = getAccount(wagmiConfig);
if (!account.address) throw new Error("No account connected.");
if (account.chainId !== chainId) await switchChain(wagmiConfig, { chainId });
const publicClient = getPublicClient(wagmiConfig, { chainId });
if (!publicClient) throw new Error("No public client available.");
const estimateGas = await publicClient.estimateContractGas({
account: account.address,
address,
abi,
functionName,
args,
value,
});
// const nextNonce = await publicClient.getTransactionCount({
// address: account.address,
// });
// Handle Sophon-specific logic
if (chainId === 50104 || chainId === 531050104) {
const walletClient = createWalletClient({
chain: chainId === 50104 ? sophonMainnet : sophonTestnet
transport: custom(window.ethereum!),
}).extend(eip712WalletActions());
const paymaster: Address = "0x98546B226dbbA8230cf620635a1e4ab01F6A99B2";
const paymasterInput: Hex = getGeneralPaymasterInput({
innerInput: "0x",
});
const txData = encodeFunctionData({ abi, functionName, args });
const hash = await walletClient.sendTransaction({
account: account.address,
to: address,
data: txData,
value,
gas: estimateGas,
chain,
paymaster,
paymasterInput,
// nonce: nextNonce, enable if you want to use a specific nonce
});
return hash;
}
// Fallback for non-ZKsync chains
return await writeContract(wagmiConfig, {
address,
chainId,
abi,
functionName,
args,
value,
gas: estimateGas,
});
}