How to Send ETH Using TypeScript: A Step-by-Step Guide

·

Introduction

This guide provides a foundational approach to sending Ethereum (ETH) on the Sepolia testnet using TypeScript. We'll cover address generation, transaction execution, and verification—ideal for developers exploring blockchain interactions.


Prerequisites

Before starting, ensure you have:


Generating Ethereum Addresses

Ethereum addresses consist of a public key (for receiving funds) and a private key (for authorizing transactions). Here’s how to generate them:

Required Packages

Install these via npm:

npm install ethers typescript ts-node

Code Implementation

Create generateAddress.ts:

import { ethers } from 'ethers';

function generateEthereumAddress() {
  const wallet = ethers.Wallet.createRandom();
  return {
    address: wallet.address,
    privateKey: wallet.privateKey
  };
}

const newAddress = generateEthereumAddress();
console.log(`Public Address: ${newAddress.address}`);
console.log(`Private Key: ${newAddress.privateKey}`);

Output Example

Public Address: 0x0x47FD9A30F48a656D9062aDE956c65f0ec8e2186c
Private Key: 0x(secured_private_key)

👉 Learn how to secure your private keys


Executing ETH Transfers

Transaction Code

Create transfer.ts:

import { ethers } from "ethers";

const senderPrivateKey = 'YOUR_SENDER_PRIVATE_KEY';
const recipientAddress = 'RECIPIENT_PUBLIC_ADDRESS';
const sepoliaProvider = new ethers.JsonRpcProvider('https://rpc.sepolia.org');

async function sendEth() {
  const wallet = new ethers.Wallet(senderPrivateKey, sepoliaProvider);
  const tx = {
    to: recipientAddress,
    value: ethers.parseEther("0.05") // Sending 0.05 ETH
  };

  const txResponse = await wallet.sendTransaction(tx);
  console.log('Transaction Hash:', txResponse.hash);
  
  const receipt = await txResponse.wait();
  console.log('Transaction Details:', receipt);
}

sendEth();

Expected Output

Transaction Hash: 0xcfd4dbbb05f0424a97bf1db963c1d42b65dbbd3c930881a64e2c0e7dbe297447
Transaction Details: { ... }

Verifying the Transaction

  1. Check Transaction Status:

    • Use a block explorer like Etherscan Sepolia and search by the transaction hash.
    • Confirm the status shows "Success."
  2. Balance Updates:

    • Sender: Original balance (3.3455 ETH) → New balance (3.2955 ETH).
    • Recipient: Original balance (0.27525 ETH) → New balance (0.32525 ETH).

👉 Understand Ethereum gas fees


FAQ

1. Why is the sender’s balance reduced by more than the sent amount?

2. How do I get Sepolia testnet ETH?

3. Is it safe to share the private key in code?


Key Takeaways

By following these steps, you’ve mastered basic ETH transfers on the testnet! For advanced scenarios, explore smart contract interactions or layer-2 solutions.