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

Estimate cost tut #913

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open

Estimate cost tut #913

wants to merge 9 commits into from

Conversation

krofax
Copy link
Contributor

@krofax krofax commented Sep 20, 2024

Description

This tutorial explains how estimate transaction costs on OP Sepolia using Viem

Tests

Please describe any tests you've added. If you've added no tests, or left important behavior untested, please explain why not.

Additional context

Add any other context about the problem you're solving.

Metadata

@krofax krofax requested a review from a team as a code owner September 20, 2024 18:04
Copy link
Contributor

coderabbitai bot commented Sep 20, 2024

Walkthrough

The changes involve significant updates to the tutorial on estimating transaction costs, transitioning from the Optimism SDK to the Viem library. The document now includes prerequisites such as Node.js and pnpm, and reorganizes tutorial steps for clarity. Additionally, the configuration of environment variables is emphasized, and the process for estimating transaction costs has been restructured. The words.txt file has been modified to remove the entry "Fastnode," resulting in a reduced list of terms.

Changes

File(s) Change Summary
pages/builders/app-developers/tutorials/... Updated to reflect the transition from the Optimism SDK to the Viem library, including changes to prerequisites, tutorial steps, and transaction cost estimation methods.
public/tutorials/sdk-estimate-costs.js Refactored to utilize the Viem library for Ethereum interactions, including new transaction cost estimation logic and improved error handling.
words.txt Removed the entry "Fastnode" from the list of terms, reducing the total number of terms.

Possibly related issues

  • ethereum-optimism/docs#595: This PR addresses the objective of updating SDK tutorials to use the Viem library, as the Optimism SDK is in maintenance mode.

Possibly related PRs

  • Create Granite notice page skeleton #870: The changes in this PR involve transitioning to the Viem library for transaction cost estimation, which may relate to the broader context of updates and preparations for the OP Stack.

Suggested reviewers

  • sbvegan: Suggested reviewer due to involvement in related issues regarding the transition to the Viem library.

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.

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

netlify bot commented Sep 20, 2024

Deploy Preview for docs-optimism ready!

Name Link
🔨 Latest commit 8427f62
🔍 Latest deploy log https://app.netlify.com/sites/docs-optimism/deploys/66fdce033a4930000838b406
😎 Deploy Preview https://deploy-preview-913--docs-optimism.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

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: 0

Outside diff range and nitpick comments (2)
pages/builders/app-developers/tutorials/sdk-estimate-costs.mdx (2)

40-88: LGTM!

The "Create a Demo Project" section provides clear and concise step-by-step instructions for setting up a demo project, including creating a folder, initializing the project, installing dependencies, and configuring environment variables. The emphasis on securely storing the private key in the .env file is important for security best practices.

Consider rephrasing the following sentences to avoid wordiness:

  • Line 72: "You need a private key to sign transactions."
  • Line 82: "You need a private key to sign transactions."
Tools
LanguageTool

[style] ~72-~72: Consider a shorter alternative to avoid wordiness.
Context: ...riables} You need a private key in order to sign transactions. Create a .env fi...

(IN_ORDER_TO_PREMIUM)


[style] ~82-~82: Consider a shorter alternative to avoid wordiness.
Context: ...e .env file. You need a private key in order to sign transactions. Make sure this pri...

(IN_ORDER_TO_PREMIUM)


Line range hint 113-133: LGTM!

The "Import Dependencies" section provides clear instructions for importing the necessary dependencies into the Node REPL session, including modules from the Viem library and the dotenv module for managing environment variables. The code snippet for importing dependencies is properly formatted and includes comments for clarity.

Consider rephrasing the following sentence to fix the grammatical error:

  • Line 180: "Viem makes it easy to prepare a transaction so you can estimate the cost of a transaction before you sign it."
Tools
LanguageTool

[grammar] ~180-~180: The plural noun “transactions” cannot be used with the article “a”. Did you mean “a transaction” or “transactions”?
Context: ...} Viem makes it easy to prepare a transactions so you can estimate the cost of a trans...

(A_NNS)

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 946f883 and cefac45.

Files selected for processing (2)
  • pages/builders/app-developers/tutorials/sdk-estimate-costs.mdx (3 hunks)
  • words.txt (0 hunks)
Files not reviewed due to no reviewable changes (1)
  • words.txt
Additional context used
Path-based instructions (1)
pages/builders/app-developers/tutorials/sdk-estimate-costs.mdx (1)

