Skip to content

Commit d88c7fb

Browse files
committed
use file format system
1 parent 8427f62 commit d88c7fb

File tree

2 files changed

+55
-117
lines changed

2 files changed

+55
-117
lines changed

pages/builders/app-developers/tutorials/sdk-estimate-costs.mdx

Lines changed: 27 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -109,35 +109,22 @@ Let's set those up now.
109109

110110
{<h3>Import Viem and other necessary modules</h3>}
111111

112-
```js
113-
114-
const { createPublicClient, createWalletClient, http, parseEther, parseGwei, formatEther } = require('viem');
115-
const { privateKeyToAccount } = require('viem/accounts');
116-
const { optimismSepolia } = require('viem/chains');
117-
const { publicActionsL2, walletActionsL2 } = require('viem/op-stack');
112+
```js file=<rootDir>/public/tutorials/sdk-estimate-costs.js#L3-L6 hash=32ecaac58846bfe7e785e2cc35562120
118113
```
119114

120115
{<h3>Set up the account</h3>}
121116

122-
```js
123-
const account = privateKeyToAccount(process.env.TUTORIAL_PRIVATE_KEY);
117+
```js file=<rootDir>/public/tutorials/sdk-estimate-costs.js#L8-L9 hash=165490e75b825c786a937fba7b8e159d
124118
```
119+
125120
{<h3>Create the public client</h3>}
126121

127-
```js
128-
const publicClientL2 = createPublicClient({
129-
chain: optimismSepolia,
130-
transport: http("https://sepolia.optimism.io"),
131-
}).extend(publicActionsL2());
122+
```js file=<rootDir>/public/tutorials/sdk-estimate-costs.js#L11-L14 hash=42293ff382c932f806beb7252803a848
132123
```
133124

134125
{<h3>Create the wallet client</h3>}
135126

136-
```js
137-
const walletClientL2 = createWalletClient({
138-
chain: optimismSepolia,
139-
transport: http("https://sepolia.optimism.io"),
140-
}).extend(walletActionsL2());
127+
```js file=<rootDir>/public/tutorials/sdk-estimate-costs.js#L16-L19 hash=e7b6423850765242512e71589382791b
141128
```
142129
</Steps>
143130

@@ -151,43 +138,31 @@ You're now going to estimate the cost of a transaction on OP Mainnet.
151138
Viem makes it easy to prepare a transactions so you can estimate the cost of a transaction before you sign it.
152139
Here you'll define an object with the required transaction fields and send a small amount of ETH from your address to the address `0x1000000000000000000000000000000000000000`.
153140

154-
```js
155-
const transaction = {
156-
account,
157-
to: '0x1000000000000000000000000000000000000000',
158-
value: parseEther('0.005'),
159-
gasPrice: parseGwei('20')
160-
};
161-
```
141+
```js file=<rootDir>/public/tutorials/sdk-estimate-costs.js#L21-L26 hash=583ee48142f33686188a7bf1cc312a1c
142+
```
162143
This transaction will send `0.005` ETH to the specified address with a gas price of 20 Gwei.
163144

164145
{<h3>Estimate the execution gas fee</h3>}
165146

166147
Now, let's estimate the gas limit for our transaction.
167148

168-
```js
169-
const gasLimit = await publicClientL2.estimateGas(transaction);
170-
console.log(`Estimated Gas Limit: ${gasLimit}`);
171-
```
149+
```js file=<rootDir>/public/tutorials/sdk-estimate-costs.js#L28-L29 hash=014939607bf2444d5f2e5a7babb02a46
150+
```
172151

173152
<Steps>
174153
{<h3>Retrieve the current gas price</h3>}
175154

176155
Retrieve the current gas price (effective gas price), Alternatively, given that you already set the gas price manually, you can use the `getGasPrice` method from viem.
177156

178-
```js
179-
const effectiveGasPrice = await publicClientL2.getGasPrice();
180-
console.log(`effective Gas Price, ${effectiveGasPrice}`);
181-
```
157+
```js file=<rootDir>/public/tutorials/sdk-estimate-costs.js#L31-L32 hash=b43ae2cb1a7471de55858fbc7f7fe5a6
158+
```
182159

183160
{<h3>Calculate the execution gas fee</h3>}
184161

185162
To calculate the execution gas fee simply multiply the gas limit by the effective gas price.
186163

187-
```js
188-
const l2CostEstimate = gasLimit * effectiveGasPrice;
189-
console.log(`Estimated Execution Gas Fee: ${formatEther(l2CostEstimate)}`);
190-
```
164+
```js file=<rootDir>/public/tutorials/sdk-estimate-costs.js#L34-L35 hash=3e536e97b83458d3d3c7545b2c74ffd6
165+
```
191166
</Steps>
192167

