Skip to main content

alchemy aa maxFeePerGas PriorityFeePerGas

import { hexToBigInt, parseGwei } from 'viem'
import { arbitrum } from 'viem/chains'

// https://github.com/wevm/viem/blob/2813fbd218a54c99d92f1e29e5ca1b2961a06071/src/account-abstraction/actions/bundler/prepareUserOperation.ts#L435-L456
export const getUserOperationFeesPerGas = async (publicClient) => {
const url = publicClient.chain.rpcUrls.default.http[0]

// https://docs.alchemy.com/reference/bundler-api-fee-logic

// Recommended Actions for Calculating maxFeePerGas
if (/alchemy/.test(url)) {
////////////////////////////////////////////////////////////////////////////////
// alchemy baseFeePerGas
////////////////////////////////////////////////////////////////////////////////
const block = await publicClient.getBlock({
blockTag: 'latest',
})
////////////////////////////////////////////////////////////////////////////////
// alchemy baseFeePerGas buffer + PriorityFeePerGas buffer
////////////////////////////////////////////////////////////////////////////////
let baseFeeBuffer = 110n
let priorityFeePerGasBuffer = 110n
// mainnet
if (!publicClient.chain.testnet) {
if (publicClient.chain.id === arbitrum.id) {
baseFeeBuffer = 105n
priorityFeePerGasBuffer = 100n
} else {
baseFeeBuffer = 150n
priorityFeePerGasBuffer = 125n
}
}
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
jsonrpc: '2.0',
method: 'rundler_maxPriorityFeePerGas',
params: [],
id: 1,
}),
}).then((response) => response.json())

const rundler_maxPriorityFeePerGas = hexToBigInt(response.result)

const baseFeePerGas = block.baseFeePerGas

// biome-ignore format:
const maxPriorityFeePerGas = priorityFeePerGasBuffer * rundler_maxPriorityFeePerGas

const result = {
maxFeePerGas:
(baseFeeBuffer * baseFeePerGas) / 100n + maxPriorityFeePerGas / 100n,
maxPriorityFeePerGas: maxPriorityFeePerGas / 100n,
}

return result
}
// other bundler providers
return {}
}


alt text