Pattern **/*.mdx: "ALWAYS review Markdown content THOROUGHLY with the following criteria:

  • Use proper nouns in place of personal pronouns like 'We' and 'Our' to maintain consistency in communal documentation.
  • Avoid gender-specific language and use the imperative form.
  • Monitor capitalization for emphasis. Use bold for prominence instead of all caps or italics.
  • Ensure proper nouns are capitalized in sentences.
  • Apply the Oxford comma.
  • Use proper title case for headers, buttons, tab names, page names, and links. Sentence case should be used for body content and short phrases, even in links.
  • Use correct spelling and grammar at all times (IMPORTANT).
    "
LanguageTool
pages/builders/app-developers/tutorials/sdk-estimate-costs.mdx

[style] ~72-~72: Consider a shorter alternative to avoid wordiness.
Context: ...riables} You need a private key in order to sign transactions. Create a .env fi...

(IN_ORDER_TO_PREMIUM)


[style] ~82-~82: Consider a shorter alternative to avoid wordiness.
Context: ...e .env file. You need a private key in order to sign transactions. Make sure this pri...

(IN_ORDER_TO_PREMIUM)


[grammar] ~180-~180: The plural noun “transactions” cannot be used with the article “a”. Did you mean “a transaction” or “transactions”?
Context: ...} Viem makes it easy to prepare a transactions so you can estimate the cost of a trans...

(A_NNS)

Additional comments not posted (5)
pages/builders/app-developers/tutorials/sdk-estimate-costs.mdx (5)

2-4: LGTM!

The updated title and description accurately reflect the focus of the tutorial on estimating transaction costs using the Viem library on OP Stack and OP Mainnet.


19-25: LGTM!

The updated prerequisites section provides a clear and concise list of requirements for following the tutorial, including Node.js, an understanding of the Viem library, and the installation of pnpm.


Line range hint 105-111: LGTM!

The "Start the Node REPL" section provides clear instructions for starting the Node REPL to interact with the Viem library, including the command to start the Node REPL.

Tools
LanguageTool

[style] ~98-~98: Consider a shorter alternative to avoid wordiness.
Context: ...will need to get some ETH on OP Sepolia in order to run the code in this tutorial. <Callou...

(IN_ORDER_TO_PREMIUM)


[uncategorized] ~107-~107: Possible missing comma found.
Context: ...ith the Viem library. To start the Node REPL run the following command in your termi...

(AI_HYDRA_LEO_MISSING_COMMA)


137-171: LGTM!

The "Set Session Variables" section provides clear and well-organized instructions for setting up the necessary variables for the tutorial, including creating a wallet instance using the private key, setting up wallet clients for L2, and setting up Viem clients for L1 and L2. The use of the tabbed format enhances the readability and organization of the instructions.


173-307: LGTM!

The "Estimate Transaction Costs" section provides clear, detailed, and well-organized step-by-step instructions for estimating transaction costs on OP Mainnet. The code snippets for each step are properly formatted and include comments for clarity. The explanations of concepts such as execution gas fee, L1 data fee, and total cost estimation are helpful for users to understand the process. The inclusion of steps for sending the transaction and comparing estimated and actual costs provides a comprehensive overview of the estimation process. The callout about the accuracy of estimates and the next steps for transaction management offers valuable insights for users.

Tools
LanguageTool

[grammar] ~180-~180: The plural noun “transactions” cannot be used with the article “a”. Did you mean “a transaction” or “transactions”?
Context: ...} Viem makes it easy to prepare a transactions so you can estimate the cost of a trans...

(A_NNS)

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: 6

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between cefac45 and 354d2a7.

Files selected for processing (1)
  • public/tutorials/sdk-estimate-costs.js (1 hunks)
Additional comments not posted (1)
public/tutorials/sdk-estimate-costs.js (1)

30-30: Verify the hardcoded recipient address

The to address '0x1000000000000000000000000000000000000000' is hardcoded in the transaction. Ensure that this is the intended recipient address for the OP Sepolia network and that sending value to this address is appropriate for the tutorial.

public/tutorials/sdk-estimate-costs.js Show resolved Hide resolved
public/tutorials/sdk-estimate-costs.js Show resolved Hide resolved
public/tutorials/sdk-estimate-costs.js Outdated Show resolved Hide resolved
public/tutorials/sdk-estimate-costs.js Outdated Show resolved Hide resolved
public/tutorials/sdk-estimate-costs.js Outdated Show resolved Hide resolved
public/tutorials/sdk-estimate-costs.js Show resolved Hide resolved
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: 0

Outside diff range and nitpick comments (8)
pages/builders/app-developers/tutorials/sdk-estimate-costs.mdx (8)

2-18: LGTM! Clear and informative introduction.

The updated title, description, and introduction effectively communicate the tutorial's focus on using the Viem library for estimating transaction costs on OP Stack. The Callout component provides a valuable link to more detailed information.

Consider rephrasing line 11 for clarity:

-In this tutorial, you'll learn how to use the [Viem](https://viem.sh/op-stack/) to estimate the cost of a transaction on OP Mainnet.
+In this tutorial, you'll learn how to use [Viem](https://viem.sh/op-stack/) to estimate the cost of a transaction on OP Mainnet.

19-25: LGTM! Clear prerequisites section.

The new Prerequisites section effectively outlines the necessary tools and knowledge for following the tutorial. The inclusion of version information for Node.js is particularly helpful.

For consistency in formatting, consider using sentence case for all list items:

-*   Node.js (version 14 or later)
-*   An understanding of the [viem library](https://viem.sh/op-stack/)
-*   `pnpm` installed for managing packages.
+* Node.js (version 14 or later)
+* An understanding of the [Viem library](https://viem.sh/op-stack/)
+* `pnpm` installed for managing packages

27-38: LGTM! Clear dependencies section with installation instructions.

The Required Dependencies section effectively lists the necessary tools and provides helpful installation instructions for pnpm.

For consistency in formatting and to align with the previous section, consider the following changes:

-*   [node](https://nodejs.org/en/)
-*   [pnpm](https://pnpm.io/installation)
-*   [viem](https://viem.sh/op-stack/)
+* [Node.js](https://nodejs.org/en/)
+* [pnpm](https://pnpm.io/installation)
+* [Viem](https://viem.sh/op-stack/)

Line range hint 40-103: LGTM! Clear and comprehensive project setup instructions.

The Create a Demo Project section provides well-structured, step-by-step instructions using the Steps component. The inclusion of environment variable configuration and the security warning about private keys are particularly valuable.

Consider the following minor improvements for clarity and consistency:

  1. In the "Install dependencies" step, consider clarifying the purpose of dotenv:
-Install `viem`, and `dotenv` for managing environment variables.
+Install `viem` for interacting with Ethereum networks and `dotenv` for managing environment variables.
  1. In the environment variable configuration, consider adding a brief explanation of what the RPC_URL is for:
+RPC_URL=https://optimism-sepolia.infura.io/v3/YOUR_INFURA_PROJECT_ID  # RPC endpoint for OP Sepolia
TUTORIAL_PRIVATE_KEY=0x...
  1. For consistency, consider using sentence case for all headers within the Steps component.
Tools
LanguageTool

[style] ~73-~73: Consider a shorter alternative to avoid wordiness.
Context: ...riables} You need a private key in order to sign transactions. Create a .env fi...

(IN_ORDER_TO_PREMIUM)


[style] ~83-~83: Consider a shorter alternative to avoid wordiness.
Context: ...e .env file. You need a private key in order to sign transactions. Make sure this pri...

(IN_ORDER_TO_PREMIUM)


Line range hint 117-135: LGTM! Comprehensive import instructions.

The Import Dependencies section provides clear instructions and a comprehensive code snippet for importing the necessary packages. The use of ES6 import syntax is modern and appropriate for the tutorial.

Consider adding a brief explanation of each imported module or group of functions to help users understand their purpose. For example:

// Import required modules
import { createPublicClient, createWalletClient, http, parseEther, parseGwei, formatEther } from 'viem' // Core Viem functions
import { privateKeyToAccount } from 'viem/accounts' // Account management
import { optimismSepolia } from 'viem/chains' // OP Sepolia chain configuration
import { publicActionsL2, walletActionsL2 } from 'viem/op-stack' // OP Stack specific actions
import * as dotenv from 'dotenv' // Environment variable management
Tools
LanguageTool

[grammar] ~182-~182: The plural noun “transactions” cannot be used with the article “a”. Did you mean “a transaction” or “transactions”?
Context: ...} Viem makes it easy to prepare a transactions so you can estimate the cost of a trans...

(A_NNS)


137-173: LGTM! Well-organized session variable setup.

The Set Session Variables section effectively uses the Tabs component to organize different aspects of setting up session variables. The instructions for creating wallet instances and RPC providers are clear, and the code snippets are well-commented.

Consider the following minor improvements for clarity and consistency:

  1. In the "Create the wallet instance" tab, update the variable name to match the code:
-To create the wallet instance, load your private key, using `privateKeyToAccount`. [`privateKeyToAccount`](https://viem.sh/docs/accounts/local/privateKeyToAccount#privatekeytoaccount) is a viem method used to sign transactions by passing a private key.
+To create the account instance, load your private key using `privateKeyToAccount`. [`privateKeyToAccount`](https://viem.sh/docs/accounts/local/privateKeyToAccount#privatekeytoaccount) is a Viem method used to create an account from a private key for signing transactions.
  1. In the "Wallet clients" tab, consider adding a brief explanation of what the wallet client is used for:
-Set up our Wallet Clients for L2(optimismSepolia)
+Set up our Wallet Client for L2 (OP Sepolia) to send transactions and interact with smart contracts:
  1. In the "Create the RPC provider" tab, update the comment to match the actual code:
-Set up our Viem Clients for the L1(Sepolia) and L2(optimismSepolia)
+Set up our Public Client for L2 (OP Sepolia) to interact with the network:

175-296: LGTM! Comprehensive guide to estimating transaction costs.

The Estimate Transaction Costs section provides a detailed, step-by-step guide using the Steps component. The instructions are clear, and the code snippets are well-commented and easy to follow. This section effectively demonstrates how to use Viem to estimate and verify transaction costs on OP Stack.

Consider the following minor improvements for clarity and consistency:

  1. In the "Creating a Transaction in Viem" step, consider adding a brief explanation of the parseEther and parseGwei functions:
const transaction = {
  account,
  to: '0x1000000000000000000000000000000000000000',
-  value: parseEther('0.1'),  
-  gasPrice: parseGwei('20')
+  value: parseEther('0.1'),  // Convert 0.1 ETH to wei
+  gasPrice: parseGwei('20')  // Set gas price to 20 Gwei
};
  1. In the "Estimate the L1 data fee" step, consider clarifying the unit of the returned value:
-This function returns the current cost estimate in wei.
+This function returns the current cost estimate in wei (the smallest unit of ETH).
  1. In the "Check the difference" step, consider adding a brief explanation of what a positive or negative difference means:
  const difference =  totalSum - totalActual
-  console.log(`The difference - ${formatEther(difference)}`) 
+  console.log(`The difference: ${formatEther(difference)} ETH`) // Positive means overestimation, negative means underestimation
Tools
LanguageTool

[grammar] ~182-~182: The plural noun “transactions” cannot be used with the article “a”. Did you mean “a transaction” or “transactions”?
Context: ...} Viem makes it easy to prepare a transactions so you can estimate the cost of a trans...

(A_NNS)


302-309: LGTM! Valuable next steps and best practices.

The Next Steps section provides a comprehensive list of best practices and considerations for transaction cost estimation. The information is relevant and valuable, covering important topics such as gas price volatility, transaction data optimization, and retry mechanisms.

For consistency with the rest of the document, consider using sentence case for all bullet points:

-*   Always estimate before sending: Estimating costs before sending a transaction helps prevent unexpected fees and failed transactions.
-*   Account for gas price volatility: Gas prices can change rapidly. Consider adding a buffer to your estimates or implementing a gas price oracle for more accurate pricing.
-*   Optimize transaction data: Minimize the amount of data in your transactions to reduce L1 data fees.
-*   Monitor network conditions: Keep an eye on network congestion and adjust your estimates accordingly.
-*   Use appropriate gas limits: Setting too low a gas limit can cause transactions to fail, while setting it too high can result in unnecessary costs.
-*   Implement retry mechanisms: If a transaction fails due to underestimated gas, implement a retry mechanism with adjusted gas parameters.
+* Always estimate before sending: Estimating costs before sending a transaction helps prevent unexpected fees and failed transactions
+* Account for gas price volatility: Gas prices can change rapidly. Consider adding a buffer to your estimates or implementing a gas price oracle for more accurate pricing
+* Optimize transaction data: Minimize the amount of data in your transactions to reduce L1 data fees
+* Monitor network conditions: Keep an eye on network congestion and adjust your estimates accordingly
+* Use appropriate gas limits: Setting too low a gas limit can cause transactions to fail, while setting it too high can result in unnecessary costs
+* Implement retry mechanisms: If a transaction fails due to underestimated gas, implement a retry mechanism with adjusted gas parameters
Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 354d2a7 and 9ec6760.

Files selected for processing (1)
  • pages/builders/app-developers/tutorials/sdk-estimate-costs.mdx (3 hunks)
Additional context used
Path-based instructions (1)
pages/builders/app-developers/tutorials/sdk-estimate-costs.mdx (1)

Pattern **/*.mdx: "ALWAYS review Markdown content THOROUGHLY with the following criteria:

  • Use proper nouns in place of personal pronouns like 'We' and 'Our' to maintain consistency in communal documentation.
  • Avoid gender-specific language and use the imperative form.
  • Monitor capitalization for emphasis. Use bold for prominence instead of all caps or italics.
  • Ensure proper nouns are capitalized in sentences.
  • Apply the Oxford comma.
  • Use proper title case for headers, buttons, tab names, page names, and links. Sentence case should be used for body content and short phrases, even in links.
  • Use correct spelling and grammar at all times (IMPORTANT).
    "