193168
{<h3>Estimate the L1 data fee</h3>}
@@ -196,73 +171,55 @@ You're now going to estimate the cost of a transaction on OP Mainnet.
196171
Under the hood, this function is estimating the amount of Ethereum gas required to publish this transaction on Ethereum and multiplying it by the current Ethereum gas price (as tracked by the L2).
197172
This function returns the current cost estimate in wei.
198173

199-
```js
200-
const l1CostEstimate = await publicClientL2.estimateL1Fee(transaction)
201-
console.log(`Estimated L1 data Fee: ${formatEther(l1CostEstimate)}`);
202-
```
174+
```js file=<rootDir>/public/tutorials/sdk-estimate-costs.js#L37-L38 hash=b1ef73988e0876529a72b61d5822cbe1
175+
```
203176

204177
{<h3>Estimate the total cost</h3>}
205178

206179
Once you've individually estimated the execution gas fee and the L1 data fee, you can sum these two values together to get the total cost of the transaction.
207180

208-
```js
209-
const totalEstimate = l2CostEstimate + l1CostEstimate;
210-
console.log(`Estimated Total Cost: ${formatEther(totalEstimate)} `);
211-
```
181+
```js file=<rootDir>/public/tutorials/sdk-estimate-costs.js#L40-L41 hash=8685f586913b87a5881cc6f917d0de50
182+
```
212183

213184
{<h3>Send the transaction</h3>}
214185

215186
Now that you've estimated the total cost of the transaction, go ahead and send it to the network.
216187
This will make it possible to see the actual cost of the transaction to compare to your estimate.
217188

218-
```js
219-
const txHash = await walletClientL2.sendTransaction(transaction)
220-
console.log(`Transaction Hash: ${txHash}`);
221-
```
189+
```js file=<rootDir>/public/tutorials/sdk-estimate-costs.js#L43-L44 hash=a0a19fa7fc17165d934cc9f7af075464
190+
```
222191

223192
{<h3>Check the actual execution gas fee</h3>}
224193

225194
Once you get back the transaction receipt, check the actual execution gas fee.
226195
You can do so by accessing the `gasUsed` and `effectiveGasPrice` from the transaction receipt.
227196
You can then multiply these values to get the actual L2 cost of the transaction
228197

229-
```js
230-
const receipt = await publicClientL2.getTransactionReceipt({ hash: txHash });
231-
console.log('Transaction receipt:', receipt);
232-
233-
const l2CostActual = receipt.gasUsed * receipt.effectiveGasPrice;
234-
console.log(`L2 Actual Cost: ${formatEther(l2CostActual)}`);
235-
```
198+
```js file=<rootDir>/public/tutorials/sdk-estimate-costs.js#L46-L49 hash=e128f21d2c994f42bdc7f5fb51eb127d
199+
```
236200

237201
{<h3>Check the actual L1 data fee</h3>}
238202

239203
You can also check the actual L1 data fee.
240204

241-
```js
242-
const l1CostActual = await publicClientL2.estimateL1Fee(txHash)
243-
console.log(`l1CostActual gas fee: ${formatEther(l1CostActual)}`);
244-
245-
```
205+
```js file=<rootDir>/public/tutorials/sdk-estimate-costs.js#L51-L52 hash=ea1801a7618fa2a21f02a97717380f42
206+
```
246207

247208
{<h3>Check the actual total cost</h3>}
248209

249210
Sum these two together to get the actual total cost of the transaction.
250211

251-
```js
252-
const totalActual = l2CostActual + l1CostActual;
253-
console.log(`Total Actual Cost: ${formatEther(totalActual)}`);
254-
```
212+
```js file=<rootDir>/public/tutorials/sdk-estimate-costs.js#L54-L56 hash=6f7943da9d70654dc040b5561b3b360d
213+
```
255214

256215
{<h3>Check the difference</h3>}
257216

258217
Finally, check the difference between the estimated total cost and the actual total cost.
259218
This will give you a sense of how accurate your estimate was.
260219
Estimates will never be entirely accurate, but they should be close!
261220

262-
```js
263-
const difference = totalEstimate >= totalActual ? totalEstimate - totalActual : totalActual - totalEstimate
264-
console.log(`Estimation Difference: ${formatEther(difference)} ETH`)
265-
```
221+
```js file=<rootDir>/public/tutorials/sdk-estimate-costs.js#L57-L58 hash=20c8c60af1cc39e842b207cfd2dfa2cb
222+
```
266223
</Steps>
267224

268225
<Callout type="info">

public/tutorials/sdk-estimate-costs.js

Lines changed: 28 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -6,74 +6,55 @@ const { optimismSepolia } = require('viem/chains');
66
const { publicActionsL2, walletActionsL2 } = require('viem/op-stack');
77

88
const privateKey = process.env.TUTORIAL_PRIVATE_KEY
9-
109
const account = privateKeyToAccount(privateKey)
1110

12-
// Set up the public client
1311
const publicClient = createPublicClient({
1412
chain: optimismSepolia,
1513
transport: http("https://sepolia.optimism.io"),
1614
}).extend(publicActionsL2())
1715

