forked from ethereumjs/ethereumjs-monorepo
-
Notifications
You must be signed in to change notification settings - Fork 4
/
ethersStateManager.spec.ts
277 lines (238 loc) · 10.4 KB
/
ethersStateManager.spec.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import { Block } from '@ethereumjs/block'
import { Chain, Common, Hardfork } from '@ethereumjs/common'
import { FeeMarketEIP1559Transaction, TransactionFactory } from '@ethereumjs/tx'
import {
Account,
Address,
bigIntToBytes,
equalsBytes,
hexStringToBytes,
setLengthLeft,
utf8ToBytes,
} from '@ethereumjs/util'
import { VM } from '@ethereumjs/vm'
import { BaseProvider, StaticJsonRpcProvider } from '@ethersproject/providers'
import { ethers } from 'ethers'
import * as tape from 'tape'
import { EthersStateManager } from '../src/ethersStateManager'
import { MockProvider } from './testdata/providerData/mockProvider'
// Hack to detect if running in browser or not
const isBrowser = new Function('try {return this===window;}catch(e){ return false;}')
// To run the tests with a live provider, set the PROVIDER environmental variable with a valid provider url
// from Infura/Alchemy or your favorite web3 provider when running the test. Below is an example command:
// `PROVIDER=https://mainnet.infura.io/v3/[mySuperS3cretproviderKey] npm run tape -- 'test/ethersStateManager.spec.ts'
tape('Ethers State Manager initialization tests', (t) => {
const provider = new MockProvider()
let state = new EthersStateManager({ provider, blockTag: 1n })
t.ok(
state instanceof EthersStateManager,
'was able to instantiate state manager with JsonRpcProvider subclass'
)
t.equal((state as any).blockTag, '0x1', 'State manager starts with default block tag of 1')
state = new EthersStateManager({ provider, blockTag: 1n })
t.equal((state as any).blockTag, '0x1', 'State Manager instantiated with predefined blocktag')
state = new EthersStateManager({ provider: 'https://google.com', blockTag: 1n })
t.ok(state instanceof EthersStateManager, 'was able to instantiate state manager with valid url')
const invalidProvider = new BaseProvider('mainnet')
t.throws(
() => new EthersStateManager({ provider: invalidProvider as any, blockTag: 1n }),
'cannot instantiate state manager with invalid provider'
)
t.end()
})
tape('Ethers State Manager API tests', async (t) => {
if (isBrowser() === true) {
// The `MockProvider` is not able to load JSON files dynamically in browser so skipped in browser tests
t.end()
} else {
const provider =
process.env.PROVIDER !== undefined
? new StaticJsonRpcProvider(process.env.PROVIDER, 1)
: new MockProvider()
const state = new EthersStateManager({ provider, blockTag: 1n })
const vitalikDotEth = Address.fromString('0xd8da6bf26964af9d7eed9e03e53415d37aa96045')
const account = await state.getAccount(vitalikDotEth)
t.ok(account!.nonce > 0n, 'Vitalik.eth returned a valid nonce')
await state.putAccount(vitalikDotEth, account!)
const retrievedVitalikAccount = Account.fromRlpSerializedAccount(
(state as any)._accountCache.get(vitalikDotEth)!.accountRLP
)
t.ok(retrievedVitalikAccount.nonce > 0n, 'Vitalik.eth is stored in cache')
const doesThisAccountExist = await state.accountExists(
Address.fromString('0xccAfdD642118E5536024675e776d32413728DD07')
)
t.ok(!doesThisAccountExist, 'accountExists returns false for non-existent account')
t.ok(state.accountExists(vitalikDotEth), 'vitalik.eth does exist')
const UNIerc20ContractAddress = Address.fromString('0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984')
const UNIContractCode = await state.getContractCode(UNIerc20ContractAddress)
t.ok(UNIContractCode.length > 0, 'was able to retrieve UNI contract code')
await state.putContractCode(UNIerc20ContractAddress, UNIContractCode)
t.ok(
typeof (state as any).contractCache.get(UNIerc20ContractAddress.toString()) !== 'undefined',
'UNI ERC20 contract code was found in cache'
)
const storageSlot = await state.getContractStorage(
UNIerc20ContractAddress,
setLengthLeft(bigIntToBytes(1n), 32)
)
t.ok(storageSlot.length > 0, 'was able to retrieve storage slot 1 for the UNI contract')
await state.putContractStorage(
UNIerc20ContractAddress,
setLengthLeft(bigIntToBytes(2n), 32),
utf8ToBytes('abcd')
)
const slotValue = await state.getContractStorage(
UNIerc20ContractAddress,
setLengthLeft(bigIntToBytes(2n), 32)
)
t.ok(equalsBytes(slotValue, utf8ToBytes('abcd')), 'should retrieve slot 2 value')
// Verify that provider is not called for cached data
;(provider as any).getStorageAt = function () {
throw new Error('should not be called!')
}
t.doesNotThrow(
async () =>
state.getContractStorage(UNIerc20ContractAddress, setLengthLeft(bigIntToBytes(2n), 32)),
'should not call provider.getStorageAt'
)
await state.putContractStorage(
UNIerc20ContractAddress,
setLengthLeft(bigIntToBytes(2n), 32),
new Uint8Array(0)
)
// Verify that provider is not called
;(state as any).getAccountFromProvider = function () {
throw new Error('should not have called this!')
}
t.doesNotThrow(
async () => state.getAccount(vitalikDotEth),
'does not call getAccountFromProvider'
)
try {
await state.getAccount(Address.fromString('0x9Cef824A8f4b3Dc6B7389933E52e47F010488Fc8'))
} catch (err) {
t.pass('calls getAccountFromProvider for non-cached account')
}
const deletedSlot = await state.getContractStorage(
UNIerc20ContractAddress,
setLengthLeft(bigIntToBytes(2n), 32)
)
t.equal(deletedSlot.length, 0, 'deleted slot from storage cache')
await state.deleteAccount(vitalikDotEth)
t.ok(await state.accountExists(vitalikDotEth), 'account should not exist after being deleted')
try {
await Block.fromJsonRpcProvider(provider, 'fakeBlockTag', {} as any)
t.fail('should have thrown')
} catch (err: any) {
t.ok(
err.message.includes('expected blockTag to be block hash, bigint, hex prefixed string'),
'threw with correct error when invalid blockTag provided'
)
}
const newState = state.copy()
t.equal(
undefined,
(state as any).contractCache.get(UNIerc20ContractAddress),
'should not have any code for contract after cache is cleared'
)
t.notEqual(
undefined,
(newState as any).contractCache.get(UNIerc20ContractAddress.toString()),
'state manager copy should have code for contract after cache is cleared on original state manager'
)
t.equal((state as any).blockTag, '0x1', 'blockTag defaults to 1')
state.setBlockTag(5n)
t.equal((state as any).blockTag, '0x5', 'blockTag set to 0x5')
state.setBlockTag('earliest')
t.equal((state as any).blockTag, 'earliest', 'blockTag set to earliest')
t.end()
}
})
tape('runTx custom transaction test', async (t) => {
if (isBrowser() === true) {
// The `MockProvider` is not able to load JSON files dynamically in browser so skipped in browser tests
t.end()
} else {
const common = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.London })
const provider =
process.env.PROVIDER !== undefined
? new StaticJsonRpcProvider(process.env.PROVIDER, 1)
: new MockProvider()
const state = new EthersStateManager({ provider, blockTag: 1n })
const vm = await VM.create({ common, stateManager: <any>state }) // TODO fix the type DefaultStateManager back to StateManagerInterface in VM
const vitalikDotEth = Address.fromString('0xd8da6bf26964af9d7eed9e03e53415d37aa96045')
const privateKey = hexStringToBytes(
'e331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109'
)
const tx = FeeMarketEIP1559Transaction.fromTxData(
{ to: vitalikDotEth, value: '0x100', gasLimit: 500000n, maxFeePerGas: 7 },
{ common }
).sign(privateKey)
const result = await vm.runTx({
skipBalance: true,
skipNonce: true,
tx,
})
t.equal(result.totalGasSpent, 21000n, 'sent some ETH to vitalik.eth')
t.end()
}
})
tape('runTx test: replay mainnet transactions', async (t) => {
if (isBrowser() === true) {
// The `MockProvider` is not able to load JSON files dynamically in browser so skipped in browser tests
t.end()
} else {
const common = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.London })
const provider =
process.env.PROVIDER !== undefined
? new ethers.providers.JsonRpcProvider(process.env.PROVIDER)
: new MockProvider()
const blockTag = 15496077n
common.setHardforkByBlockNumber(blockTag)
const txData = require('./testdata/providerData/transactions/0xed1960aa7d0d7b567c946d94331dddb37a1c67f51f30bf51f256ea40db88cfb0.json')
const tx = await TransactionFactory.fromRPCTx(txData, { common })
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: <any>state })
const res = await vm.runTx({ tx })
t.equal(res.totalGasSpent, 21000n, 'calculated correct total gas spent for simple transfer')
t.end()
}
})
tape('runBlock test', async (t) => {
if (isBrowser() === true) {
// The `MockProvider` is not able to load JSON files dynamically in browser so skipped in browser tests
t.end()
} else {
const common = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.Chainstart })
const provider =
process.env.PROVIDER !== undefined
? new ethers.providers.JsonRpcProvider(process.env.PROVIDER)
: new MockProvider()
const blockTag = 500000n
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,
})
// Set the common to HF, doesn't impact this specific blockTag, but will impact much recent
// blocks, also for post merge network, ttd should also be passed
common.setHardforkByBlockNumber(blockTag - 1n)
const vm = await VM.create({ common, stateManager: state })
const blockData = require('./testdata/providerData/blocks/block0x7a120.json')
const block = Block.fromRPC(blockData, [], { common })
try {
const res = await vm.runBlock({
block,
generate: true,
skipHeaderValidation: true,
})
t.equal(res.gasUsed, block.header.gasUsed, 'should compute correct cumulative gas for block')
} catch (err: any) {
t.fail(`should have successfully ran block; got error ${err.message}`)
}
}
})