LanguageTool
pages/builders/app-developers/tutorials/sdk-estimate-costs.mdx

[style] ~73-~73: Consider a shorter alternative to avoid wordiness.
Context: ...riables} You need a private key in order to sign transactions. Create a .env fi...

(IN_ORDER_TO_PREMIUM)


[style] ~83-~83: Consider a shorter alternative to avoid wordiness.
Context: ...e .env file. You need a private key in order to sign transactions. Make sure this pri...

(IN_ORDER_TO_PREMIUM)


[grammar] ~182-~182: The plural noun “transactions” cannot be used with the article “a”. Did you mean “a transaction” or “transactions”?
Context: ...} Viem makes it easy to prepare a transactions so you can estimate the cost of a trans...

(A_NNS)

Additional comments not posted (1)
pages/builders/app-developers/tutorials/sdk-estimate-costs.mdx (1)

Line range hint 107-115: LGTM! Clear instructions for starting the Node REPL.

The Start the Node REPL section provides clear and concise instructions for initiating the Node REPL. The explanation of its purpose in the context of the tutorial is helpful, especially for beginners.

Tools
LanguageTool

[style] ~99-~99: Consider a shorter alternative to avoid wordiness.
Context: ...will need to get some ETH on OP Sepolia in order to run the code in this tutorial. <Callou...

