-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
callHandler.js
468 lines (458 loc) · 22.5 KB
/
callHandler.js
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
import { runCallWithTrace } from '../internal/runCallWithTrace.js'
import { callHandlerOpts } from './callHandlerOpts.js'
import { callHandlerResult } from './callHandlerResult.js'
import { maybeThrowOnFail } from './maybeThrowOnFail.js'
import { validateCallParams } from '@tevm/zod'
import { createTransaction } from './createTransaction.js'
import { EthjsAccount, EthjsAddress, bytesToBigint, bytesToHex } from '@tevm/utils'
import { forkAndCacheBlock } from '../internal/forkAndCacheBlock.js'
import { mineHandler } from './mineHandler.js'
import { runTx } from '@tevm/vm'
import { evmInputToImpersonatedTx } from '../internal/evmInputToImpersonatedTx.js'
/**
* The callHandler is the most important function in Tevm.
* It is the direct implementation of `tevm_call`.
* It is also wrapped by all call-like actions including
* - `tevm_contract`
* - `tevm_script`
* - `eth_call`
* - `debug_traceCall`
* - etc.
*
* If it needs to create a transaction on the chain it sends it's results to [createTransactionHandler](./createTrasactionHandler.js)
*
* It has 5 steps
* 0. Validate params
* 1. Clone vm
* 2. Run vm
* 3. Create tx (if necessary)
* 4. Return result
*/
/**
* Creates an CallHandler for handling call params with Ethereumjs EVM
* @param {import('@tevm/base-client').BaseClient} client
* @param {object} [options]
* @param {boolean} [options.throwOnFail]
* @returns {import('@tevm/actions-types').CallHandler}
*/
export const callHandler =
(client, { throwOnFail: defaultThrowOnFail = true } = {}) =>
async (params) => {
/**
* ***************
* 0 VALIDATE PARAMS
* ***************
*/
client.logger.debug(params, 'callHandler: Executing call with params')
const validationErrors = validateCallParams(params)
if (validationErrors.length > 0) {
client.logger.debug(validationErrors, 'Params do not pass validation')
return maybeThrowOnFail(params.throwOnFail ?? defaultThrowOnFail, {
errors: validationErrors,
executionGasUsed: 0n,
/**
* @type {`0x${string}`}
*/
rawData: '0x',
})
}
const { errors, data: evmInput } = await callHandlerOpts(client, params)
if (errors ?? !evmInput) {
client.logger.error(
errors ?? evmInput,
'callHandler: Unexpected error converting params to ethereumjs params',
)
return maybeThrowOnFail(params.throwOnFail ?? defaultThrowOnFail, {
errors: /** @type {import('@tevm/errors').CallError[]}*/ (errors),
executionGasUsed: 0n,
rawData: /** @type {`0x${string}`}*/('0x'),
})
}
/**
* ************
* 1 CLONE THE VM WITH BLOCK TAG
* ************
*/
client.logger.debug(
'Cloning vm to execute a call...',
)
/**
* @type {import('@tevm/vm').Vm}
*/
let vm
try {
vm = await client.getVm().then(vm => vm.deepCopy())
const block = evmInput?.block
// this will never happen the type is wrong internally
if (!block) {
throw new Error('UnexpectedError: Internal block header does not have a state root. This potentially indicates a bug in tevm')
}
if (params.createTransaction && block !== await vm.blockchain.getCanonicalHeadBlock()) {
throw new Error('Creating transactions on past blocks is not currently supported')
}
// TODO why doesn't this type have stateRoot prop? It is always there.
// Haven't looked into it so it might be a simple fix.
/**
* @type {Uint8Array}
*/
const stateRoot = /** @type any*/(block.header).stateRoot
if (client.forkTransport && !(await vm.stateManager.hasStateRoot(stateRoot))) {
forkAndCacheBlock(client, /** @type any*/(block))
}
await vm.stateManager.setStateRoot(stateRoot)
// if we are forking we need to update the block tag we are forking if the block is in past
const forkBlock = vm.blockchain.blocksByTag.get('forked')
if (client.forkTransport && forkBlock !== undefined && block.header.number < forkBlock.header.number) {
vm.stateManager._baseState.options.fork = {
transport: client.forkTransport,
blockTag: block.header.number,
}
vm.blockchain.blocksByTag.set('forked', /** @type {any} */(block))
}
} catch (e) {
client.logger.error(e, 'callHandler: Unexpected error failed to clone vm')
return maybeThrowOnFail(params.throwOnFail ?? defaultThrowOnFail, {
errors: [
{
name: 'UnexpectedError',
_tag: 'UnexpectedError',
message:
typeof e === 'string'
? e
: e instanceof Error
? e.message
: typeof e === 'object' && e !== null && 'message' in e
? e.message
: 'unknown error',
},
],
executionGasUsed: 0n,
rawData: '0x',
})
}
// Do a quick defensive check
const shouldHaveContract = evmInput.to && evmInput.data && bytesToBigint(evmInput.data) !== 0n
const isContract = evmInput.to && (await vm.stateManager.getContractCode(evmInput.to)).length > 0
if (shouldHaveContract && !isContract) {
client.logger.warn(`Data is being passed in a call to a to address ${evmInput.to?.toString()} with no contract bytecode!`)
}
/**
* ************
* 2 RUN THE EVM
* ************
*/
/**
* @type {import('@tevm/vm').RunTxResult | undefined}
*/
let evmOutput = undefined
/**
* @type {import('@tevm/actions-types').DebugTraceCallResult | undefined}
*/
let trace = undefined
/**
* evm returns an access list without the 0x prefix
* @type {Map<string, Set<string>> | undefined}
*/
let accessList = undefined
try {
client.logger.debug({
to: evmInput.to?.toString(),
origin: evmInput.origin?.toString(),
caller: evmInput.caller?.toString(),
value: evmInput.value?.toString(),
gasLimit: evmInput.gasLimit?.toString(),
data: evmInput.data
}, 'callHandler: Executing runCall with params')
if (params.createTrace) {
// this trace will be filled in when the tx runs
trace = await runCallWithTrace(
vm,
client.logger,
evmInput,
true,
).then(({ trace }) => trace)
}
try {
evmOutput = await runTx(vm)({
reportAccessList: params.createAccessList ?? false,
reportPreimages: params.createAccessList ?? false,
skipHardForkValidation: true,
skipBlockGasLimitValidation: true,
// we currently set the nonce ourselves user can't set it
skipNonce: true,
skipBalance: evmInput.skipBalance ?? false,
...(evmInput.block !== undefined ? { block: /** @type any*/(evmInput.block) } : {}),
tx: await evmInputToImpersonatedTx({
...client,
getVm: () => Promise.resolve(vm)
})(evmInput)
})
} catch (e) {
if (!(e instanceof Error)) {
throw e
}
if (e.message.includes('is less than the block\'s baseFeePerGas')) {
return maybeThrowOnFail(
params.throwOnFail ?? defaultThrowOnFail,
{
errors: [
{
name: 'GasPriceTooLow',
_tag: 'GasPriceTooLow',
message: e.message
}
],
executionGasUsed: 0n,
rawData: '0x',
...(evmOutput && await callHandlerResult(evmInput, evmOutput, undefined, trace, accessList, vm))
}
)
}
if (e.message.includes('invalid sender address, address is not an EOA (EIP-3607)')) {
return maybeThrowOnFail(
params.throwOnFail ?? defaultThrowOnFail,
{
errors: [
{
name: 'InvalidSender',
_tag: 'InvalidSender',
message: e.message
}
],
executionGasUsed: 0n,
rawData: '0x',
...(evmOutput && await callHandlerResult(evmInput, evmOutput, undefined, trace, accessList, vm))
}
)
}
if (e.message.includes('is lower than the minimum gas limit')) {
return maybeThrowOnFail(
params.throwOnFail ?? defaultThrowOnFail,
{
errors: [
{
name: 'GasLimitTooLowForBaseFee',
_tag: 'GasLimitTooLowForBaseFee',
message: e.message
}
],
executionGasUsed: 0n,
rawData: '0x',
...(evmOutput && await callHandlerResult(evmInput, evmOutput, undefined, trace, accessList, vm))
}
)
}
if (e.message.includes('tx has a higher gas limit than the block')) {
return maybeThrowOnFail(
params.throwOnFail ?? defaultThrowOnFail,
{
errors: [
{
name: 'GasLimitExceeded',
_tag: 'GasLimitExceeded',
message: e.message
}
],
executionGasUsed: 0n,
rawData: '0x',
...(evmOutput && await callHandlerResult(evmInput, evmOutput, undefined, trace, accessList, vm))
}
)
}
// When these happen we still want to run the tx
if (
e.message.includes('block has a different hardfork than the vm') ||
e.message.includes('the tx doesn\'t have the correct nonce.') ||
e.message.includes('sender doesn\'t have enough funds to send tx.') ||
e.message.includes('sender doesn\'t have enough funds to send tx. The upfront cost is')
) {
const errors = e.message.includes('block has a different hardfork than the vm') ? [{
name: 'HardForkMismatch',
_tag: 'HardForkMismatch',
message: e.message
}] :
e.message.includes('the tx doesn\'t have the correct nonce.') ? [
{
name: 'InvalidNonce',
_tag: 'InvalidNonce',
message: e.message
}
] : [
{
name: 'InsufficientBalance',
_tag: 'InsufficientBalance',
message: e.message
}
]
try {
// user might have tracing turned on hoping to trace why it's using too much gas
/// calculate skipping all validation but still return errors too
evmOutput = await runTx(vm)({
reportAccessList: params.createAccessList ?? false,
reportPreimages: params.createAccessList ?? false,
skipHardForkValidation: true,
skipBlockGasLimitValidation: true,
// we currently set the nonce ourselves user can't set it
skipNonce: true,
skipBalance: true,
...(evmInput.block !== undefined ? { block: /** @type any*/(evmInput.block) } : {}),
tx: await evmInputToImpersonatedTx({
...client,
getVm: () => Promise.resolve(vm)
})(evmInput)
})
if (trace) {
trace.gas = evmOutput.execResult.executionGasUsed
trace.failed = true
trace.returnValue = bytesToHex(evmOutput.execResult.returnValue)
}
} catch (e) {
const message = e instanceof Error ? e.message : typeof e === 'string' ? e : 'unknown error'
errors.push({ name: 'UnexpectedError', _tag: 'UnexpectedError', message })
}
return maybeThrowOnFail(params.throwOnFail ?? defaultThrowOnFail, {
errors,
executionGasUsed: 0n,
rawData: '0x',
...(evmOutput && await callHandlerResult(evmInput, evmOutput, undefined, trace, accessList, vm))
})
}
throw e
}
client.logger.debug({
returnValue: bytesToHex(evmOutput.execResult.returnValue),
exceptionError: evmOutput.execResult.exceptionError,
executionGasUsed: evmOutput.execResult.executionGasUsed,
}, 'callHandler: runCall result')
if (params.createAccessList && evmOutput.accessList !== undefined) {
accessList = new Map(evmOutput.accessList.map(item => [item.address, new Set(item.storageKeys)]))
}
} catch (e) {
if (typeof e === 'object' && e !== null && '_tag' in e && (params.throwOnFail ?? defaultThrowOnFail)) {
throw e
}
client.logger.error(e, 'callHandler: Unexpected error executing evm')
return maybeThrowOnFail(params.throwOnFail ?? defaultThrowOnFail, {
errors: [
{
name: 'UnexpectedError',
_tag: 'UnexpectedError',
message:
typeof e === 'string'
? e
: e instanceof Error
? e.message
: typeof e === 'object' && e !== null && 'message' in e
? e.message
: 'unknown error',
},
],
executionGasUsed: 0n,
/**
* @type {`0x${string}`}
*/
rawData: '0x',
})
}
if (trace) {
trace.gas = evmOutput.execResult.executionGasUsed
trace.failed = false
trace.returnValue = bytesToHex(evmOutput.execResult.returnValue)
}
/**
* ****************************
* 3 CREATE TRANSACTION WITH CALL (if neessary)
* ****************************
*/
/**
* @type {import('@tevm/utils').Hex | undefined}
*/
let txHash = undefined
const shouldCreateTransaction = (() => {
if (params.createTransaction === undefined) {
client.logger.debug(
'callHandler: Defaulting to false for creating a transaction',
)
return false
}
if (
params.createTransaction === true ||
params.createTransaction === 'always'
) {
client.logger.debug(
"callHandler: Creating transaction because config set to 'always'",
)
return true
}
if (
params.createTransaction === false ||
params.createTransaction === 'never'
) {
client.logger.debug(
"callHandler: Creating transaction because config set to 'never'",
)
return false
}
if (params.createTransaction === 'on-success') {
client.logger.debug(
"callHandler: Creating transaction because config set to 'on-success'",
)
return evmOutput.execResult.exceptionError === undefined
}
/**
* @type {never} this typechecks that we've exhausted all cases
*/
const invalidOption = params.createTransaction
throw new Error(`Invalid createTransaction value: ${invalidOption}`)
})()
if (shouldCreateTransaction) {
client.logger.debug('creating a transaction in the mempool...')
// quickly do a sanity check that eth exists at origin
const accountAddress = evmInput.origin ?? EthjsAddress.zero()
const account = await vm.stateManager.getAccount(accountAddress).catch(() => new EthjsAccount())
const hasEth = evmInput.skipBalance || ((account)?.balance ?? 0n) > 0n
if (!hasEth) {
return maybeThrowOnFail(
params.throwOnFail ?? defaultThrowOnFail,
{
errors: [{ _tag: 'InsufficientBalance', name: 'InsufficientBalance', message: `Insufficientbalance: Account ${accountAddress} attempted to create a transaction with zero eth. Consider adding eth to account or using a different from or origin address` }],
...(await callHandlerResult(evmInput, evmOutput, undefined, trace, accessList, vm)),
}
)
}
const txRes = await createTransaction(client)({ throwOnFail: false, evmOutput, evmInput })
txHash = 'txHash' in txRes ? txRes.txHash : undefined
if ('errors' in txRes && txRes.errors.length) {
return /** @type {any}*/ (
maybeThrowOnFail(
params.throwOnFail ?? defaultThrowOnFail,
{
...('errors' in txRes ? { errors: txRes.errors } : {}),
...(await callHandlerResult(evmInput, evmOutput, undefined, trace, accessList, vm)),
}
)
)
}
client.logger.debug(txHash, 'Transaction successfully added')
// handle automining
if (client.miningConfig.type === 'auto') {
client.logger.debug(`Automining transaction ${txHash}...`)
const mineRes = await mineHandler(client)({ throwOnFail: false })
if (mineRes.errors?.length) {
return maybeThrowOnFail(params.throwOnFail ?? defaultThrowOnFail, {
...('errors' in mineRes ? { errors: mineRes.errors } : {}),
...(await callHandlerResult(evmInput, evmOutput, txHash, trace, accessList, vm)),
})
}
client.logger.debug(mineRes, 'Transaction successfully mined')
}
}
/**
* ******************
* 4 RETURN CALL RESULT
* ******************
*/
return maybeThrowOnFail(params.throwOnFail ?? defaultThrowOnFail, {
...(await callHandlerResult(evmInput, evmOutput, txHash, trace, accessList, vm)),
})
}