github.com/ethereum-optimism/optimism@v1.7.2/packages/web3js-plugin/README.md (about)

     1  # @eth-optimism/web3.js-plugin
     2  
     3  This web3.js plugin adds utility functions for estimating L1 and L2 gas for OP chains by wrapping the [GasPriceOracle](../contracts-bedrock/contracts/l2/GasPriceOracle.sol) contract
     4  
     5  The GasPriceOracle is [deployed to Optimism](https://optimistic.etherscan.io/address/0x420000000000000000000000000000000000000F) and other OP chains at a predeployed address of `0x420000000000000000000000000000000000000F`
     6  
     7  For more detailed information about gas fees on Optimism's Layer 2, you can visit the [official documentation](https://community.optimism.io/docs/developers/build/transaction-fees/#the-l2-execution-fee)
     8  
     9  ## Installation
    10  
    11  This plugin is intended to be [registered](https://docs.web3js.org/guides/web3_plugin_guide/plugin_users#registering-the-plugin) onto an instance of `Web3`. It has a [peerDependency](https://nodejs.org/es/blog/npm/peer-dependencies) of `web3` version `4.x`, so make sure you have that latest version of `web3` installed for your project before installing the plugin
    12  
    13  ### Installing the Plugin
    14  
    15  ```bash
    16  pnpm install @eth-optimism/web3.js-plugin
    17  ```
    18  
    19  ```bash
    20  npm install @eth-optimism/web3.js-plugin
    21  ```
    22  
    23  ```bash
    24  yarn add @eth-optimism/web3.js-plugin
    25  ```
    26  
    27  ### Registering the Plugin
    28  
    29  ```typescript
    30  import Web3 from 'web3'
    31  import { OptimismPlugin } from '@eth-optimism/web3.js-plugin'
    32  
    33  const web3 = new Web3('http://yourProvider.com')
    34  web3.registerPlugin(new OptimismPlugin())
    35  ```
    36  
    37  You will now have access to the following functions under the `op` namespace, i.e. `web3.op.someMethod`
    38  
    39  ## API
    40  
    41  | Function Name                            | Returns                                                                                                                                                                                                                |
    42  | ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
    43  | [estimateFees](#estimatefees)            | The combined estimated L1 and L2 fees for a transaction                                                                                                                                                                |
    44  | [getL1Fee](#getl1fee)                    | The L1 portion of the fee based on the size of the [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/) encoded transaction, the current L1 base fee, and other various dynamic parameters |
    45  | [getL2Fee](#getl2fee)                    | The L2 portion of the fee based on the simulated execution of the provided transaction and current `gasPrice`                                                                                                          |
    46  | [getBaseFee](#getbasefee)                | The current L2 base fee                                                                                                                                                                                                |
    47  | [getDecimals](#getdecimals)              | The decimals used in the scalar                                                                                                                                                                                        |
    48  | [getGasPrice](#getgasprice)              | The current L2 gas price                                                                                                                                                                                               |
    49  | [getL1GasUsed](#getl1gasused)            | The amount of L1 gas estimated to be used to execute a transaction                                                                                                                                                     |
    50  | [getL1BaseFee](#getdegetl1basefeecimals) | The L1 base fee                                                                                                                                                                                                        |
    51  | [getOverhead](#getoverhead)              | The current overhead                                                                                                                                                                                                   |
    52  | [getScalar](#getscalar)                  | The current fee scalar                                                                                                                                                                                                 |
    53  | [getVersion](#getversion)                | The current version of `GasPriceOracle`                                                                                                                                                                                |
    54  
    55  ---
    56  
    57  ### `estimateFees`
    58  
    59  Computes the total (L1 + L2) fee estimate to execute a transaction
    60  
    61  ```typescript
    62  async estimateFees(transaction: Transaction, returnFormat?: ReturnFormat)
    63  ```
    64  
    65  #### Parameters
    66  
    67  - `transaction: Transaction` - An unsigned web3.js [transaction](https://docs.web3js.org/api/web3-types/interface/Transaction) object
    68  - `returnFormat?: ReturnFormat` - A web3.js [DataFormat][1] object that specifies how to format number and bytes values
    69    - If `returnFormat` is not provided, [DEFAULT_RETURN_FORMAT][2] is used which will format numbers to `BigInt`s
    70  
    71  #### Returns
    72  
    73  - `Promise<Numbers>` - The estimated total fee as a `BigInt` by default, but `returnFormat` determines type
    74  
    75  #### Example
    76  
    77  ```typescript
    78  import Web3 from 'web3'
    79  import { OptimismPlugin } from '@eth-optimism/web3.js-plugin'
    80  import {
    81    l2StandardBridgeABI,
    82    l2StandardBridgeAddress,
    83  } from '@eth-optimism/contracts-ts'
    84  
    85  const web3 = new Web3('https://mainnet.optimism.io')
    86  web3.registerPlugin(new OptimismPlugin())
    87  
    88  const l2BridgeContract = new web3.eth.Contract(
    89    l2StandardBridgeABI,
    90    optimistAddress[420]
    91  )
    92  const encodedWithdrawMethod = l2BridgeContract.methods
    93    .withdraw(
    94      // l2 token address
    95      '0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000',
    96      // amount
    97      Web3.utils.toWei('0.00000001', 'ether'),
    98      // l1 gas
    99      0,
   100      // extra data
   101      '0x00'
   102    )
   103    .encodeABI()
   104  
   105  const totalFee = await web3.op.estimateFees({
   106    chainId: 10,
   107    data: encodedWithdrawMethod,
   108    value: Web3.utils.toWei('0.00000001', 'ether'),
   109    type: 2,
   110    to: '0x420000000000000000000000000000000000000F',
   111    from: '0x6387a88a199120aD52Dd9742C7430847d3cB2CD4',
   112    maxFeePerGas: Web3.utils.toWei('0.2', 'gwei'),
   113    maxPriorityFeePerGas: Web3.utils.toWei('0.1', 'gwei'),
   114  })
   115  
   116  console.log(totalFee) // 26608988767659n
   117  ```
   118  
   119  ##### Formatting Response as a Hex String
   120  
   121  ```typescript
   122  import Web3 from 'web3'
   123  import { OptimismPlugin } from '@eth-optimism/web3.js-plugin'
   124  import {
   125    l2StandardBridgeABI,
   126    l2StandardBridgeAddress,
   127  } from '@eth-optimism/contracts-ts'
   128  
   129  const web3 = new Web3('https://mainnet.optimism.io')
   130  web3.registerPlugin(new OptimismPlugin())
   131  
   132  const l2BridgeContract = new web3.eth.Contract(
   133    l2StandardBridgeABI,
   134    optimistAddress[420]
   135  )
   136  const encodedWithdrawMethod = l2BridgeContract.methods
   137    .withdraw(
   138      // l2 token address
   139      '0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000',
   140      // amount
   141      Web3.utils.toWei('0.00000001', 'ether'),
   142      // l1 gas
   143      0,
   144      // extra data
   145      '0x00'
   146    )
   147    .encodeABI()
   148  
   149  const totalFee = await web3.op.estimateFees(
   150    {
   151      chainId: 10,
   152      data: encodedWithdrawMethod,
   153      value: Web3.utils.toWei('0.00000001', 'ether'),
   154      type: 2,
   155      to: '0x420000000000000000000000000000000000000F',
   156      from: '0x6387a88a199120aD52Dd9742C7430847d3cB2CD4',
   157      maxFeePerGas: Web3.utils.toWei('0.2', 'gwei'),
   158      maxPriorityFeePerGas: Web3.utils.toWei('0.1', 'gwei'),
   159    },
   160    { number: FMT_NUMBER.HEX, bytes: FMT_BYTES.HEX }
   161  )
   162  
   163  console.log(totalFee) // 0x18336352c5ab
   164  ```
   165  
   166  ### `getL1Fee`
   167  
   168  Computes the L1 portion of the fee based on the size of the rlp encoded input transaction, the current L1 base fee, and the various dynamic parameters
   169  
   170  ```typescript
   171  async getL1Fee(transaction: Transaction, returnFormat?: ReturnFormat)
   172  ```
   173  
   174  #### Parameters
   175  
   176  - `transaction: Transaction` - An unsigned web3.js [transaction](https://docs.web3js.org/api/web3-types/interface/Transaction) object
   177  - `returnFormat?: ReturnFormat` - A web3.js [DataFormat][1] object that specifies how to format number and bytes values
   178    - If `returnFormat` is not provided, [DEFAULT_RETURN_FORMAT][2] is used which will format numbers to `BigInt`s
   179  
   180  #### Returns
   181  
   182  - `Promise<Numbers>` - The estimated L1 fee as a `BigInt` by default, but `returnFormat` determines type
   183  
   184  #### Example
   185  
   186  ```typescript
   187  import { Contract } from 'web3'
   188  import { optimistABI, optimistAddress } from '@eth-optimism/contracts-ts'
   189  
   190  const optimistContract = new Contract(optimistABI, optimistAddress[420])
   191  const encodedBurnMethod = optimistContract.methods
   192    .burn('0x77194aa25a06f932c10c0f25090f3046af2c85a6')
   193    .encodeABI()
   194  
   195  const l1Fee = await web3.op.getL1Fee({
   196    chainId: 10,
   197    data: encodedBurnMethod,
   198    type: 2,
   199  })
   200  
   201  console.log(l1Fee) // 18589035222172n
   202  ```
   203  
   204  ##### Formatting Response as a Hex String
   205  
   206  ```typescript
   207  import { Contract } from 'web3'
   208  import { optimistABI, optimistAddress } from '@eth-optimism/contracts-ts'
   209  
   210  const optimistContract = new Contract(optimistABI, optimistAddress[420])
   211  const encodedBurnMethod = optimistContract.methods
   212    .burn('0x77194aa25a06f932c10c0f25090f3046af2c85a6')
   213    .encodeABI()
   214  
   215  const l1Fee = await web3.op.getL1Fee(
   216    {
   217      chainId: 10,
   218      data: encodedBurnMethod,
   219      type: 2,
   220    },
   221    { number: FMT_NUMBER.HEX, bytes: FMT_BYTES.HEX }
   222  )
   223  
   224  console.log(l1Fee) // 0x10e818d7549c
   225  ```
   226  
   227  ### `getL2Fee`
   228  
   229  Retrieves the amount of L2 gas estimated to execute `transaction`
   230  
   231  ```typescript
   232  async getL2Fee(transaction: Transaction, returnFormat?: ReturnFormat)
   233  ```
   234  
   235  #### Parameters
   236  
   237  - `transaction: Transaction` - An unsigned web3.js [transaction](https://docs.web3js.org/api/web3-types/interface/Transaction) object
   238  - `options?: { blockNumber?: BlockNumberOrTag, returnFormat?: ReturnFormat }` - An optional object with properties:
   239    - `blockNumber?: BlockNumberOrTag` - Specifies what block to use for gas estimation. Can be either:
   240      - **Note** Specifying a block to estimate L2 gas for is currently not working
   241      - A web3.js [Numbers](https://docs.web3js.org/api/web3-types#Numbers)
   242      - A web3.js [BlockTags](https://docs.web3js.org/api/web3-types/enum/BlockTags)
   243      - If not provided, `BlockTags.LATEST` is used
   244    - `returnFormat?: ReturnFormat` - A web3.js [DataFormat][1] object that specifies how to format number and bytes values
   245      - If `returnFormat` is not provided, [DEFAULT_RETURN_FORMAT][2] is used which will format numbers to `BigInt`s
   246  
   247  #### Returns
   248  
   249  - `Promise<Numbers>` - The estimated total fee as a `BigInt` by default, but `returnFormat` determines type
   250  
   251  #### Example
   252  
   253  ```typescript
   254  import { Contract } from 'web3'
   255  import { optimistABI, optimistAddress } from '@eth-optimism/contracts-ts'
   256  
   257  const optimistContract = new Contract(optimistABI, optimistAddress[420])
   258  const encodedBurnMethod = optimistContract.methods
   259    .burn('0x77194aa25a06f932c10c0f25090f3046af2c85a6')
   260    .encodeABI()
   261  
   262  const l2Fee = await web3.op.getL2Fee({
   263    chainId: '0xa',
   264    data: encodedBurnMethod,
   265    type: '0x2',
   266    to: optimistAddress[420],
   267    from: '0x77194aa25a06f932c10c0f25090f3046af2c85a6',
   268  })
   269  
   270  console.log(l2Fee) // 2659500n
   271  ```
   272  
   273  ##### Formatting Response as a Hex String
   274  
   275  ```typescript
   276  import { Contract } from 'web3'
   277  import { optimistABI, optimistAddress } from '@eth-optimism/contracts-ts'
   278  
   279  const optimistContract = new Contract(optimistABI, optimistAddress[420])
   280  const encodedBurnMethod = optimistContract.methods
   281    .burn('0x77194aa25a06f932c10c0f25090f3046af2c85a6')
   282    .encodeABI()
   283  
   284  const l2Fee = await web3.op.getL2Fee(
   285    {
   286      chainId: '0xa',
   287      data: encodedBurnMethod,
   288      type: '0x2',
   289      to: optimistAddress[420],
   290      from: '0x77194aa25a06f932c10c0f25090f3046af2c85a6',
   291    },
   292    {
   293      returnFormat: { number: FMT_NUMBER.HEX, bytes: FMT_BYTES.HEX },
   294    }
   295  )
   296  
   297  console.log(l2Fee) // 0x2894ac
   298  ```
   299  
   300  ### `getBaseFee`
   301  
   302  Retrieves the current L2 base fee
   303  
   304  ```typescript
   305  async getBaseFee(returnFormat?: ReturnFormat)
   306  ```
   307  
   308  #### Parameters
   309  
   310  - `returnFormat?: ReturnFormat` - A web3.js [DataFormat][1] object that specifies how to format number and bytes values
   311    - If `returnFormat` is not provided, [DEFAULT_RETURN_FORMAT][2] is used which will format numbers to `BigInt`s
   312  
   313  #### Returns
   314  
   315  - `Promise<Numbers>` - The L2 base fee as a `BigInt` by default, but `returnFormat` determines type
   316  
   317  #### Example
   318  
   319  ```typescript
   320  const baseFee = await web3.op.getBaseFee()
   321  
   322  console.log(baseFee) // 68n
   323  ```
   324  
   325  ##### Formatting Response as a Hex String
   326  
   327  ```typescript
   328  const baseFee = await web3.op.getBaseFee({
   329    number: FMT_NUMBER.HEX,
   330    bytes: FMT_BYTES.HEX,
   331  })
   332  
   333  console.log(baseFee) // 0x44
   334  ```
   335  
   336  ### `getDecimals`
   337  
   338  Retrieves the decimals used in the scalar
   339  
   340  ```typescript
   341  async getDecimals(returnFormat?: ReturnFormat)
   342  ```
   343  
   344  #### Parameters
   345  
   346  - `returnFormat?: ReturnFormat` - A web3.js [DataFormat][3] object that specifies how to format number and bytes values
   347    - If `returnFormat` is not provided, [DEFAULT_RETURN_FORMAT][2] is used which will format numbers to `BigInt`s
   348  
   349  #### Returns
   350  
   351  - `Promise<Numbers>` - The number of decimals as a `BigInt` by default, but `returnFormat` determines type
   352  
   353  #### Example
   354  
   355  ```typescript
   356  const decimals = await web3.op.getDecimals()
   357  
   358  console.log(decimals) // 6n
   359  ```
   360  
   361  ##### Formatting Response as a Hex String
   362  
   363  ```typescript
   364  const decimals = await web3.op.getDecimals({
   365    number: FMT_NUMBER.HEX,
   366    bytes: FMT_BYTES.HEX,
   367  })
   368  
   369  console.log(decimals) // 0x6
   370  ```
   371  
   372  ### `getGasPrice`
   373  
   374  Retrieves the current L2 gas price (base fee)
   375  
   376  ```typescript
   377  async getGasPrice(returnFormat?: ReturnFormat)
   378  ```
   379  
   380  #### Parameters
   381  
   382  - `returnFormat?: ReturnFormat` - A web3.js [DataFormat][3] object that specifies how to format number and bytes values
   383    - If `returnFormat` is not provided, [DEFAULT_RETURN_FORMAT][2] is used which will format numbers to `BigInt`s
   384  
   385  #### Returns
   386  
   387  - `Promise<Numbers>` - The current L2 gas price as a `BigInt` by default, but `returnFormat` determines type
   388  
   389  #### Example
   390  
   391  ```typescript
   392  const gasPrice = await web3.op.getGasPrice()
   393  
   394  console.log(gasPrice) // 77n
   395  ```
   396  
   397  ##### Formatting Response as a Hex String
   398  
   399  ```typescript
   400  const gasPrice = await web3.op.getGasPrice({
   401    number: FMT_NUMBER.HEX,
   402    bytes: FMT_BYTES.HEX,
   403  })
   404  
   405  console.log(gasPrice) // 0x4d
   406  ```
   407  
   408  ### `getL1GasUsed`
   409  
   410  Computes the amount of L1 gas used for {transaction}. Adds the overhead which represents the per-transaction gas overhead of posting the {transaction} and state roots to L1. Adds 68 bytes of padding to account for the fact that the input does not have a signature.
   411  
   412  ```typescript
   413  async getL1GasUsed(transaction: Transaction, returnFormat?: ReturnFormat)
   414  ```
   415  
   416  #### Parameters
   417  
   418  - `transaction: Transaction` - An unsigned web3.js [transaction](https://docs.web3js.org/api/web3-types/interface/Transaction) object
   419  - `returnFormat?: ReturnFormat` - A web3.js [DataFormat][3] object that specifies how to format number and bytes values
   420    - If `returnFormat` is not provided, [DEFAULT_RETURN_FORMAT][2] is used which will format numbers to `BigInt`s
   421  
   422  #### Returns
   423  
   424  - `Promise<Numbers>` - The amount of gas as a `BigInt` by default, but `returnFormat` determines type
   425  
   426  #### Example
   427  
   428  ```typescript
   429  import { Contract } from 'web3'
   430  import { optimistABI, optimistAddress } from '@eth-optimism/contracts-ts'
   431  
   432  const optimistContract = new Contract(optimistABI, optimistAddress[420])
   433  const encodedBurnMethod = optimistContract.methods
   434    .burn('0x77194aa25a06f932c10c0f25090f3046af2c85a6')
   435    .encodeABI()
   436  
   437  const l1GasUsed = await web3.op.getL1GasUsed({
   438    chainId: 10,
   439    data: encodedBurnMethod,
   440    type: 2,
   441  })
   442  
   443  console.log(l1GasUsed) // 1884n
   444  ```
   445  
   446  ##### Formatting Response as a Hex String
   447  
   448  ```typescript
   449  import { Contract } from 'web3'
   450  import { optimistABI, optimistAddress } from '@eth-optimism/contracts-ts'
   451  
   452  const optimistContract = new Contract(optimistABI, optimistAddress[420])
   453  const encodedBurnMethod = optimistContract.methods
   454    .burn('0x77194aa25a06f932c10c0f25090f3046af2c85a6')
   455    .encodeABI()
   456  
   457  const l1GasUsed = await web3.op.getL1GasUsed(
   458    {
   459      chainId: 10,
   460      data: encodedBurnMethod,
   461      type: 2,
   462    },
   463    { number: FMT_NUMBER.HEX, bytes: FMT_BYTES.HEX }
   464  )
   465  
   466  console.log(l1GasUsed) // 0x75c
   467  ```
   468  
   469  ### `getL1BaseFee`
   470  
   471  Retrieves the latest known L1 base fee
   472  
   473  ```typescript
   474  async getL1BaseFee(returnFormat?: ReturnFormat)
   475  ```
   476  
   477  #### Parameters
   478  
   479  - `returnFormat?: ReturnFormat` - A web3.js [DataFormat][3] object that specifies how to format number and bytes values
   480    - If `returnFormat` is not provided, [DEFAULT_RETURN_FORMAT][2] is used which will format numbers to `BigInt`s
   481  
   482  #### Returns
   483  
   484  - `Promise<Numbers>` - The L1 base fee as a `BigInt` by default, but `returnFormat` determines type
   485  
   486  #### Example
   487  
   488  ```typescript
   489  const baseFee = await web3.op.getL1BaseFee()
   490  
   491  console.log(baseFee) // 13752544112n
   492  ```
   493  
   494  ##### Formatting Response as a Hex String
   495  
   496  ```typescript
   497  const baseFee = await web3.op.getL1BaseFee({
   498    number: FMT_NUMBER.HEX,
   499    bytes: FMT_BYTES.HEX,
   500  })
   501  
   502  console.log(baseFee) // 0x333b72b70
   503  ```
   504  
   505  ### `getOverhead`
   506  
   507  Retrieves the current fee overhead
   508  
   509  ```typescript
   510  async getOverhead(returnFormat?: ReturnFormat)
   511  ```
   512  
   513  #### Parameters
   514  
   515  - `returnFormat?: ReturnFormat` - A web3.js [DataFormat][3] object that specifies how to format number and bytes values
   516    - If `returnFormat` is not provided, [DEFAULT_RETURN_FORMAT][2] is used which will format numbers to `BigInt`s
   517  
   518  #### Returns
   519  
   520  - `Promise<Numbers>` - The current overhead as a `BigInt` by default, but `returnFormat` determines type
   521  
   522  #### Example
   523  
   524  ```typescript
   525  const overhead = await web3.op.getOverhead()
   526  
   527  console.log(overhead) // 188n
   528  ```
   529  
   530  ##### Formatting Response as a Hex String
   531  
   532  ```typescript
   533  const overhead = await web3.op.getOverhead({
   534    number: FMT_NUMBER.HEX,
   535    bytes: FMT_BYTES.HEX,
   536  })
   537  
   538  console.log(overhead) // 0xbc
   539  ```
   540  
   541  ### `getScalar`
   542  
   543  Retrieves the current fee scalar
   544  
   545  ```typescript
   546  async getScalar(returnFormat?: ReturnFormat)
   547  ```
   548  
   549  #### Parameters
   550  
   551  - `returnFormat?: ReturnFormat` - A web3.js [DataFormat][1] object that specifies how to format number and bytes values
   552    - If `returnFormat` is not provided, [DEFAULT_RETURN_FORMAT][2] is used which will format numbers to `BigInt`s
   553  
   554  #### Returns
   555  
   556  - `Promise<Numbers>` - The current scalar fee as a `BigInt` by default, but `returnFormat` determines type
   557  
   558  #### Example
   559  
   560  ```typescript
   561  const scalarFee = await web3.op.getScalar()
   562  
   563  console.log(scalarFee) // 684000n
   564  ```
   565  
   566  ##### Formatting Response as a Hex String
   567  
   568  ```typescript
   569  const scalarFee = await web3.op.getScalar({
   570    number: FMT_NUMBER.HEX,
   571    bytes: FMT_BYTES.HEX,
   572  })
   573  
   574  console.log(scalarFee) // 0xa6fe0
   575  ```
   576  
   577  ### `getVersion`
   578  
   579  Retrieves the full semver version of GasPriceOracle
   580  
   581  ```typescript
   582  async getVersion()
   583  ```
   584  
   585  #### Returns
   586  
   587  - `Promise<string>` - The semver version
   588  
   589  #### Example
   590  
   591  ```typescript
   592  const version = await web3.op.getVersion()
   593  
   594  console.log(version) // 1.0.0
   595  ```
   596  
   597  ## Known Issues
   598  
   599  - As of version `4.0.3` of web3.js, both `input` and `data` parameters are automatically added to a transaction objects causing the gas estimations to be inflated. This was corrected in [this](https://github.com/web3/web3.js/pull/6294) PR, but has yet to be released
   600  - For the plugin function `getL2Fee`, you should be able to get the fee estimates using the state of the blockchain at a specified block, however, this doesn't seem to be working with web3.js and requires further investigation
   601  
   602  [1]: https://docs.web3js.org/api/web3-types#DataFormat
   603  [2]: https://docs.web3js.org/api/web3-types#DEFAULT_RETURN_FORMAT
   604  [3]: https://docs.web3js.org/api/web3-types#DataFormat