(IN_ORDER_TO_PREMIUM)

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: 0

Outside diff range and nitpick comments (8)
pages/builders/app-developers/tutorials/sdk-estimate-costs.mdx (8)

2-18: LGTM! Clear and informative introduction.

The title, description, and introduction accurately reflect the tutorial's content and purpose. The use of the Callout component effectively emphasizes important information.

Consider rephrasing line 11 for clarity:

-In this tutorial, you'll learn how to use the [Viem](https://viem.sh/op-stack/) to estimate the cost of a transaction on OP Mainnet.
+In this tutorial, you'll learn how to use the [Viem library](https://viem.sh/op-stack/) to estimate the cost of a transaction on OP Mainnet.

19-25: LGTM! Clear prerequisites section.

The prerequisites are well-defined and relevant to the tutorial. The inclusion of version information for Node.js is particularly helpful.

Consider adding a link to the Viem library documentation for easy reference:

-*   An understanding of the [viem library](https://viem.sh/op-stack/)
+*   An understanding of the [Viem library](https://viem.sh/docs/getting-started.html)

27-38: LGTM! Clear dependency list and installation instructions.

The required dependencies are clearly listed, and the installation instructions for pnpm are helpful.

Consider adding installation instructions for the Viem library:

npm install -g pnpm

+# Install Viem library
+pnpm add viem

40-93: LGTM! Well-structured project setup instructions.

The project setup instructions are clear, concise, and easy to follow. The use of the Steps component improves readability, and the environment variable setup is well-explained, including an important security warning.

For consistency, consider using the same naming convention for the environment variables:

-RPC_URL=https://optimism-mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID
-TUTORIAL_PRIVATE_KEY=0x...
+L2_RPC_URL=https://optimism-mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID
+PRIVATE_KEY=0x...

This change aligns with the variable names used later in the tutorial (e.g., L2_RPC_URL and PRIVATE_KEY).

Tools
LanguageTool

[style] ~73-~73: Consider a shorter alternative to avoid wordiness.
Context: ...riables} You need a private key in order to sign transactions. Create a .env fi...

(IN_ORDER_TO_PREMIUM)


[style] ~83-~83: Consider a shorter alternative to avoid wordiness.
Context: ...e .env file. You need a private key in order to sign transactions. Make sure this pri...

(IN_ORDER_TO_PREMIUM)


Line range hint 105-135: LGTM! Clear instructions for REPL setup and dependency imports.

The instructions for starting the Node REPL are clear, and the import statements are comprehensive, including all necessary modules. The use of environment variables is handled correctly.

For clarity, consider adding a brief comment explaining the purpose of each imported module or group of modules. For example:

// Viem core utilities
import { createPublicClient, createWalletClient, http, parseEther, parseGwei, formatEther } from 'viem'

// Account management
import { privateKeyToAccount } from 'viem/accounts'

// Chain-specific imports
import { optimismSepolia } from 'viem/chains'
import { publicActionsL2, walletActionsL2 } from 'viem/op-stack'

// Environment variable management
import * as dotenv from 'dotenv';
Tools
LanguageTool

[grammar] ~190-~190: The plural noun “transactions” cannot be used with the article “a”. Did you mean “a transaction” or “transactions”?
Context: ...} Viem makes it easy to prepare a transactions so you can estimate the cost of a trans...

