Skip to content

Instantly share code, notes, and snippets.

@holgerd77
Created October 5, 2022 11:05
Show Gist options
  • Save holgerd77/3a7a2dd11babc58daa1264632ba69836 to your computer and use it in GitHub Desktop.
Save holgerd77/3a7a2dd11babc58daa1264632ba69836 to your computer and use it in GitHub Desktop.
Ethers State Manager Consecutive Mainnet Block Test
import { Chain, Common, Hardfork } from '@ethereumjs/common'
import { Account, Address, bigIntToHex, bufferToBigInt, bufferToHex } from '@ethereumjs/util'
import { VM } from '@ethereumjs/vm'
import { JsonRpcProvider } from '@ethersproject/providers'
import { EthersStateManager } from '../src/ethersStateManager'
const run = async () => {
const infura = 'https://mainnet.infura.io/v3/[YOUR-INFURA-KEY]'
const provider = new JsonRpcProvider(infura)
const stateManager = new EthersStateManager({ provider })
// Example 1
const vitalikDotEth = Address.fromString('0xd8da6bf26964af9d7eed9e03e53415d37aa96045')
const account = await stateManager.getAccount(vitalikDotEth)
console.log('Vitalik has a current ETH balance of ', account.balance)
// Example 2
const common = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.Chainstart })
const startBlockTags = [2000000n]
const numRuns = 10
for (const startBlockTag of startBlockTags) {
for (let i = 0n; i < numRuns; i++) {
const blockTag = BigInt(startBlockTag + i)
common.setHardforkByBlockNumber(blockTag)
if (i === 0n) {
console.log(`Starting with block ${blockTag} (${common.hardfork()})...`)
}
const state = new EthersStateManager({
provider,
// Set the state manager to look at the state of the chain before the block has been executed
blockTag: blockTag - 1n,
})
const vm = await VM.create({ common, stateManager: state })
const previousStateRoot = Buffer.from(
(
await provider.send('eth_getBlockByNumber', [bigIntToHex(blockTag - 1n), true])
).stateRoot.slice(2),
'hex'
)
const beforeTS = Date.now()
const block = await state.getBlockFromProvider(blockTag, common)
const afterGetBlockTS = Date.now()
try {
const res = await vm.runBlock({
block,
root: previousStateRoot,
generate: true,
skipHeaderValidation: true,
})
const afterRunBlockTS = Date.now()
const getTime = (afterGetBlockTS - beforeTS) / 1000
const runTime = (afterRunBlockTS - afterGetBlockTS) / 1000
const totalTime = (afterRunBlockTS - beforeTS) / 1000
let out = `Block ${blockTag} (${common.hardfork()}) - ${block.transactions.length} txs: `
out += `${bufferToHex(block.header.stateRoot).substring(0, 8)}.. gasUsed (result/header): ${
res.gasUsed
}/${block.header.gasUsed} ${res.gasUsed !== block.header.gasUsed ? '(ERROR)' : ''}, `
out += `Time: ${getTime}s GET / ${runTime}s RUN / ${totalTime}s TOTAL`
console.log(out)
} catch (e) {
console.log(e)
}
}
}
}
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment