Sending Transactions Using Web3

·

Sending transactions on the Ethereum blockchain is a foundational skill for any blockchain developer. Whether you're transferring ETH, interacting with smart contracts, or building decentralized applications (dApps), understanding how to securely and efficiently send transactions using Web3 is essential. This guide walks you through the entire process—from setup to execution—using Alchemy Web3, ideal for beginners and intermediate developers alike.

We’ll cover the three core steps: create, sign, and broadcast, while emphasizing security best practices and real-world implementation details.


Understanding the Basics of Ethereum Transactions

Before diving into code, it’s crucial to understand what happens behind the scenes when you send a transaction on Ethereum.

Why Private Keys Matter

Alchemy and most node providers do not store your private keys. This is a security feature, not a limitation. Your private key grants full control over your Ethereum address—anyone with access can sign transactions on your behalf. Therefore, never share your private key with any service or individual.

To write data to the blockchain (i.e., send a transaction), you must sign it locally using your private key before broadcasting it through a node provider like Alchemy.

👉 Generate highly click-attractive anchor text here based on article context and anchor link characteristics; no brand names other than 'OKX' may appear here.

What Is a Signer?

A signer is a tool or library that signs transactions using your private key. In backend environments, we often use libraries like web3.js or ethers.js. On the frontend, MetaMask acts as a signer by prompting users to approve and sign transactions.

In this tutorial, we'll use Alchemy Web3—a powerful wrapper around standard JSON-RPC methods—to sign and send our transaction.

Key Difference: eth_sendTransaction vs eth_sendRawTransaction

We’ll be using web3.eth.sendSignedTransaction(), which maps to eth_sendRawTransaction.


Prerequisites

Before proceeding, ensure you have:


Step-by-Step Guide to Sending a Transaction

Step 1: Create an Alchemy App on Sepolia Testnet

  1. Go to the Alchemy Dashboard
  2. Click “Create App”
  3. Choose Sepolia as the network
  4. Copy the HTTP API URL under “View Key” — you’ll need this later

Using a testnet like Sepolia allows you to experiment without risking real funds.

Step 2: Get Test ETH from a Faucet

Visit the Alchemy Sepolia Faucet and request test ETH using your MetaMask wallet address. Confirm the transaction in your wallet and verify the balance.

Step 3: Set Up Your Project

Open your terminal and run:

mkdir sendtx-example
cd sendtx-example
npm init -y

Step 4: Install Required Packages

Install Alchemy Web3 and dotenv for environment variable management:

npm install @alch/alchemy-web3 dotenv

Step 5: Configure Environment Variables

Create a .env file in your project root:

API_URL="your-alchemy-http-url"
PRIVATE_KEY="your-metamask-private-key"
🔒 Never commit .env to version control. Add it to .gitignore.

Step 6: Write the Transaction Script

Create sendTx.js with the following code:

async function main() {
  require('dotenv').config();
  const { API_URL, PRIVATE_KEY } = process.env;
  const { createAlchemyWeb3 } = require("@alch/alchemy-web3");
  const web3 = createAlchemyWeb3(API_URL);

  const myAddress = '0xYourPublicAddress'; // Replace with your own
  const recipient = '0x31B98D14007bDEe637298086988A0bBd31184523'; // Sepolia faucet

  const nonce = await web3.eth.getTransactionCount(myAddress, 'latest');

  const transaction = {
    to: recipient,
    value: '0xDE0B6B3A7640000', // 1 ETH in hex (wei)
    gas: 30000,
    nonce: nonce,
    chainId: 11155111 // Sepolia chain ID
  };

  const signedTx = await web3.eth.accounts.signTransaction(transaction, PRIVATE_KEY);

  web3.eth.sendSignedTransaction(signedTx.rawTransaction, (error, hash) => {
    if (!error) {
      console.log("🎉 Transaction hash:", hash);
      console.log("Check Alchemy Mempool or Etherscan to track its status!");
    } else {
      console.log("❗Error submitting transaction:", error);
    }
  });
}

main();

Key Components Explained


Run and Monitor Your Transaction

Execute the script:

node sendTx.js

If successful, you’ll see a transaction hash. Now:

👉 Generate highly click-attractive anchor text here based on article context and anchor link characteristics; no brand names other than 'OKX' may appear here.

Track It in Real Time

Go to your Alchemy dashboard > Mempool, filter by your app, and find your transaction. Watch it move from pending to mined.

You can also paste the hash into Sepolia Etherscan for full details.


Frequently Asked Questions (FAQ)

Q: Can I use ethers.js instead of web3.js?

Yes! While this guide uses Alchemy Web3 (based on web3.js), ethers.js is another popular choice offering a more modern API. Both support signing and sending raw transactions securely.

Q: What should I do if my transaction fails?

Common causes include:

Q: How do I send tokens (ERC-20), not ETH?

To send tokens, you need to call the token contract’s transfer() function. This requires encoding the function call into the data field of the transaction.

Q: Is it safe to use .env files for private keys?

Yes—as long as they are not committed to public repositories. For production apps, consider using secure secret managers like AWS KMS or Hashicorp Vault.

Q: Can I send private transactions?

Yes, Alchemy’s Transact API supports private transactions via Flashbots, preventing front-running. Explore their Transact API documentation for advanced use cases.

Q: How can I optimize gas costs?

Use dynamic gas pricing:

const gasPrice = await web3.eth.getGasPrice();
transaction.gasPrice = gasPrice;

Or integrate Alchemy’s Notify API to act when gas prices drop.


Final Thoughts

You’ve now successfully sent an Ethereum transaction using Web3 and Alchemy. By following secure practices—like never exposing your private key and using environment variables—you're well on your way to building robust dApps.

Whether you're transferring ETH, interacting with DeFi protocols, or deploying contracts, mastering transaction handling is key.

With tools like Alchemy simplifying node access and monitoring, developers can focus on innovation rather than infrastructure.

Core keywords naturally integrated: Web3, Ethereum transactions, Alchemy, sendSignedTransaction, private key, nonce, gas, blockchain development.