(A_NNS)


137-181: LGTM! Well-organized session variable setup.

The use of Tabs effectively organizes different aspects of setting up session variables. The code snippets are clear, well-commented, and include good error handling for missing environment variables.

For consistency and clarity, consider adding error handling for the L2_RPC_URL environment variable, similar to what's done for PRIVATE_KEY:

if (!process.env.L2_RPC_URL) {
  throw new Error('Error: L2_RPC_URL is not defined in the environment variables.')
}

const walletClient = createWalletClient({
  chain: optimismSepolia,
  transport: http(process.env.L2_RPC_URL),
}).extend(walletActionsL2())

183-303: LGTM! Comprehensive guide to estimating transaction costs.

The section effectively guides users through the process of estimating transaction costs, with clear steps and well-explained code snippets. The breakdown of each step helps users understand the entire process.

For improved clarity, consider adding a brief explanation of the parseEther and parseGwei functions when they're first used. For example:

const transaction = {
  account,
  to: '0x1000000000000000000000000000000000000000',
  value: parseEther('0.005'),  // Converts 0.005 ETH to wei
  gasPrice: parseGwei('20')    // Converts 20 Gwei to wei
};

This addition helps users understand the purpose of these functions and the units being used.

Tools
LanguageTool

[grammar] ~190-~190: The plural noun “transactions” cannot be used with the article “a”. Did you mean “a transaction” or “transactions”?
Context: ...} Viem makes it easy to prepare a transactions so you can estimate the cost of a trans...

