estimateFeesPerGas
Returns an estimate for the fees per gas (in wei) for a transaction to be likely included in the next block.
If chain.fees.estimateFeesPerGas
is set on the Client Chain or override Chain, it will use the returned value.
Otherwise, for EIP-1159 Transactions, viem will estimate the fees using a combination of the block's base fee per gas (to derive maxFeePerGas
) + the estimateMaxPriorityFeePerGas
Action (to derive maxPriorityFeePerGas
). For Legacy Transactions, viem will estimate the fee based on the gas price (via the getGasPrice
Action).
Usage
ts
import { publicClient } from './client'
const {
maxFeePerGas,
maxPriorityFeePerGas
} = await publicClient.estimateFeesPerGas()
/**
* {
* maxFeePerGas: 15_000_000_000n,
* maxPriorityFeePerGas: 1_000_000_000n,
* }
*/
const { gasPrice } = await publicClient.estimateFeesPerGas({
type: 'legacy'
})
/**
* { gasPrice: 15_000_000_000n }
*/
import { publicClient } from './client'
const {
maxFeePerGas,
maxPriorityFeePerGas
} = await publicClient.estimateFeesPerGas()
/**
* {
* maxFeePerGas: 15_000_000_000n,
* maxPriorityFeePerGas: 1_000_000_000n,
* }
*/
const { gasPrice } = await publicClient.estimateFeesPerGas({
type: 'legacy'
})
/**
* { gasPrice: 15_000_000_000n }
*/
ts
import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
export const publicClient = createPublicClient({
chain: mainnet,
transport: http()
})
import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
export const publicClient = createPublicClient({
chain: mainnet,
transport: http()
})
Returns
An estimate (in wei) for the fees per gas.
Parameters
chain (optional)
- Type: Chain
- Default:
client.chain
Optional Chain override. Used to infer the fees per gas from chain.fees.estimateFeesPerGas
.
ts
import { optimism } from 'viem/chains'
const { maxFeePerGas, maxPriorityFeePerGas } =
await publicClient.estimateFeesPerGas({
chain: optimism
})
import { optimism } from 'viem/chains'
const { maxFeePerGas, maxPriorityFeePerGas } =
await publicClient.estimateFeesPerGas({
chain: optimism
})
type (optional)
- Type:
"legacy" | "eip1559"
- Default:
"eip1559"
ts
const { gasPrice } = await publicClient.estimateFeesPerGas({
type: 'legacy'
})
const { gasPrice } = await publicClient.estimateFeesPerGas({
type: 'legacy'
})