Recommended: JavaScript SDK with React Hooks For new React apps, we recommend the JavaScript SDK with React Hooks (@dynamic-labs-sdk/react-hooks) instead of the legacy React SDK documented here. The JS SDK comes with many benefits such as a much smaller bundle size and other optimizations. Use the React quickstart (JavaScript SDK) to get started.
This is a React-only guide.
Before sending a transaction, you can use the public client to estimate the gas
fees. Some chains also support custom gas estimation methods.
Here are examples of how to get a gas estimate using viem:
Setup
import { FC } from 'react' ;
import { parseEther , toHex } from 'viem' ;
import { useDynamicContext } from '@dynamic-labs/sdk-react-core' ;
import { isEthereumWallet } from '@dynamic-labs/ethereum-core' ;
export const EVMEstimateGas : FC = () => {
const toAddress = '0x0000000000000000000000000000000000000000' ;
const amount = '0.001' ;
const { primaryWallet } = useDynamicContext ();
if ( ! primaryWallet || ! isEthereumWallet ( primaryWallet )) {
return (
< div > EVM Wallet not found </ div >
);
}
const estimateGas = async () => {
// See [Estimate Gas Function]
}
return (
< div >
< button onClick = { estimateGas } > Estimate Gas </ button >
</ div >
)
};
Estimate Gas Function
const estimateGas = async () => {
const client = await primaryWallet . getPublicClient ();
if ( ! client ) {
console . error ( 'Failed to get wallet client' );
return ;
}
const estimate = await client . transport . request ({
method: 'eth_estimateGas' ,
params: [
{
from: primaryWallet . address as `0x ${ string } ` ,
to: toAddress as `0x ${ string } ` ,
value: toHex ( parseEther ( amount )),
},
],
});
// On success, the estimate will be a hex string
console . log ( estimate );
}
const estimateGas = async () => {
const client = await primaryWallet . getPublicClient ();
if ( ! client ) {
console . error ( 'Failed to get wallet client' );
return ;
}
const estimate = await client . transport . request ({
method: 'linea_estimateGas' ,
params: [
{
from: primaryWallet . address as `0x ${ string } ` ,
to: toAddress as `0x ${ string } ` ,
value: toHex ( parseEther ( amount )),
},
],
});
// On success, the estimate will be an object like:
// {
// baseFeePerGas: "0x7",
// gasLimit: "0xcf08",
// priorityFeePerGas: "0x43a82a4"
// }
console . log ( estimate );
}