(A_NNS)


310-317: LGTM! Valuable next steps and best practices.

This section provides excellent guidance on applying the knowledge gained from the tutorial in real-world scenarios. The points covered are relevant and offer valuable insights into transaction cost management.

Consider adding a point about staying updated with the latest developments in the Optimism ecosystem:

*   Implement retry mechanisms: If a transaction fails due to underestimated gas, implement a retry mechanism with adjusted gas parameters.
+*   Stay informed: Keep up-to-date with the latest developments in the Optimism ecosystem, as changes to the protocol may affect transaction costs and estimation methods.

This addition encourages users to maintain awareness of potential changes that could impact their applications.

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 9ec6760 and 70bf529.

Files selected for processing (2)
  • pages/builders/app-developers/tutorials/sdk-estimate-costs.mdx (3 hunks)
  • public/tutorials/sdk-estimate-costs.js (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • public/tutorials/sdk-estimate-costs.js
Additional context used
Path-based instructions (1)
pages/builders/app-developers/tutorials/sdk-estimate-costs.mdx (1)

Pattern **/*.mdx: "ALWAYS review Markdown content THOROUGHLY with the following criteria:

  • Use proper nouns in place of personal pronouns like 'We' and 'Our' to maintain consistency in communal documentation.
  • Avoid gender-specific language and use the imperative form.
  • Monitor capitalization for emphasis. Use bold for prominence instead of all caps or italics.
  • Ensure proper nouns are capitalized in sentences.
  • Apply the Oxford comma.
  • Use proper title case for headers, buttons, tab names, page names, and links. Sentence case should be used for body content and short phrases, even in links.
  • Use correct spelling and grammar at all times (IMPORTANT).
    "
LanguageTool
pages/builders/app-developers/tutorials/sdk-estimate-costs.mdx

[style] ~73-~73: Consider a shorter alternative to avoid wordiness.
Context: ...riables} You need a private key in order to sign transactions. Create a .env fi...

(IN_ORDER_TO_PREMIUM)


[style] ~83-~83: Consider a shorter alternative to avoid wordiness.
Context: ...e .env file. You need a private key in order to sign transactions. Make sure this pri...

(IN_ORDER_TO_PREMIUM)


[grammar] ~190-~190: The plural noun “transactions” cannot be used with the article “a”. Did you mean “a transaction” or “transactions”?
Context: ...} Viem makes it easy to prepare a transactions so you can estimate the cost of a trans...

(A_NNS)

Additional comments not posted (3)
pages/builders/app-developers/tutorials/sdk-estimate-costs.mdx (3)

Line range hint 95-103: LGTM! Clear instructions for obtaining ETH on OP Sepolia.

This section effectively explains the need for ETH on OP Sepolia and provides a helpful link to the Superchain Faucet. The use of the Callout component appropriately emphasizes this important information.

Tools
LanguageTool

[style] ~99-~99: Consider a shorter alternative to avoid wordiness.
Context: ...will need to get some ETH on OP Sepolia in order to run the code in this tutorial. <Callou...

(IN_ORDER_TO_PREMIUM)


306-309: LGTM! Important information about estimate accuracy.

This Callout effectively communicates the potential inaccuracy of estimates due to network conditions and gas price fluctuations. It's an important piece of information for users to understand the limitations of the estimation process.


Line range hint 1-317: Excellent tutorial on estimating transaction costs with Viem!

This tutorial provides a comprehensive, well-structured guide to estimating transaction costs on OP Stack using the Viem library. The content is clear, informative, and includes helpful code snippets and explanations throughout. The use of components like Steps, Tabs, and Callouts enhances readability and emphasizes important information.

Some minor suggestions for further improvement:

  1. Ensure consistency in environment variable naming throughout the tutorial.
  2. Add brief explanations for some of the more complex functions or concepts to aid user understanding.
  3. Consider adding a section on troubleshooting common issues that users might encounter during the estimation process.

Overall, this tutorial is an valuable resource for developers working with OP Stack and the Viem library.

Tools
LanguageTool

[grammar] ~190-~190: The plural noun “transactions” cannot be used with the article “a”. Did you mean “a transaction” or “transactions”?
Context: ...} Viem makes it easy to prepare a transactions so you can estimate the cost of a trans...

(A_NNS)

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: 1

🧹 Outside diff range and nitpick comments (4)
pages/builders/app-developers/tutorials/sdk-estimate-costs.mdx (4)

2-4: LGTM! Consider adding a brief explanation of OP Stack.

The updates to the title, description, and introduction accurately reflect the transition to using Viem for estimating transaction costs on OP Stack. The content is clear and informative.

Consider adding a brief explanation or link to what OP Stack is, as some readers might not be familiar with the term.

Also applies to: 9-17


19-24: LGTM! Minor grammatical correction needed.

The "Supported Networks" section provides clear and helpful information about Viem's compatibility with Superchain networks and the possibility of adding custom networks.

In line 21, change "Viem supports any of the Superchain networks." to "Viem supports all of the Superchain networks." for better grammatical accuracy.


61-78: LGTM! Consider rephrasing for conciseness.

The instructions for getting ETH on Sepolia and adding a private key to the environment are clear and helpful.

In line 72, consider rephrasing "You need a private key in order to sign transactions." to "You need a private key to sign transactions." for improved conciseness.

🧰 Tools
🪛 LanguageTool

[style] ~72-~72: Consider a shorter alternative to avoid wordiness.
Context: ...our Environment You need a private key in order to sign transactions. Set your private key...

(IN_ORDER_TO_PREMIUM)


80-101: LGTM! Minor grammatical and typographical corrections needed.

The instructions for starting the Node REPL and getting ETH on OP Sepolia are clear and helpful.

  1. In line 83, add a comma after "Viem": "To interact with Viem, To start the Node REPL run the following command in your terminal:"
  2. In line 94, add "to" before "estimate": "This tutorial explains how to estimate transaction costs on OP Sepolia."
🧰 Tools
🪛 LanguageTool

[uncategorized] ~83-~83: Possible missing comma found.
Context: ...o interact with Viem. To start the Node REPL run the following command in your termi...

(AI_HYDRA_LEO_MISSING_COMMA)


[uncategorized] ~94-~94: Possible missing preposition found.
Context: ... OP Sepolia This tutorial explains how estimate transaction costs on OP Sepolia. You wi...

(AI_HYDRA_LEO_MISSING_TO)


[style] ~95-~95: Consider a shorter alternative to avoid wordiness.
Context: ...will need to get some ETH on OP Sepolia in order to run the code in this tutorial. <Callou...

(IN_ORDER_TO_PREMIUM)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 70bf529 and 8427f62.

📒 Files selected for processing (3)
  • pages/builders/app-developers/tutorials/sdk-estimate-costs.mdx (2 hunks)
  • public/tutorials/sdk-estimate-costs.js (1 hunks)
  • words.txt (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
pages/builders/app-developers/tutorials/sdk-estimate-costs.mdx (1)

Pattern **/*.mdx: "ALWAYS review Markdown content THOROUGHLY with the following criteria:

  • Use proper nouns in place of personal pronouns like 'We' and 'Our' to maintain consistency in communal documentation.
  • Avoid gender-specific language and use the imperative form.
  • Monitor capitalization for emphasis. Use bold for prominence instead of all caps or italics.
  • Ensure proper nouns are capitalized in sentences.
  • Apply the Oxford comma.
  • Use proper title case for headers, buttons, tab names, page names, and links. Sentence case should be used for body content and short phrases, even in links.
  • Use correct spelling and grammar at all times (IMPORTANT).
    "
🪛 LanguageTool
pages/builders/app-developers/tutorials/sdk-estimate-costs.mdx

[style] ~72-~72: Consider a shorter alternative to avoid wordiness.
Context: ...our Environment You need a private key in order to sign transactions. Set your private key...

(IN_ORDER_TO_PREMIUM)


[uncategorized] ~83-~83: Possible missing comma found.
Context: ...o interact with Viem. To start the Node REPL run the following command in your termi...

(AI_HYDRA_LEO_MISSING_COMMA)


[uncategorized] ~94-~94: Possible missing preposition found.
Context: ... OP Sepolia This tutorial explains how estimate transaction costs on OP Sepolia. You wi...

(AI_HYDRA_LEO_MISSING_TO)


[style] ~95-~95: Consider a shorter alternative to avoid wordiness.
Context: ...will need to get some ETH on OP Sepolia in order to run the code in this tutorial. <Callou...

(IN_ORDER_TO_PREMIUM)


[grammar] ~151-~151: The plural noun “transactions” cannot be used with the article “a”. Did you mean “a transaction” or “transactions”?
Context: ...} Viem makes it easy to prepare a transactions so you can estimate the cost of a trans...

