Day 3: Gas Fee Estimation and Cost Calculator

What You Will Learn Today

Why Are We Doing This?

Why estimate fees? Just send the transaction!

Here is why this matters:

Imagine you are using a payment app and you want to send $50 to a friend.

BAD UX (without estimation):

You: "Send $50 to John"

App: "Sending..."

Result: Transaction failed - insufficient funds

You: "Wait, I have $50... why did it fail?"


GOOD UX (with estimation):

You: "Send $50 to John"

App: "Total cost: $50.00 + $0.01 fee = $50.01"

You: "Oh, I only have $50.00. Let me send $49.99 instead."

App: "Success! Sent $49.99 (+ $0.01 fee)"

The Arc Advantage

Traditional blockchain (Ethereum):

Arc blockchain:

Prerequisites


Step 1: Navigate to Your Project Folder

Open Terminal in VS Code and run:

cd arc-project

Verify you are in the right folder:

ls

You should see your previous files:

Step 2: Basic Gas Estimation

Create Gas Estimator

  1. In VS Code, right-click your arc-project folder and select New File
  2. Name it: estimate-gas.ts
  3. Copy and paste this code:
import { createViemAdapterFromPrivateKey } from "@circle-fin/adapter-viem-v2";
import { createPublicClient, http, defineChain, parseUnits, formatUnits } from "viem";

const arcTestnet = defineChain({
  id: 5042002,
  name: "Arc Testnet",
  network: "arc-testnet",
  nativeCurrency: { name: "USDC", symbol: "USDC", decimals: 6 },
  rpcUrls: {
    default: { http: ["https://rpc.testnet.arc.network"] },
    public: { http: ["https://rpc.testnet.arc.network"] },
  },
});

const client = createPublicClient({
  chain: arcTestnet,
  transport: http(),
});

const estimateGas = async () => {
  console.log("Gas Fee Estimation Tool\n");
  console.log("----------------------------------\n");

  const adapter = createViemAdapterFromPrivateKey({
    privateKey: process.env.PRIVATE_KEY as string,
  });

  const address = await adapter.getAddress({ chain: "Arc_Testnet" });
  console.log("Your wallet:", address);
  console.log("----------------------------------\n");

  // Define a sample transaction
  const recipientAddress = "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1";
  const amountUSDC = "10.00";
  const amountWei = parseUnits(amountUSDC, 18); // Arc uses 18 decimals

  console.log("Transaction Details:");
  console.log("   To:", recipientAddress);
  console.log("   Amount:", amountUSDC, "USDC");
  console.log("   Chain: Arc Testnet\n");

  try {
    console.log("Estimating gas fee...\n");

    // Estimate gas for the transaction
    const gasEstimate = await client.estimateGas({
      account: address,
      to: recipientAddress,
      value: amountWei,
    });

    // Get current gas price
    const gasPrice = await client.getGasPrice();

    // Calculate total gas cost in wei
    const gasCostWei = gasEstimate * gasPrice;
    const gasCostUSDC = formatUnits(gasCostWei, 18);

    // Calculate total cost
    const totalCost = (parseFloat(amountUSDC) + parseFloat(gasCostUSDC)).toFixed(6);

    console.log("Estimation Complete");
    console.log("----------------------------------");
    console.log("Gas Limit:", gasEstimate.toString(), "units");
    console.log("Gas Price:", formatUnits(gasPrice, 9), "Gwei");
    console.log("Gas Fee:", gasCostUSDC, "USDC");
    console.log("Amount:", amountUSDC, "USDC");
    console.log("----------------------------------");
    console.log("Total Cost:", totalCost, "USDC");
    console.log("----------------------------------\n");

    // Check if user has enough
    const balance = await client.getBalance({ address });
    const balanceUSDC = formatUnits(balance, 18);

    console.log("Balance Check:");
    console.log("   Your balance:", balanceUSDC, "USDC");
    console.log("   Required:", totalCost, "USDC");

    if (parseFloat(balanceUSDC) >= parseFloat(totalCost)) {
      console.log("   Status: Sufficient funds\n");
    } else {
      const needed = (parseFloat(totalCost) - parseFloat(balanceUSDC)).toFixed(6);
      console.log("   Status: Insufficient funds\n");
      console.log("   You need", needed, "more USDC");
    }

  } catch (error: any) {
    console.error("Error:", error.message);
    console.log("\nCommon issues:");
    console.log("- Invalid recipient address");
    console.log("- Network connection problem");
    console.log("- Private key incorrect");
  }
};

estimateGas();
  1. Save the file (Ctrl+S)

Run the Script

npx tsx --env-file=.env estimate-gas.ts

Expected Output

Gas Fee Estimation Tool

----------------------------------

Your wallet: 0x6967b953509306348d42D541B4AA35d6aB1123AE
----------------------------------

Transaction Details:
   To: 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1
   Amount: 10.00 USDC
   Chain: Arc Testnet

Estimating gas fee...

Estimation Complete
----------------------------------
Gas Limit: 21000 units
Gas Price: 0.001 Gwei
Gas Fee: 0.000021 USDC
Amount: 10.00 USDC
----------------------------------
Total Cost: 10.000021 USDC
----------------------------------

Balance Check:
   Your balance: 37.998877 USDC
   Required: 10.000021 USDC
   Status: Sufficient funds

Step 3: Build a Cost Calculator

Create Interactive Calculator

  1. Right-click your arc-project folder and select New File
  2. Name it: cost-calculator.ts
  3. Copy and paste this code:
