Spring til hovedindholdet

Sending Transactions Using Web3

transactionsweb3.jsalchemy
Beginner
Elan Halpern
Alchemy docs(opens in a new tab)
4. november 2020
10 minute read minute read

This is a beginner friendly guide to sending Ethereum transactions using Web3. There are three main steps in order to send a transaction to the Ethereum blockchain: create, sign, and broadcast. We’ll go through all three, hopefully answering any questions you might have! In this tutorial, we'll be using Alchemy(opens in a new tab) to send our transactions to the Ethereum chain. You can create a free Alchemy account here(opens in a new tab).

NOTE: This guide is for signing your transactions on the backend for your app. If you want to integrate signing your transactions on the frontend, check out integrating Web3 with a browser provider(opens in a new tab).

The Basics

Like most blockchain developers when they first start, you might have done some research on how to send a transaction (something that should be pretty simple) and ran into a plethora of guides, each saying different things and leaving you a bit overwhelmed and confused. If you’re in that boat, don’t worry; we all were at some point! So, before we start, let’s get a few things straight:

1.Alchemy does not store your private keys

  • This means that Alchemy cannot sign and send transactions on your behalf. The reason for this is security purposes. Alchemy will never ask you to share your private key, and you should never share your private key with a hosted node (or anyone for that matter).
  • You can read from the blockchain using Alchemy’s core API, but to write to it you’ll need to use something else to sign your transactions before sending them through Alchemy (this is the same for any other node service).

2.What is a “signer”?

3.Why do I need to sign my transactions?

  • Every user that wants to send a transaction on the Ethereum network must sign the transaction (using their private key), in order to validate that the origin of the transaction is who it claims to be.
  • It is super important to protect this private key, since having access to it grants full control over your Ethereum account, allowing you (or anyone with access) to perform transactions on your behalf.

4.How do I protect my private key?

  • There are many ways to protect your private key and to use it to send off transactions. In this tutorial we will be using a .env file. However, you could also use a separate provider that stores private keys, use a keystore file, or other options.

5. What is the difference between eth_sendTransaction and eth_sendRawTransaction?

eth_sendTransaction and eth_sendRawTransaction are both Ethereum API functions which broadcast a transaction to the Ethereum network so it will be added to a future block. They differ in how they handle signing of the transactions.

When using web3, eth_sendRawTransaction is accessed by calling the function web3.eth.sendSignedTransaction(opens in a new tab).

This is what we will be using in this tutorial.

6.What is the web3 library?

Okay, now that we have a few of these questions out of the way, let’s move on to the tutorial. Feel free to ask questions anytime in the Alchemy discord(opens in a new tab)!

7. How to send secure, gas-optimized, and private transactions? {how-to-send-secure-gas-optimized-and-private-transactions}

NOTE: This guide requires an Alchemy account, an Ethereum address or MetaMask wallet, NodeJs, and npm installed. If not, follow these steps:

  1. Create a free Alchemy account(opens in a new tab)
  2. Create MetaMask account(opens in a new tab) (or get an Ethereum address)
  3. Follow these steps to install NodeJs and NPM(opens in a new tab)

Steps to Sending your Transaction

1.Create an Alchemy app on the Sepolia testnet

Navigate to your Alchemy Dashboard(opens in a new tab) and create a new app, choosing Sepolia (or any other testnet) for your network.

2.Request ETH from the Sepolia faucet

Follow the instructions on the Alchemy Sepolia faucet(opens in a new tab) to receive ETH. Make sure to include your Sepolia Ethereum address (from MetaMask) and not another network. After following the instructions, double-check that you’ve received the ETH in your wallet.

3. Create a new project directory and cdinto it

Create a new project directory from the command line (terminal for macs) and navigate into it:

1mkdir sendtx-example
2cd sendtx-example

4.Install Alchemy Web3 (or any web3 library)

Run the following command in your project directory to install Alchemy Web3(opens in a new tab):

Note, if you'd like to use the ethers.js library, follow the instructions here(opens in a new tab).

1npm install @alch/alchemy-web3

5.Install dotenv

We’ll use a .env file to safely store our API key and private key.

1npm install dotenv --save

6. Create the .envfile

Create a .env file in your project directory and add the following (replacing “your-api-url" and "your-private-key")

1API_URL = "your-api-url"
2PRIVATE_KEY = "your-private-key"
Don't commit .env! Please make sure never to share or expose your .env file with anyone, as you are compromising your secrets in doing so. If you are using version control, add your .env to a gitignore(opens in a new tab) file.

7. Create sendTx.jsfile

Great, now that we have our sensitive data protected in a .env file, let’s start coding. For our send transaction example, we’ll be sending ETH back to the Sepolia faucet.

Create a sendTx.js file, which is where we will configure and send our example transaction, and add the following lines of code to it:

1async function main() {
2 require('dotenv').config();
3 const { API_URL, PRIVATE_KEY } = process.env;
4 const { createAlchemyWeb3 } = require("@alch/alchemy-web3");
5 const web3 = createAlchemyWeb3(API_URL);
6 const myAddress = '0x610Ae88399fc1687FA7530Aac28eC2539c7d6d63' //TODO: replace this address with your own public address
7
8 const nonce = await web3.eth.getTransactionCount(myAddress, 'latest'); // nonce starts counting from 0
9
10 const transaction = {
11 'to': '0x31B98D14007bDEe637298086988A0bBd31184523', // faucet address to return eth
12 'value': 1000000000000000000, // 1 ETH
13 'gas': 30000,
14 'nonce': nonce,
15 // optional data field to send message or execute smart contract
16 };
17
18 const signedTx = await web3.eth.accounts.signTransaction(transaction, PRIVATE_KEY);
19
20 web3.eth.sendSignedTransaction(signedTx.rawTransaction, function(error, hash) {
21 if (!error) {
22 console.log("🎉 The hash of your transaction is: ", hash, "\n Check Alchemy's Mempool to view the status of your transaction!");
23 } else {
24 console.log("❗Something went wrong while submitting your transaction:", error)
25 }
26 });
27}
28
29main();
Vis alle

Be sure to replace the address on line 6 with your own public address.

Now, before we jump into running this code, let's talk about some of the components here.

A Note on data There are a two main types of transactions that can be sent in Ethereum.

8. Run the code using node sendTx.js

Navigate back to your terminal or command line and run:

1node sendTx.js

9.See your transaction in the Mempool

Open up the Mempool page(opens in a new tab) in your Alchemy dashboard and filter by the app you created to find your transaction. This is where we can watch our transaction transition from pending state to mined state (if successful) or dropped state if unsuccessful. Make sure to keep it on “All” so that you capture “mined”, “pending”, and “dropped” transactions. You can also search for your transaction by looking for transactions sent to address 0x31b98d14007bdee637298086988a0bbd31184523 .

To view the details of your transaction once you’ve found it, select the tx hash, which should take you to a view that looks like this:

Mempool watcher screenshot

From there you can view your transaction on Etherscan by clicking on the icon circled in red!

Yippieeee! You just sent your first Ethereum transaction using Alchemy 🎉

For feedback and suggestions about this guide, please message Elan on Alchemy’s Discord(opens in a new tab)!

Originally published at https://docs.alchemyapi.io/tutorials/sending-transactions-using-web3-and-alchemy(opens in a new tab)

Seneste redigering: @nhsz(opens in a new tab), 15. august 2023

Var denne vejledning nyttig?