18-
// Set up the wallet client
19-
const walletClient = createWalletClient({
16+
const walletClientL2 = createWalletClient({
2017
chain: optimismSepolia,
2118
transport: http("https://sepolia.optimism.io"),
2219
}).extend(walletActionsL2())
2320

24-
try {
25-
// Prepare the transaction
26-
const transaction = {
27-
account,
28-
to: '0x1000000000000000000000000000000000000000',
29-
value: parseEther('0.005'),
30-
gasPrice: parseGwei('20')
31-
}
32-
33-
// Estimate gas limit
34-
const gasLimit = await publicClient.estimateGas(transaction)
35-
console.log(`Estimated Gas Limit: ${gasLimit}`)
36-
37-
// Get current gas price
38-
const effectiveGasPrice = await publicClient.getGasPrice()
39-
console.log(`Effective Gas Price: ${formatEther(effectiveGasPrice)} ETH`)
21+
const transaction = {
22+
account,
23+
to: '0x1000000000000000000000000000000000000000',
24+
value: parseEther('0.005'),
25+
gasPrice: parseGwei('20')
26+
}
4027

41-
// Calculate execution gas fee
42-
const l2CostEstimate = gasLimit * effectiveGasPrice
43-
console.log(`Estimated Execution Gas Fee: ${formatEther(l2CostEstimate)} ETH`)
28+
const gasLimit = await publicClient.estimateGas(transaction)
29+
console.log(`Estimated Gas Limit: ${gasLimit}`)
4430

45-
// Estimate L1 data fee
46-
const l1CostEstimate = await publicClient.estimateL1Fee(transaction)
47-
console.log(`Estimated L1 Data Fee: ${formatEther(l1CostEstimate)} ETH`)
31+
const effectiveGasPrice = await publicClient.getGasPrice()
32+
console.log(`Effective Gas Price: ${formatEther(effectiveGasPrice)} ETH`)
4833

49-
// Calculate total estimated cost
50-
const totalEstimate = l2CostEstimate + l1CostEstimate
51-
console.log(`Estimated Total Cost: ${formatEther(totalEstimate)} ETH`)
34+
const l2CostEstimate = gasLimit * effectiveGasPrice
35+
console.log(`Estimated Execution Gas Fee: ${formatEther(l2CostEstimate)} ETH`)
5236

53-
// Send the transaction
54-
const txHash = await walletClient.sendTransaction(transaction)
55-
console.log(`Transaction Hash: ${txHash}`)
37+
const l1CostEstimate = await publicClient.estimateL1Fee(transaction)
38+
console.log(`Estimated L1 Data Fee: ${formatEther(l1CostEstimate)} ETH`)
5639

57-
// Wait for the transaction to be mined
58-
const receipt = await publicClient.waitForTransactionReceipt({ hash: txHash })
40+
const totalEstimate = l2CostEstimate + l1CostEstimate
41+
console.log(`Estimated Total Cost: ${formatEther(totalEstimate)} ETH`)
5942

60-
// Calculate actual costs
61-
const l2CostActual = receipt.gasUsed * receipt.effectiveGasPrice
62-
console.log(`Actual Execution Gas Fee: ${formatEther(l2CostActual)} ETH`)
43+
const txHash = await walletClientL2.sendTransaction(transaction)
44+
console.log(`Transaction Hash: ${txHash}`)
6345

64-
const l1CostActual = await publicClient.estimateL1Fee({ hash: txHash })
65-
console.log(`Actual L1 Data Fee: ${formatEther(l1CostActual)} ETH`)
46+
const receipt = await publicClient.waitForTransactionReceipt({ hash: txHash })
6647

67-
const totalActual = l2CostActual + l1CostActual
68-
console.log(`Actual Total Cost: ${formatEther(totalActual)} ETH`)
48+
const l2CostActual = receipt.gasUsed * receipt.effectiveGasPrice
49+
console.log(`Actual Execution Gas Fee: ${formatEther(l2CostActual)} ETH`)
6950

70-
// Compare estimated vs actual costs
71-
const difference = totalEstimate >= totalActual ? totalEstimate - totalActual : totalActual - totalEstimate
72-
console.log(`Estimation Difference: ${formatEther(difference)} ETH`)
51+
const l1CostActual = await publicClient.estimateL1Fee({ hash: txHash })
52+
console.log(`Actual L1 Data Fee: ${formatEther(l1CostActual)} ETH`)
7353

74-
} catch (error) {
75-
console.error('Error:', error)
76-
}
54+
const totalActual = l2CostActual + l1CostActual
55+
console.log(`Actual Total Cost: ${formatEther(totalActual)} ETH`)
7756

57+
const difference = totalEstimate >= totalActual ? totalEstimate - totalActual : totalActual - totalEstimate
58+
console.log(`Estimation Difference: ${formatEther(difference)} ETH`)
7859

7960
})()

0 commit comments

Comments
 (0)