EIP1559如何设置合理的Gas
October 19th, 2022

EIP-1559已经运行有一段时间了,不过大部分的库还没有自动支持。这里就以Ethers.js为例说明如何设置新的Gas参数。

一般来说,如果你不设置参数,就像这样直接提交交易

await contract.connect(account).method(params...);

你得到的应该是老的交易格式(type=0),即非EIP-1559类型的交易。

默认交易类型
默认交易类型

而想要得到EIP-1559类型的交易(type=2),需要明确设置参数maxFeePerGasmaxPriorityFeePerGas

await contract.connect(account).method(params..., {
            maxFeePerGas: maxFeePerGas,
            maxPriorityFeePerGas: maxPriorityFeePerGas,
});

带上这两个参数之后,交易的type会变成2。

EIP-1559交易
EIP-1559交易

接下来的问题是,如何动态获取网络的拥堵情况,设置合理的值?

答案是使用feeData

let feeData = await ethers.provider.getFeeData();
console.log(feeData);
{
  lastBaseFeePerGas: BigNumber { value: "36" },
  maxFeePerGas: BigNumber { value: "1500000072" },
  maxPriorityFeePerGas: BigNumber { value: "1500000000" },
  gasPrice: BigNumber { value: "10000014" }
}

feeData获得的数值即为推荐值,如果不太怕拥堵,可以直接使用。

let feeData = await ethers.provider.getFeeData();
await contract.connect(account).method(params..., {
            maxFeePerGas: feeData.maxFeePerGas,
            maxPriorityFeePerGas: feeData.maxPriorityFeePerGas,
});

当然,如果是在抢购东西,也可以考虑酌情增加。

Subscribe to Alex
Receive the latest updates directly to your inbox.
Mint this entry as an NFT to add it to your collection.
Verification
This entry has been permanently stored onchain and signed by its creator.
More from Alex

Skeleton

Skeleton

Skeleton