VanillaJS library for Ethereum blockchain interactions with reactive primitives and utilities for building Ethereum applications
—
Transaction sending, estimation, waiting, and monitoring. Complete transaction lifecycle management.
Sends a transaction to the blockchain.
/**
* Sends a transaction to the blockchain
* @param config - Wagmi configuration
* @param parameters - Transaction parameters
* @returns Transaction hash
*/
function sendTransaction<config extends Config>(
config: config,
parameters: SendTransactionParameters<config>
): Promise<SendTransactionReturnType>;
interface SendTransactionParameters<config extends Config> {
/** Account to send from (optional, uses connected account) */
account?: Address;
/** Target address */
to?: Address;
/** Transaction data */
data?: Hex;
/** Gas limit */
gas?: bigint;
/** Gas price (legacy transactions) */
gasPrice?: bigint;
/** Max fee per gas (EIP-1559) */
maxFeePerGas?: bigint;
/** Max priority fee per gas (EIP-1559) */
maxPriorityFeePerGas?: bigint;
/** Nonce */
nonce?: number;
/** Value to send in wei */
value?: bigint;
/** Chain ID to send on */
chainId?: config['chains'][number]['id'];
}
type SendTransactionReturnType = Hash; // Transaction hash
type SendTransactionErrorType =
| BaseErrorType
| UserRejectedRequestErrorType
| InsufficientFundsErrorType;Usage Example:
import { sendTransaction, parseEther } from '@wagmi/core'
// Send ETH transfer
const hash = await sendTransaction(config, {
to: '0x742d35Cc6601C2F3Ac5e5c7A9d16e4e6Be4e6e9e',
value: parseEther('0.1'), // 0.1 ETH
})
console.log('Transaction hash:', hash)
// Send transaction with custom gas
const customGasHash = await sendTransaction(config, {
to: '0x742d35Cc6601C2F3Ac5e5c7A9d16e4e6Be4e6e9e',
value: parseEther('0.05'),
gas: 21000n,
maxFeePerGas: parseGwei('20'),
maxPriorityFeePerGas: parseGwei('2'),
})
// Send contract interaction data
const contractCallHash = await sendTransaction(config, {
to: '0xContractAddress',
data: '0x1234567890abcdef...', // Encoded function call
gas: 100000n,
})Estimates gas required for a transaction.
/**
* Estimates gas for a transaction
* @param config - Wagmi configuration
* @param parameters - Gas estimation parameters
* @returns Estimated gas amount
*/
function estimateGas<config extends Config>(
config: config,
parameters: EstimateGasParameters<config>
): Promise<EstimateGasReturnType>;
interface EstimateGasParameters<config extends Config> {
/** Account to estimate from */
account?: Address;
/** Target address */
to?: Address;
/** Transaction data */
data?: Hex;
/** Gas price */
gasPrice?: bigint;
/** Max fee per gas */
maxFeePerGas?: bigint;
/** Max priority fee per gas */
maxPriorityFeePerGas?: bigint;
/** Nonce */
nonce?: number;
/** Value to send */
value?: bigint;
/** Chain ID to estimate on */
chainId?: config['chains'][number]['id'];
/** Block number to estimate at */
blockNumber?: bigint;
/** Block tag */
blockTag?: 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';
}
type EstimateGasReturnType = bigint;
type EstimateGasErrorType = BaseErrorType | EstimationErrorType;Usage Example:
import { estimateGas, parseEther } from '@wagmi/core'
// Estimate gas for ETH transfer
const gasEstimate = await estimateGas(config, {
to: '0x742d35Cc6601C2F3Ac5e5c7A9d16e4e6Be4e6e9e',
value: parseEther('0.1'),
})
console.log('Estimated gas:', gasEstimate.toString())
// Estimate gas for contract call
const contractGasEstimate = await estimateGas(config, {
to: '0xContractAddress',
data: '0x1234567890abcdef...', // Encoded function call
})
console.log('Contract call gas estimate:', contractGasEstimate.toString())
// Use estimate in actual transaction
const hash = await sendTransaction(config, {
to: '0x742d35Cc6601C2F3Ac5e5c7A9d16e4e6Be4e6e9e',
value: parseEther('0.1'),
gas: gasEstimate + 10000n, // Add buffer
})Prepares a transaction request with gas estimation and fee calculation.
/**
* Prepares transaction request with gas estimation
* @param config - Wagmi configuration
* @param parameters - Transaction preparation parameters
* @returns Prepared transaction request
*/
function prepareTransactionRequest<config extends Config>(
config: config,
parameters: PrepareTransactionRequestParameters<config>
): Promise<PrepareTransactionRequestReturnType>;
interface PrepareTransactionRequestParameters<config extends Config> {
/** Account to send from */
account?: Address;
/** Target address */
to?: Address;
/** Transaction data */
data?: Hex;
/** Gas limit (optional, will estimate if not provided) */
gas?: bigint;
/** Gas price (legacy) */
gasPrice?: bigint;
/** Max fee per gas (EIP-1559) */
maxFeePerGas?: bigint;
/** Max priority fee per gas (EIP-1559) */
maxPriorityFeePerGas?: bigint;
/** Nonce (optional, will fetch if not provided) */
nonce?: number;
/** Value to send */
value?: bigint;
/** Chain ID */
chainId?: config['chains'][number]['id'];
}
interface PrepareTransactionRequestReturnType {
/** Account sending transaction */
account: Address;
/** Target address */
to?: Address;
/** Transaction data */
data?: Hex;
/** Gas limit */
gas: bigint;
/** Gas price (legacy) */
gasPrice?: bigint;
/** Max fee per gas (EIP-1559) */
maxFeePerGas?: bigint;
/** Max priority fee per gas (EIP-1559) */
maxPriorityFeePerGas?: bigint;
/** Nonce */
nonce: number;
/** Value to send */
value?: bigint;
/** Chain ID */
chainId: number;
/** Transaction type */
type: 'legacy' | 'eip2930' | 'eip1559';
}
type PrepareTransactionRequestErrorType =
| BaseErrorType
| EstimationErrorType;Usage Example:
import { prepareTransactionRequest, sendTransaction } from '@wagmi/core'
// Prepare transaction with automatic gas estimation
const prepared = await prepareTransactionRequest(config, {
to: '0x742d35Cc6601C2F3Ac5e5c7A9d16e4e6Be4e6e9e',
value: parseEther('0.1'),
})
console.log('Prepared transaction:', {
gas: prepared.gas.toString(),
maxFeePerGas: prepared.maxFeePerGas?.toString(),
nonce: prepared.nonce,
type: prepared.type,
})
// Send the prepared transaction
const hash = await sendTransaction(config, prepared)
console.log('Transaction sent:', hash)Waits for a transaction to be mined and returns the receipt.
/**
* Waits for transaction to be mined
* @param config - Wagmi configuration
* @param parameters - Wait parameters
* @returns Transaction receipt
*/
function waitForTransactionReceipt<config extends Config>(
config: config,
parameters: WaitForTransactionReceiptParameters<config>
): Promise<WaitForTransactionReceiptReturnType>;
interface WaitForTransactionReceiptParameters<config extends Config> {
/** Transaction hash to wait for */
hash: Hash;
/** Number of confirmations to wait for */
confirmations?: number;
/** Polling interval in milliseconds */
pollingInterval?: number;
/** Timeout in milliseconds */
timeout?: number;
/** Chain ID */
chainId?: config['chains'][number]['id'];
}
interface WaitForTransactionReceiptReturnType {
/** Transaction hash */
transactionHash: Hash;
/** Block hash */
blockHash: Hash;
/** Block number */
blockNumber: bigint;
/** Transaction index in block */
transactionIndex: number;
/** From address */
from: Address;
/** To address */
to?: Address;
/** Gas used */
gasUsed: bigint;
/** Effective gas price */
effectiveGasPrice: bigint;
/** Transaction status */
status: 'success' | 'reverted';
/** Event logs */
logs: Log[];
/** Contract address (if deployment) */
contractAddress?: Address;
/** Cumulative gas used in block */
cumulativeGasUsed: bigint;
/** Transaction type */
type: 'legacy' | 'eip2930' | 'eip1559';
}
type WaitForTransactionReceiptErrorType =
| BaseErrorType
| TransactionReceiptNotFoundErrorType
| TransactionNotFoundErrorType
| WaitForTransactionReceiptTimeoutErrorType;
/** @deprecated Use waitForTransactionReceipt instead */
const waitForTransaction = waitForTransactionReceipt;Usage Example:
import { sendTransaction, waitForTransactionReceipt } from '@wagmi/core'
// Send transaction and wait for confirmation
const hash = await sendTransaction(config, {
to: '0x742d35Cc6601C2F3Ac5e5c7A9d16e4e6Be4e6e9e',
value: parseEther('0.1'),
})
console.log('Transaction sent:', hash)
// Wait for transaction to be mined
const receipt = await waitForTransactionReceipt(config, {
hash,
confirmations: 1, // Wait for 1 confirmation
})
console.log('Transaction confirmed:', {
blockNumber: receipt.blockNumber.toString(),
gasUsed: receipt.gasUsed.toString(),
status: receipt.status,
})
// Check if transaction succeeded
if (receipt.status === 'success') {
console.log('Transaction successful!')
console.log('Logs:', receipt.logs.length)
} else {
console.log('Transaction failed/reverted')
}Send multiple operations in a single batch transaction.
/**
* Sends batch of calls (EIP-5792)
* @param config - Wagmi configuration
* @param parameters - Batch calls parameters
* @returns Batch call identifier
*/
function sendCalls<config extends Config>(
config: config,
parameters: SendCallsParameters<config>
): Promise<SendCallsReturnType>;
interface SendCallsParameters<config extends Config> {
/** Array of calls to execute */
calls: readonly {
/** Target contract address */
to?: Address;
/** Call data */
data?: Hex;
/** Value to send with call */
value?: bigint;
}[];
/** Chain ID to execute on */
chainId?: config['chains'][number]['id'];
/** Capabilities for the batch */
capabilities?: {
/** Paymaster service configuration */
paymasterService?: {
url: string;
};
/** Auxiliary funds configuration */
auxiliaryFunds?: {
supported: boolean;
};
};
}
type SendCallsReturnType = string; // Batch identifier
type SendCallsErrorType =
| BaseErrorType
| UserRejectedRequestErrorType;
/**
* Gets status of batch calls
* @param config - Wagmi configuration
* @param parameters - Status query parameters
* @returns Batch status information
*/
function getCallsStatus<config extends Config>(
config: config,
parameters: GetCallsStatusParameters<config>
): Promise<GetCallsStatusReturnType>;
interface GetCallsStatusParameters<config extends Config> {
/** Batch identifier */
id: string;
/** Chain ID */
chainId?: config['chains'][number]['id'];
}
interface GetCallsStatusReturnType {
/** Batch status */
status: 'PENDING' | 'CONFIRMED';
/** Transaction receipts (if confirmed) */
receipts?: TransactionReceipt[];
}
/**
* Waits for batch calls to complete
* @param config - Wagmi configuration
* @param parameters - Wait parameters
* @returns Final batch status
*/
function waitForCallsStatus<config extends Config>(
config: config,
parameters: WaitForCallsStatusParameters<config>
): Promise<WaitForCallsStatusReturnType>;
interface WaitForCallsStatusParameters<config extends Config> {
/** Batch identifier */
id: string;
/** Chain ID */
chainId?: config['chains'][number]['id'];
/** Polling interval */
pollingInterval?: number;
/** Timeout */
timeout?: number;
}
type WaitForCallsStatusReturnType = GetCallsStatusReturnType;
/**
* Shows status UI for batch calls
* @param config - Wagmi configuration
* @param parameters - Show status parameters
* @returns Status display result
*/
function showCallsStatus<config extends Config>(
config: config,
parameters: ShowCallsStatusParameters<config>
): Promise<ShowCallsStatusReturnType>;
interface ShowCallsStatusParameters<config extends Config> {
/** Batch identifier */
id: string;
/** Chain ID */
chainId?: config['chains'][number]['id'];
}
type ShowCallsStatusReturnType = null;Usage Example:
import {
sendCalls,
waitForCallsStatus,
getCallsStatus,
showCallsStatus
} from '@wagmi/core'
// Send batch of ERC-20 transfers
const batchId = await sendCalls(config, {
calls: [
{
to: '0xTokenA',
data: encodeFunctionData({
abi: erc20Abi,
functionName: 'transfer',
args: ['0xRecipient1', 1000000n],
}),
},
{
to: '0xTokenB',
data: encodeFunctionData({
abi: erc20Abi,
functionName: 'transfer',
args: ['0xRecipient2', 2000000n],
}),
},
],
})
console.log('Batch sent:', batchId)
// Wait for batch to complete
const finalStatus = await waitForCallsStatus(config, {
id: batchId,
})
if (finalStatus.status === 'CONFIRMED') {
console.log('Batch confirmed!')
console.log('Receipts:', finalStatus.receipts?.length)
}
// Or check status manually
const status = await getCallsStatus(config, { id: batchId })
console.log('Current status:', status.status)
// Show status in wallet UI
await showCallsStatus(config, { id: batchId })Monitor pending and confirmed transactions.
/**
* Watches for pending transactions
* @param config - Wagmi configuration
* @param parameters - Watch parameters
* @returns Unsubscribe function
*/
function watchPendingTransactions<config extends Config>(
config: config,
parameters: WatchPendingTransactionsParameters<config>
): WatchPendingTransactionsReturnType;
interface WatchPendingTransactionsParameters<config extends Config> {
/** Callback when new pending transaction detected */
onTransactions(transactions: Hash[]): void;
/** Callback for errors */
onError?(error: Error): void;
/** Chain ID to watch */
chainId?: config['chains'][number]['id'];
/** Polling interval */
poll?: boolean;
/** Polling interval in ms */
pollingInterval?: number;
}
type WatchPendingTransactionsReturnType = () => void; // Unsubscribe functionUsage Example:
import { watchPendingTransactions } from '@wagmi/core'
// Watch for pending transactions
const unsubscribe = watchPendingTransactions(config, {
onTransactions(hashes) {
console.log('New pending transactions:', hashes)
// Process pending transactions
hashes.forEach(hash => {
console.log('Pending tx:', hash)
})
},
onError(error) {
console.error('Watch error:', error)
},
pollingInterval: 1000, // Check every second
})
// Stop watching
// unsubscribe()Here's a complete example showing the full transaction lifecycle:
import {
estimateGas,
prepareTransactionRequest,
sendTransaction,
waitForTransactionReceipt,
parseEther,
parseGwei
} from '@wagmi/core'
async function sendTransactionWithFullFlow() {
try {
// 1. Estimate gas first
const gasEstimate = await estimateGas(config, {
to: '0x742d35Cc6601C2F3Ac5e5c7A9d16e4e6Be4e6e9e',
value: parseEther('0.1'),
})
console.log('Gas estimate:', gasEstimate.toString())
// 2. Prepare transaction with custom parameters
const prepared = await prepareTransactionRequest(config, {
to: '0x742d35Cc6601C2F3Ac5e5c7A9d16e4e6Be4e6e9e',
value: parseEther('0.1'),
gas: gasEstimate + 5000n, // Add buffer
maxFeePerGas: parseGwei('20'),
maxPriorityFeePerGas: parseGwei('2'),
})
console.log('Prepared transaction:', prepared)
// 3. Send transaction
const hash = await sendTransaction(config, prepared)
console.log('Transaction sent:', hash)
// 4. Wait for confirmation
const receipt = await waitForTransactionReceipt(config, {
hash,
confirmations: 2, // Wait for 2 confirmations
timeout: 60000, // 1 minute timeout
})
// 5. Handle result
if (receipt.status === 'success') {
console.log('✅ Transaction successful!')
console.log('Block:', receipt.blockNumber.toString())
console.log('Gas used:', receipt.gasUsed.toString())
console.log('Effective gas price:', receipt.effectiveGasPrice.toString())
} else {
console.log('❌ Transaction failed')
}
return receipt
} catch (error) {
console.error('Transaction failed:', error)
// Handle specific errors
if (error.name === 'UserRejectedRequestError') {
console.log('User cancelled transaction')
} else if (error.name === 'InsufficientFundsError') {
console.log('Insufficient funds for transaction')
} else if (error.name === 'EstimationError') {
console.log('Gas estimation failed')
}
throw error
}
}
// Usage
sendTransactionWithFullFlow()
.then(receipt => console.log('Final receipt:', receipt))
.catch(error => console.error('Flow failed:', error))Install with Tessl CLI
npx tessl i tessl/npm-wagmi--core