web3.js 发送EIP-1559交易

EIP-1559简介

以太坊经过伦敦硬分叉后,实施了EIP-1559提案,该提案主要有以下内容。

添加新字段

EIP-1559添加了基本费用最高优先费用最高费用三个字段,分别解释如下:

  1. 基本费用(Base Fee):在以太坊上发送交易所需的最低Gas价格。基本费随着上一区块的Gas使用量而动态调整。
  2. 最高优先费用(MaxPriority Fee):用户愿意向矿工支付的Gas价格,越高越可能更快被打包到区块中。即给矿工的小费,默认是2gwei。
  3. 最高费用(Max Fee):用户愿意支付的最高Gas价格(基本费用+优先费用)。

使用原交易字段Gas Price的交易类型,现在被称为Type 1。

使用新交易字段Base Fee、MaxPriority Fee、Max Fee,而不使用Gas Price的交易类型,现在被称为Type 2。

基本费的调整

以太坊中存在Gas上限(Gas Limit)和目标Gas使用量(Gas Target)两个参数。

可将Gas上限视为以太坊的区块大小,它限制了一个区块所能容纳的交易数量。目标Gas使用量是Gas上限的50%,是以太坊网络希望长期维持的理想区块空间。

为了使当前Gas使用量尽量维持在目标Gas使用量,当父区块的Gas使用量小于目标Gas使用量时,以太坊会降低基本费,而如果大于目标Gas使用量时,会提高基本费。

销毁基本费

以太坊会将小费(最高优先费用)支付给矿工,而基本费将被销毁。因为如果将基本费支付给矿工,矿工会为了追求利益而恶意推高基本费。

以太币过去是一个通胀模型,而这个改变可能使以太币成为一个通缩模型。

发送Type-2交易

使用web3.js以及@ethereumjs/tx库发送Type-2交易。

代码如下:

const EthereumCommon = require('@ethereumjs/common')
const EthereumTx = require('@ethereumjs/tx')

web3.eth.getTransactionCount(address).then(nonce => {
    var txParams = {
        chainId: chainId,
        nonce: web3.utils.toHex(nonce),
        maxFeePerGas: maxFeePerGas, 
        maxPriorityFeePerGas: maxPriorityFeePerGas,
        type: '0x2', //EIP-1559
        gasLimit: 3000000,
        to: address,
        data: data
    };

    var common = new EthereumCommon.default({ chain: EthereumCommon.Chain.Ropsten, hardfork: EthereumCommon.Hardfork.London });
    var tx = EthereumTx.FeeMarketEIP1559Transaction.fromTxData(txParams, { common });

    var signedtx = tx.sign(privatekey);
    var serializedTx = signedtx.serialize();

    web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex')).then(result => {
        //success code
    }).catch(error => {
        //error code
    });
).catch(error => {
    //error code
});

这里@ethereumjs/tx库的用法参考自官方文档:https://www.npmjs.com/package/@ethereumjs/tx

posted @ 2022-05-16 21:59  lnjoy  阅读(955)  评论(0编辑  收藏  举报