@web3-onboard/gas
A module for requesting streams or single requests of gas price estimates from the Blocknative Gas Platform API.
Supports both Eth Mainnet and Polygon gas pricing.
Install
NPM
npm i @web3-onboard/gas
Yarn
yarn add @web3-onboard/gas
Standalone Setup
import gas from '@web3-onboard/gas'
const ethMainnetGasBlockPrices = gas.stream({
chains: ['0x1'],
apiKey: '<OPTIONAL_API_KEY>',
endpoint: 'blockPrices'
})
const { unsubscribe: ethGasUnsub } = ethMainnetGasBlockPrices.subscribe(
estimates => console.log(estimates)
)
setTimeout(ethGasUnsub, 10000)
const gasBlockPrices = gas.stream({
chains: ['0x1', '0x89'],
apiKey: '<OPTIONAL_API_KEY>',
endpoint: 'blockPrices',
poll: 1000
})
const { unsubscribe } = gasBlockPrices.subscribe(estimates =>
console.log(estimates)
console.log(estimates[0].blockPrices[0].estimatedPrice)
console.log(bnGasPrices.find(gas => gas.confidence === 90))
)
setTimeout(unsubscribe, 10000)
const gasBlockPrices = await gas.get({
chains: ['0x1', '0x89'],
apiKey: '<OPTIONAL_API_KEY>',
endpoint: 'blockPrices'
})
Usage with Web3-Onboard wallet Connect and Ethers.js
This example assumes you have already setup web3-onboard to connect wallets to your dapp.
For more information see web3-onboard docs.
import gas from '@web3-onboard/gas'
import { ethers } from 'ethers'
let provider = new ethers.providers.Web3Provider(wallet.provider, 'any')
let bnGasPrices
const ethMainnetGasBlockPrices = gas.stream({
chains: ['0x1'],
apiKey: '<OPTIONAL_API_KEY>',
endpoint: 'blockPrices'
})
ethMainnetGasBlockPrices.subscribe(estimates => {
console.log(estimates)
bnGasPrices = estimates[0].blockPrices[0].estimatedPrices
})
const gweiToWeiHex = gwei => {
return `0x${(gwei * 1e9).toString(16)}`
}
const sendTransaction = async () => {
if (!toAddress) {
alert('An Ethereum address to send Eth to is required.')
return
}
const signer = provider.getUncheckedSigner()
const bnGasForTransaction = bnGasPrices.find(gas => gas.confidence === 90)
const rc = await signer.sendTransaction({
to: toAddress,
value: 1000000000000000
maxPriorityFeePerGas: gweiToWeiHex(
bnGasForTransaction.maxPriorityFeePerGas
),
maxFeePerGas: gweiToWeiHex(bnGasForTransaction.maxFeePerGas)
})
console.log(rc)
}