Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

⚡ Feat: Optimize executeCall #1497

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

roninjin10
Copy link
Collaborator

@roninjin10 roninjin10 commented Nov 15, 2024

Description

Concise description of proposed changes

Testing

Explain the quality checks that have been done on the code changes

Additional Information

Your ENS/address:

Summary by CodeRabbit

  • New Features

    • Enhanced access list management in the execute call function, improving transaction efficiency.
    • Improved error handling with detailed logging for access list requests.
  • Bug Fixes

    • Ensured consistent return values for access lists and traces, even in error scenarios.

Copy link

vercel bot commented Nov 15, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

1 Skipped Deployment
Name Status Preview Updated (UTC)
tevm-monorepo-tevm ⬜️ Ignored (Inspect) Nov 15, 2024 6:30am

Copy link

changeset-bot bot commented Nov 15, 2024

⚠️ No Changeset found

Latest commit: b49dbeb

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@roninjin10 roninjin10 marked this pull request as ready for review November 15, 2024 06:30
Copy link
Contributor

coderabbitai bot commented Nov 15, 2024

Walkthrough

The changes to the executeCall function in packages/actions/src/Call/executeCall.js introduce new imports and expand the function's internal logic to include asynchronous handling of access lists. The function now attempts to fetch an access list using the eth_createAccessList method and processes the response to manage storage keys. Enhanced error handling is implemented, ensuring that access list information is consistently returned, whether the operation is successful or not. The method signature remains unchanged, but the functionality is significantly improved.

Changes

File Path Change Summary
packages/actions/src/Call/executeCall.js - Added imports: hexToBytes, numberToHex, createAddress.
- Expanded internal logic to fetch and manage access lists using eth_createAccessList.
- Enhanced error handling with logging for access list requests.
- Updated return structure to include access list, runTxResult, and trace.

Poem

In the burrow where calls take flight,
Access lists dance in the moonlight. 🌙
With each new fetch, our treasures grow,
Errors logged, we’re ready to flow!
A hop, a skip, through code we weave,
In this patch, new magic we believe! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Collaborator Author

roninjin10 commented Nov 15, 2024

This stack of pull requests is managed by Graphite. Learn more about stacking.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Outside diff range and nitpick comments (1)
packages/actions/src/Call/executeCall.js (1)

46-46: TODO indicates incomplete implementation needing attention

The comment on line 46 suggests that the current approach is a temporary workaround and that forkTransport.send should be used when it's available.

Would you like me to open a GitHub issue to track the implementation of forkTransport.send? This will ensure that the code is updated accordingly once the method becomes available.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 236ed18 and b49dbeb.

📒 Files selected for processing (1)
  • packages/actions/src/Call/executeCall.js (2 hunks)

