I am using below code to call a smart contract method on Ethereum network.
const w = new Web3(url);
await w.eth.accounts.signTransaction(
{
from: account.address,
to: contractAddress,
gas: 1000000,
gasPrice: 1000000000,
nonce: await w.eth.getTransactionCount(account.address),
data: await contract.methods
.createSector(
{ value: web3.utils.fromWei(price, 'ether') }
)
.encodeABI(),
},
privateKey
);
In above code, it requires gas and gasPrice parameters. I need to set the value when calling the contract method. My question is how I know what the right value to set? I thought those values are not static which can be set during runtime when Metamask is open. Do I misunderstand anything on gas?
gasprice a little higher than thegetPricereturned from the network, will the real gas charged by the network be lower than the gas set in the transaction? Will there be a return from the network to the charged account? – Joey Yi Zhao Feb 27 '24 at 10:45You can see here: https://ethereum.stackexchange.com/questions/54606/what-is-difference-between-gas-gas-price-and-fee
Or I can give a simply example in life:
gas=>how much gasoline for your cargasPrice=>price of gasolineToday, you want to drive to London, you will need 1000L gas, and gasPrice today is 5000¥/L
Nextday, you want to drive to Paris, 500L gas, and because of war gasPrice now is 7000¥/L
– CT95 Feb 28 '24 at 02:47And about your question, you can set any value for
gasPriceif lower than normal, your tx will be stuck, wait until gasPrice decrease to your value if greater than normal, your tx will be broadcast asapAbout
– CT95 Feb 28 '24 at 02:50gas, you must set the true value, if lower than it your tx will failed, if too much your balance can't adapt. Just enoughjust enoughis something very hard to hit – Joey Yi Zhao Feb 28 '24 at 02:57very hard to hit, in my opinion it's not.I will give you an example in hardhat: your tx is
contractA.deposit(). You can get estimation bycontractA.estimateGas.deposit()=> 80.000 gasYou can use that value in
gas. But for safety, you don't want your tx fail because of over gas limit, you can increase 80.000 * 3% = 82400.You can see in every single tx on etherscan, see the value at
– CT95 Feb 28 '24 at 03:06Gas Limit & Usage by Txn:Gas Limit is 82400 and usage by txn may 80020 (or any value)a%is not too much, because if you want to set too much, your client address must adapt that balance. So you have to optimize that value due to your expectation. Like if your common transaction is around 2$, 3$. 10% 20% is not too much,If your common transaction is around 1000$, 1500$. 10% 20% is too much, 3%, 5% is reasonable
– CT95 Feb 28 '24 at 03:11gasPriceandgas limitright? – Joey Yi Zhao Feb 28 '24 at 11:20estimationand must <=gas limitAnd your real fee you pay in ETH is:
gas used*gas price= ... ETHThe unit gas is: wei or gwei (1e9 wei) The unit gas fee is: ETH
– CT95 Feb 29 '24 at 04:31