(A_NNS)

words.txt

[duplication] ~365-~365: Möglicher Tippfehler: ein Wort wird wiederholt
Context: ...E verkle VHOSTS vhosts Viem viem Viem's VMDEBUG vmdebug VMODULE vmodule wagmi Warpcast XORI xte...

(GERMAN_WORD_REPEAT_RULE)

🔇 Additional comments (7)
pages/builders/app-developers/tutorials/sdk-estimate-costs.mdx (6)

26-53: LGTM! Clear and concise project setup instructions.

The "Dependencies" and "Create a Demo Project" sections provide clear, step-by-step instructions for setting up the project. The use of the component enhances readability and makes it easy for users to follow along.


Line range hint 103-141: LGTM! Well-structured setup for Viem usage.

The "Set Session Variables" section provides clear and well-organized code snippets for importing Viem modules, setting up the account, and creating public and wallet clients. The use of environment variables for the private key is a good security practice.

🧰 Tools
🪛 LanguageTool

[grammar] ~151-~151: The plural noun “transactions” cannot be used with the article “a”. Did you mean “a transaction” or “transactions”?
Context: ...} Viem makes it easy to prepare a transactions so you can estimate the cost of a trans...

(A_NNS)


146-202: LGTM! Comprehensive guide for estimating transaction costs.