Comment on lines +82 to +84
if (getStorage()?.length) {
return
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Premature function exit inside asynchronous operation may skip storage updates

The return statement within the storage retrieval promise may cause the asynchronous function to exit early, potentially skipping the processing of remaining storage keys. This can lead to incomplete storage caching and inconsistent state.

Consider revising the control flow to ensure all storage keys are processed. If the intention is to skip the rest of the current promise execution, ensure that other promises continue executing as expected.

}
for (const contract of accessListRes.result?.accessList ?? []) {
for (const storageKey of contract.storageKeys) {
const getStorage = () => vm.stateManager._baseState.caches.storage.get(createAddress(contract.address), hexToBytes(storageKey, { size: 32 }))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Accessing internal properties may lead to maintenance issues

The code accesses internal properties _baseState and caches of vm.stateManager, which are intended for internal use and may change in future versions of the library. Relying on internal implementation details can introduce maintenance challenges and compatibility issues.

Consider using the public API methods provided by vm.stateManager to interact with the storage. For example, use vm.stateManager.getContractStorage and vm.stateManager.putContractStorage for accessing and modifying contract storage.

Comment on lines +63 to +65
if (accessListRes.error) {
client.logger.error('Unable to get an access list', accessListRes.error)
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Error handling may be insufficient when access list retrieval fails

Currently, if accessListRes.error exists, the code logs an error but continues execution. If the subsequent code relies on the access list being available, this might lead to unintended behavior or runtime errors.

Consider adding error handling to manage this scenario appropriately, such as:

  • Returning early with an error response.
  • Providing a fallback mechanism if the access list is critical for execution.
  • Ensuring that subsequent code checks for the existence of accessListRes.result before proceeding.

Comment on lines +69 to +71
if (getStorage()?.length) {
return
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Improper use of return inside a loop may cause premature function exit

Using return inside the inner for loop will exit the entire asynchronous function, not just skip to the next iteration. If the goal is to skip to the next iteration when getStorage()?.length is truthy, continue should be used instead of return.

Apply this diff to correct the control flow:

-                    if (getStorage()?.length) {
-                        return
-                    }
+                    if (getStorage()?.length) {
+                        continue
+                    }

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +41 to +94
; (async () => {
if (!client.forkTransport) return
const blockTag = await client.getVm()
.then(vm => vm.blockchain.blocksByTag.get('forked'))
.then(block => block !== undefined ? numberToHex(block.header.number) : 'latest')
// TODO this is wrong we should use forkTransport.send but it doesn't exist yet
/**
* @type {import('../eth/EthJsonRpcResponse.js').EthCreateAccessListJsonRpcResponse}
*/
const accessListRes = await client.forkTransport?.request({
method: 'eth_createAccessList',
params: [
{
to: evmInput.to,
gas: evmInput.gasLimit,
// gasPrice: evmInput.gasPrice, not necessary to set this
value: evmInput.value,
data: evmInput.data,
},
blockTag,
],
})
if (accessListRes.error) {
client.logger.error('Unable to get an access list', accessListRes.error)
}
for (const contract of accessListRes.result?.accessList ?? []) {
for (const storageKey of contract.storageKeys) {
const getStorage = () => vm.stateManager._baseState.caches.storage.get(createAddress(contract.address), hexToBytes(storageKey, { size: 32 }))
if (getStorage()?.length) {
return
}
/**
* @type {import('../eth/EthJsonRpcResponse.js').EthCreateAccessListJsonRpcResponse}
*/
client.forkTransport.request({
method: 'eth_getStorageAt',
params: [contract.address, storageKey, blockTag]
}).then(async storage => {
const vm = await client.getVm()
// THIS MUST BE SYNC TO INITIALLY SET STORAGE OR RACE CONDITIONS WILL EXIST!!!
// This can be cleaned up with a state lock later
if (getStorage()?.length) {
return
}
vm.stateManager._baseState.caches.storage
.put(
createAddress(contract.address),
hexToBytes(storageKey, { size: 32 }),
hexToBytes(/** @type {import('viem').Hex}*/(storage))
)
})
}
}
})()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Potential race conditions due to unawaited asynchronous function

The asynchronous function starting at line 41 is invoked without awaiting its completion. Since it's not awaited, the main execution flow continues without ensuring that the storage fetching and caching operations have completed. This can lead to race conditions where the required storage data may not be available when needed.

Consider awaiting the asynchronous function to ensure proper execution order:

-        ; (async () => {
+        await (async () => {

Alternatively, if the intention is to perform these operations in parallel, ensure that the rest of the code does not depend on the outcome of this asynchronous function.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
; (async () => {
if (!client.forkTransport) return
const blockTag = await client.getVm()
.then(vm => vm.blockchain.blocksByTag.get('forked'))
.then(block => block !== undefined ? numberToHex(block.header.number) : 'latest')
// TODO this is wrong we should use forkTransport.send but it doesn't exist yet
/**
* @type {import('../eth/EthJsonRpcResponse.js').EthCreateAccessListJsonRpcResponse}
*/
const accessListRes = await client.forkTransport?.request({
method: 'eth_createAccessList',
params: [
{
to: evmInput.to,
gas: evmInput.gasLimit,
// gasPrice: evmInput.gasPrice, not necessary to set this
value: evmInput.value,
data: evmInput.data,
},
blockTag,
],
})
if (accessListRes.error) {
client.logger.error('Unable to get an access list', accessListRes.error)
}
for (const contract of accessListRes.result?.accessList ?? []) {
for (const storageKey of contract.storageKeys) {
const getStorage = () => vm.stateManager._baseState.caches.storage.get(createAddress(contract.address), hexToBytes(storageKey, { size: 32 }))
if (getStorage()?.length) {
return
}
/**
* @type {import('../eth/EthJsonRpcResponse.js').EthCreateAccessListJsonRpcResponse}
*/
client.forkTransport.request({
method: 'eth_getStorageAt',
params: [contract.address, storageKey, blockTag]
}).then(async storage => {
const vm = await client.getVm()
// THIS MUST BE SYNC TO INITIALLY SET STORAGE OR RACE CONDITIONS WILL EXIST!!!
// This can be cleaned up with a state lock later
if (getStorage()?.length) {
return
}
vm.stateManager._baseState.caches.storage
.put(
createAddress(contract.address),
hexToBytes(storageKey, { size: 32 }),
hexToBytes(/** @type {import('viem').Hex}*/(storage))
)
})
}
}
})()
await (async () => {
if (!client.forkTransport) return
const blockTag = await client.getVm()
.then(vm => vm.blockchain.blocksByTag.get('forked'))
.then(block => block !== undefined ? numberToHex(block.header.number) : 'latest')
// TODO this is wrong we should use forkTransport.send but it doesn't exist yet
/**
* @type {import('../eth/EthJsonRpcResponse.js').EthCreateAccessListJsonRpcResponse}
*/
const accessListRes = await client.forkTransport?.request({
method: 'eth_createAccessList',
params: [
{
to: evmInput.to,
gas: evmInput.gasLimit,
// gasPrice: evmInput.gasPrice, not necessary to set this
value: evmInput.value,
data: evmInput.data,
},
blockTag,
],
})
if (accessListRes.error) {
client.logger.error('Unable to get an access list', accessListRes.error)
}
for (const contract of accessListRes.result?.accessList ?? []) {
for (const storageKey of contract.storageKeys) {
const getStorage = () => vm.stateManager._baseState.caches.storage.get(createAddress(contract.address), hexToBytes(storageKey, { size: 32 }))
if (getStorage()?.length) {
return
}
/**
* @type {import('../eth/EthJsonRpcResponse.js').EthCreateAccessListJsonRpcResponse}
*/
client.forkTransport.request({
method: 'eth_getStorageAt',
params: [contract.address, storageKey, blockTag]
}).then(async storage => {
const vm = await client.getVm()
// THIS MUST BE SYNC TO INITIALLY SET STORAGE OR RACE CONDITIONS WILL EXIST!!!
// This can be cleaned up with a state lock later
if (getStorage()?.length) {
return
}
vm.stateManager._baseState.caches.storage
.put(
createAddress(contract.address),
hexToBytes(storageKey, { size: 32 }),
hexToBytes(/** @type {import('viem').Hex}*/(storage))
)
})
}
}
})()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant