Ethereum API method that returns the number of transactions sent from an address at the selected block. This value is also called nonce
; it is an important piece of information, especially to ensure that a transaction is not sent twice.
Get you own node endpoint today
Start for free and get your app to production levels immediately. No credit card required.
You can sign up with your GitHub, X, Google, or Microsoft account.
Parameters
-
address
— the address to retrieve the transaction count. -
quantity or tag
— the integer of a block encoded as hexadecimal or the string with:-
latest
— the most recent block in the blockchain and the current state of the blockchain at the most recent block. A chain reorganization is to be expected. -
safe
— the block that received justification from the beacon chain. Although this block could be involved in a chain reorganization, it would necessitate either a coordinated attack by the majority of validators or an instance of severe propagation latency. -
finalized
— the block accepted as canonical by more than 2/3 of the validators. A chain reorganization is extremely unlikely, and it would require at least 1/3 of the staked ETH to be burned. -
earliest
— the earliest available or genesis block -
pending
— the pending state and transactions block. The current state of transactions that have been broadcast to the network but have not yet been included in a block.See the default block parameter and How The Merge Impacts Ethereum’s Application Layer.
-
Response
quantity
— an integer value identifying the number of transactions sent from an address at the specified block.
eth_getTransactionCount
code examples
eth_getTransactionCount
code examplesLearn more about the
ChainstackProvider
inethers.js
: ethers ChainstackProvider Documentation.
const ethers = require("ethers");
// Create a ChainstackProvider instance for Ethereum mainnet
const chainstack = new ethers.ChainstackProvider("mainnet");
const getNonce = async (address, blockId) => {
const nonce = await chainstack.send("eth_getTransactionCount", [ // This value is returned in HEX
address,
blockId,
]);
// Convert hex to decimal
const nonceDecimal = parseInt(nonce, 16);
console.log(nonceDecimal);
};
getNonce("0xCb6Ed7E78d27FDff28127F9CbD61d861F09a2324", "latest");
const { Web3 } = require("web3");
const NODE_URL = "CHAINSTACK_NODE_URL";
const web3 = new Web3(NODE_URL);
async function getTransactionsCount(address, blockId) {
const count = await web3.eth.getTransactionCount(address, blockId)
console.log(count);
}
getTransactionsCount("0xCb6Ed7E78d27FDff28127F9CbD61d861F09a2324", 'latest')
from web3 import Web3
node_url = "CHAINSTACK_NODE_URL"
web3 = Web3(Web3.HTTPProvider(node_url))
print(web3.eth.get_transaction_count("0xCb6Ed7E78d27FDff28127F9CbD61d861F09a2324", "latest"))
Use case
One of the most common use cases for eth_getTransactionCount
is to create the transaction object built in a script designed to send a transaction. The nonce field is required, and it is retrieved using the eth_getTransactionCount
method.
The following code shows how to build a rawTransction
using web3.js.
Security notice
You need your private key to sign the transaction; never share your private key with anyone.
On a side note, the private key in this case must be imported with '0x' at the beginning of the string.
const { Web3 } = require("web3");
const NODE_URL = "CHAINSTACK_NODE_URL";
const web3 = new Web3(NODE_URL);
// Function to get the transaction count (nonce)
async function getTransactionsCount(address) {
return await web3.eth.getTransactionCount(address, 'latest');
}
// Function to perform the transaction
async function sendEther() {
try {
// Add your private key here (ideally from an environment variable)
const privateKey = "0xPRIVATE_KEY";
// Add the wallet to Web3
const wallet = web3.eth.accounts.wallet.add(privateKey);
// Retrieve the nonce for the sender's address
const nonce = await getTransactionsCount(wallet[0].address);
// Transaction parameters
const toAddress = '0xae2Fc483527B8EF99EB5D9B44875F005ba1FaE13'; // Replace with the receiver's address
const value = web3.utils.toWei('1', 'ether'); // Amount in ETH (e.g., 1 ETH)
console.log(`Sending ${web3.utils.fromWei(value, "ether")} ETH from ${wallet[0].address} to ${toAddress}...`)
// Send the transaction
const receipt = await web3.eth.sendTransaction({
from: wallet[0].address,
to: toAddress,
value: value,
nonce: nonce, // Include the nonce
// Optional: Specify gas and gasPrice if needed
});
console.log('Transaction receipt:', receipt);
} catch (error) {
console.error('Transaction failed:', error);
}
}
// Execute the function
sendEther();
The code sets up a direct transaction to be broadcast to the Ethereum network using Web3.js.
Initially, the script establishes a connection to an Ethereum node and sets up the Web3 instance. The key part of the transaction process involves retrieving the nonce
for the sender's address, which is done through the getTransactionsCount
function. This function calls web3.eth.getTransactionCount
, passing the sender's address and returning the count of transactions previously sent from this address. This count, used as the nonce
, is critical for ensuring the transaction's uniqueness and order in the blockchain.
After setting up the sender's wallet with a private key, the script defines the transaction parameters, including the toAddress
and the value
(amount of ETH to be transferred). The value
is defined in Wei and then converted to ETH for logging purposes.
The script then constructs a transaction object that includes essential fields such as from
, to
, value
, and nonce
. While gasPrice
and gasLimit
can be specified; they are optional in this script, as Web3.js will provide default values if they are not explicitly set.
The transaction is sent using web3.eth.sendTransaction
, which handles the transaction signing under the hood with the private key from the wallet. This approach simplifies the transaction creation and sending process, as the complex steps of manually creating, signing, and serializing the transaction are abstracted away by Web3.js. This will ultimately send a transaction using the eth_sendRawTransaction method.
Once the transaction is sent, a receipt is obtained and logged, providing details of the executed transaction. In case of any errors during the transaction process, these are caught and logged, aiding in troubleshooting and ensuring robust error handling.
The sendEther
function encapsulates the entire process, and its execution triggers the sending of the transaction, demonstrating a streamlined and efficient way to handle Ethereum transactions programmatically.
Use the eth_getTransactionCount
RPC method yourself
eth_getTransactionCount
RPC method yourself