The "Estimate Transaction Costs" section provides clear, step-by-step instructions with accompanying code snippets for defining a transaction and estimating various components of the transaction cost. The explanations are informative and the code examples are well-structured.

🧰 Tools
🪛 LanguageTool

[grammar] ~151-~151: The plural noun “transactions” cannot be used with the article “a”. Did you mean “a transaction” or “transactions”?
Context: ...} Viem makes it easy to prepare a transactions so you can estimate the cost of a trans...

(A_NNS)


204-265: LGTM! Excellent walkthrough of transaction execution and cost verification.

The second part of the "Estimate Transaction Costs" section provides a comprehensive guide for sending the transaction and verifying the actual costs. The step-by-step approach, along with the comparison between estimated and actual costs, offers valuable insights into the transaction process on OP Stack.


268-271: LGTM! Helpful note on estimate accuracy.

The callout provides valuable context about the nature of transaction cost estimates, setting appropriate expectations for users regarding the accuracy of these estimates.


272-279: LGTM! Comprehensive list of best practices.

The "Next Steps" section provides a valuable list of best practices and considerations for transaction cost estimation and management. The bullet points cover important aspects such as gas price volatility, transaction data optimization, and retry mechanisms, offering users a solid foundation for working with transactions on OP Stack.

public/tutorials/sdk-estimate-costs.js (1)

28-28: Verify the recipient address in the transaction

The to address is set to 0x1000000000000000000000000000000000000000, which is typically a system contract address on the Optimism network, such as the L2 to L1 Message Passer. Sending Ether directly to this address may not have the intended effect and could result in loss of funds.

Please verify that this is the correct recipient for your transaction. If you intended to interact with a different contract or send funds to a specific address, update the to field accordingly.

Run the following script to check occurrences and usages of this address in the codebase:

✅ Verification successful

Recipient address verified as correct

The to address 0x1000000000000000000000000000000000000000 is appropriately used as the recipient in the transaction. It corresponds to a system contract address on the Optimism network, such as the L2 to L1 Message Passer. In the context of tutorials, sending Ether to this address is intentional and ensures that funds are not lost.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for usages of the address '0x1000000000000000000000000000000000000000' in the codebase.

rg '0x1000000000000000000000000000000000000000'

Length of output: 686

account,
to: '0x1000000000000000000000000000000000000000',
value: parseEther('0.005'),
gasPrice: parseGwei('20')
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

Ensure consistent gas price between transaction and estimation

In your transaction object, you specify a fixed gas price of 20 gwei (gasPrice: parseGwei('20')), but when estimating costs, you retrieve the current network gas price using publicClient.getGasPrice(). This inconsistency could lead to discrepancies between your estimated and actual costs if the network gas price differs from 20 gwei at the time of transaction.

To improve accuracy and ensure consistency, consider using the same gas price for both the transaction and the estimation. You have two options:

  1. Use the network's gas price for both the transaction and estimation:

    Remove the gasPrice field from your transaction object. This will allow the transaction to use the current network gas price, aligning it with your estimation.

    Apply this diff to implement this change:

     const transaction = {
       account,
       to: '0x1000000000000000000000000000000000000000',
       value: parseEther('0.005'),
    -  gasPrice: parseGwei('20')
     }
  2. Use a fixed gas price for both the transaction and estimation:

    Set effectiveGasPrice to the same fixed value you used in the transaction (parseGwei('20')), ensuring both use 20 gwei.

    Apply this diff to implement this change:

    -const effectiveGasPrice = await publicClient.getGasPrice()
    +const effectiveGasPrice = parseGwei('20')

Also applies to: 38-39


```js file=<rootDir>/public/tutorials/sdk-estimate-costs.js#L6 hash=755b77a7ffc7dfdc186f36c37d3d847a
Copy link
Contributor

Choose a reason for hiding this comment

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

Please use the file import syntax instead of inlining the code. Using the file import syntax guarantees that the tutorial actually works by running the tutorial in CI. If you inline the code then you can only guarantee that the tutorial works by running it manually which is a huge waste of time and no one will actually do it. End result is that tutorials become outdated and broken which undermines the docs.

const totalSum = l2CostEstimate.add(l1CostEstimate)
console.log(ethers.utils.formatEther(totalSum))
// Estimate gas limit
const gasLimit = await publicClient.estimateGas(transaction)
Copy link
Contributor

Choose a reason for hiding this comment

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

Note that the reason this was originally not indented was because the file import syntax imports the code as-is including indents. It's better to not have this first indent here.

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.

2 participants