import { createViemAdapterFromPrivateKey } from "@circle-fin/adapter-viem-v2";
import { createPublicClient, http, defineChain, parseUnits, formatUnits } from "viem";

const arcTestnet = defineChain({
  id: 5042002,
  name: "Arc Testnet",
  network: "arc-testnet",
  nativeCurrency: { name: "USDC", symbol: "USDC", decimals: 6 },
  rpcUrls: {
    default: { http: ["https://rpc.testnet.arc.network"] },
    public: { http: ["https://rpc.testnet.arc.network"] },
  },
});

const client = createPublicClient({
  chain: arcTestnet,
  transport: http(),
});

const calculateCosts = async (amounts: string[]) => {
  console.log("USDC Transfer Cost Calculator\n");
  console.log("----------------------------------\n");

  const adapter = createViemAdapterFromPrivateKey({
    privateKey: process.env.PRIVATE_KEY as string,
  });

  const address = await adapter.getAddress({ chain: "Arc_Testnet" });
  const recipientAddress = "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1";

  console.log("Calculating costs for multiple amounts...\n");

  // Store results
  const results: any[] = [];

  // Get gas price once (it is constant for all transactions)
  const gasPrice = await client.getGasPrice();

  for (const amount of amounts) {
    try {
      const amountWei = parseUnits(amount, 18);

      const gasEstimate = await client.estimateGas({
        account: address,
        to: recipientAddress,
        value: amountWei,
      });

      const gasCostWei = gasEstimate * gasPrice;
      const gasCostUSDC = formatUnits(gasCostWei, 18);
      const total = (parseFloat(amount) + parseFloat(gasCostUSDC)).toFixed(6);

      results.push({
        amount: amount,
        fee: gasCostUSDC,
        total: total,
      });
    } catch (error) {
      results.push({
        amount: amount,
        fee: "ERROR",
        total: "ERROR",
      });
    }
  }

  // Display results in a table
  console.log("Amount       | Gas Fee      | Total");
  console.log("-------------|--------------|-------------");

  results.forEach((result) => {
    const amountStr = `${result.amount} USDC`.padEnd(12);
    const feeStr = `${result.fee} USDC`.padEnd(12);
    const totalStr = `${result.total} USDC`.padEnd(12);
    console.log(`${amountStr} | ${feeStr} | ${totalStr}`);
  });

  console.log("\n----------------------------------");

  // Calculate some statistics
  console.log("\nFee Analysis:");
  console.log("----------------------------------\n");

  const validResults = results.filter(r => r.fee !== "ERROR");

  if (validResults.length > 0) {
    const avgFee = validResults.reduce((sum, r) => sum + parseFloat(r.fee), 0) / validResults.length;

    console.log("Average gas fee:", avgFee.toFixed(6), "USDC");
    console.log("Fee is constant regardless of amount");
    console.log("Sending $1 costs same as sending $1000\n");

    // Compare with Ethereum
    console.log("Comparison with Ethereum:");
    console.log("   Arc fee: ~$0.000021 USDC (stable)");
    console.log("   Ethereum fee: ~$5-$20 (volatile)");
    console.log("   Savings: 200,000x - 1,000,000x cheaper\n");
  }
};

// Test with different amounts
const testAmounts = ["1.00", "10.00", "50.00", "100.00", "500.00"];

calculateCosts(testAmounts);
  1. Save the file

Run It

npx tsx --env-file=.env cost-calculator.ts

Expected Output

USDC Transfer Cost Calculator

----------------------------------

Calculating costs for multiple amounts...

Amount       | Gas Fee      | Total
-------------|--------------|-------------
1.00 USDC    | 0.000021 USDC| 1.000021 USDC
10.00 USDC   | 0.000021 USDC| 10.000021 USDC
50.00 USDC   | 0.000021 USDC| 50.000021 USDC
100.00 USDC  | 0.000021 USDC| 100.000021 USDC
500.00 USDC  | 0.000021 USDC| 500.000021 USDC

----------------------------------

Fee Analysis:
----------------------------------

Average gas fee: 0.000021 USDC
Fee is constant regardless of amount
Sending $1 costs same as sending $1000

Comparison with Ethereum:
   Arc fee: ~$0.000021 USDC (stable)
   Ethereum fee: ~$5-$20 (volatile)
   Savings: 200,000x - 1,000,000x cheaper

Understanding Arc Gas Fees

Why Are Arc Fees So Low?

Arc is optimized specifically for USDC transfers. Traditional chains (Ethereum) were designed for complex smart contracts, so they are expensive. Arc stripped away complexity and focused on one thing: fast, cheap USDC payments.

Key Points


Troubleshooting

Error: Estimation failed

Fix:

Fee shows as "0.000000"

This should not happen on Arc, but if it does:

Balance check shows insufficient even though I have funds

Fix:

What You Learned Today

Technical Skills

Concepts

Your Project Folder Now

Your arc-project folder should now contain:

arc-project/
├── .env
├── package.json
├── node_modules/
├── transfer.ts
├── check-balance.ts
├── multi-chain-balance.ts
├── transaction-history.ts
├── dashboard.ts
├── estimate-gas.ts         (new)
└── cost-calculator.ts      (new)

Key Takeaway

Transparency builds trust.

Users trust apps that show costs upfront. No hidden fees. No surprises.

Arc makes this easy because fees are:

Your P2P app will have the most transparent pricing in crypto!

See you for Day 4!