paint-brush
How to Send Ethers Programmatically without Metamaskby@daltonic
561 reads
561 reads

How to Send Ethers Programmatically without Metamask

by Darlington Gospel February 8th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

This tutorial will show you how to transfer Ethers using code rather than Metamask. The implementation makes use of the ethers library, which allows JavaScript to interact with Ether networks and contracts.
featured image - How to Send Ethers Programmatically without Metamask
Darlington Gospel  HackerNoon profile picture

Introduction

This tutorial will show you how to transfer Ethers using code rather than Metamask. The implementation makes use of the ethers library, which allows JavaScript to interact with Ethereum networks and contracts.


Upon completion, you will have gained a deeper understanding of how to programmatically transmit Ethers and will have a working sample for future reference.


Sending Ethers without Metamask

Here is a full code performing a programmatic transaction of ethers between accounts.

To dive deeper into the world of Web3 development, check out this video on how to build a decentralized autonomous organization.


Let's start by taking a closer look at the code and understanding how it works.

Clone this repository into your preferred working directory using the command below. Make sure you have NodeJs and Git Bash installed on your local machine before proceeding with these steps.


git clone https://github.com/Daltonic/tailwind_ethers_starter_kit <PROJECT NAME>


Next, you need to install the packages using npm install or yarn install on that project directory.


Next, create a file at the root of this project called transactions.js and start by importing the **ethers** library from hardhat:


const { ethers } = require('hardhat')


Next, it defines two helper functions, **toWei** and **fromWei**, to convert between Ether and its smallest unit, Wei. This is important because the Ethereum network operates in Wei, so we need to make sure the amounts we send are in Wei.


const toWei = (num) => ethers.utils.parseEther(num.toString())
const fromWei = (num) => ethers.utils.formatEther(num)


These two functions, **toWei** and **fromWei**, convert between ether and wei. **toWei** converts a value in ether to its equivalent in wei, and **fromWei** does the opposite. The **parseEther** and **formatEther** methods from the **ethers.utils** the module is used for this conversion.


const sendEthers = async (recipientAddress, amountInWei) => {
  return new Promise(async (resolve, reject) => {
    const privateKey =
      '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80';
    const provider = new ethers.providers.JsonRpcProvider(
      'http://localhost:8545',
    );
    const wallet = new ethers.Wallet(privateKey, provider);
    const gasPrice = provider.getGasPrice();
    const nonce = provider.getTransactionCount(wallet.address, 'latest');
    const transaction = {
      to: recipientAddress,
      value: amountInWei,
      gasPrice,
      gasLimit: ethers.utils.hexlify(100000),
      nonce,
    };
    await wallet
      .sendTransaction(transaction)
      .then((transactionHash) => resolve(transactionHash))
      .catch((error) => reject(error));
  });
};


The **sendEthers** function is defined to send ethers from one wallet to another. It takes two parameters: **recipientAddress** and **amountInWei** which represent the address of the recipient and the amount to be sent, respectively.


A **privateKey** and a **provider** are created. The transaction is signed with the private key, and the provider communicates with the Ethereum network. Using the private key and the provider, a wallet instance is created.


The provider's getGasPrice and getTransactionCount methods are used to obtain the current gasPrice and nonce of the wallet, respectively. The gasPrice represents the cost of one unit of gas, and the nonce represents the number of transactions sent from the wallet.


A **transaction** object is created with the following parameters: **to** (recipientAddress), **value** (amountInWei), **gasPrice**, **gasLimit** (100000 in hex), and **nonce**. The **sendTransaction** method of the **wallet** instance is then used to send the transaction.


If the transaction is successful, the promise resolves with the transaction hash, otherwise it rejects with an error.


const getBalance = async (walletAddress) => {
  return new Promise(async (resolve, reject) => {
    const provider = new ethers.providers.JsonRpcProvider(
      'http://localhost:8545',
    )
    await provider
      .getBalance(walletAddress)
      .then((balanceInWei) => resolve(balanceInWei))
      .catch((error) => reject(error))
  })
}


The **getBalance** function returns a promise that resolves with the balance of a wallet in wei. The function creates a JsonRpcProvider object and calls the **getBalance** method on it.


The method takes the address of the wallet as an argument. The **getBalance** method returns a Promise that resolves with the balance of the wallet in wei. If an error occurs, the Promise is rejected with the error.


Check out the video below to learn how to code a blog smart contract in solidity. This will give you a head start on how to advance in Web3 development.


async function main() {
  // the rest of the codes goes in here
}


The **main** function is defined to perform the transfer of ethers.


;[sender, receiver] = await ethers.getSigners()
const amountInWei = toWei(4.7)

console.log('\n')
let balance = await getBalance(sender.address)
console.log('Sender balance before transfer: ', fromWei(balance))
balance = await getBalance(receiver.address)
console.log('Receiver balance before transfer: ', fromWei(balance))
console.log('\n')


The **ethers.getSigners** method is called to obtain the sender and receiver addresses. The amount to be sent is converted to wei using the **toWei** function.


The balance of the sender and receiver is logged before the transfer by calling the **getBalance** function twice and pass the addresses of the sender and receiver as arguments.


await sendEthers(receiver.address, amountInWei).then((data) =>
  console.log('Transaction Details: ', data),
)
console.log('\n')


The **sendEthers** function is called to initiate the transfer of ethers. The function takes the recipient's address and the amount in wei as arguments.


The **sendEthers** function returns a Promise that resolves with the transaction details. This Promise is logged into the console.


balance = await getBalance(sender.address)
console.log('Sender balance after transfer: ', fromWei(balance))
balance = await getBalance(receiver.address)
console.log('Receiver balance after transfer: ', fromWei(balance))
console.log('\n')


The balance of the sender and receiver is logged again to show that the transfer was successful. The **getBalance** function is called twice to obtain the balance of the sender and receiver after the transfer. The result is logged onto the console.

Conclusion

In conclusion, this tutorial has shown how to send Ethers programmatically without the need for Metamask.


The code provided demonstrates the use of the **ethers** library in JavaScript to interact with the Ethereum network and perform a programmatic transaction of ethers between accounts.


The code includes helper functions to convert between Ether and its smallest unit, Wei, as well as functions to send ethers and get the balance of a wallet.


The code also demonstrates the use of private keys, providers, wallets, gas prices, nonces, and transactions in Ethereum.


The article has provided a good foundation for understanding how to send Ethers programmatically and serves as a useful reference for those starting out in this area.


My  latest book


Obtain a copy of my book, "Capturing Smart Contract Development", to attain the skills and knowledge needed to be a sought-after smart contract developer.


Remember to sign up for my channel to see various web3 development videos. Take care until our next tutorial.

About the Author

Gospel Darlington is a full-stack blockchain developer with 6+ years of experience in the software development industry.


By combining Software Development, writing, and teaching, he demonstrates how to build decentralized applications on EVM-compatible blockchain networks.


For more information about him, kindly visit and follow his page on Twitter, Github, LinkedIn, or his website.


If you're passionate about Web3 development, make sure to subscribe to my channel for a variety of educational videos. If you'd like to connect with me, take a look at my services.