curl --request POST \
--url https://nd-828-700-214.p2pify.com/a9bca2f0f84b54086ceebe590316fff3 \
--header 'Content-Type: application/json' \
--data '
{
"id": 1,
"jsonrpc": "2.0",
"method": "eth_getTransactionCount",
"params": [
"0xe341b2f448eb190495ed4a89c01f20078b26b0f6",
"latest"
]
}
'{
"jsonrpc": "<string>",
"id": 123,
"result": {}
}curl --request POST \
--url https://nd-828-700-214.p2pify.com/a9bca2f0f84b54086ceebe590316fff3 \
--header 'Content-Type: application/json' \
--data '
{
"id": 1,
"jsonrpc": "2.0",
"method": "eth_getTransactionCount",
"params": [
"0xe341b2f448eb190495ed4a89c01f20078b26b0f6",
"latest"
]
}
'{
"jsonrpc": "<string>",
"id": 123,
"result": {}
}nonce; it is an important piece of information, especially to ensure that a transaction is not sent twice.
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 blockearliest — the earliest available or genesis blockpending — 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.quantity — an integer value identifying the number of transactions sent from an address at the specified block.eth_getTransactionCount code examplesconst 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("0xe341b2f448eb190495ed4a89c01f20078b26b0f6", 'latest')
eth_getTransactionCountis 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 and ethereumjs-tx.
const Web3 = require("web3");
const Tx = require("ethereumjs-tx").Transaction;
const NODE_URL = "CHAINSTACK_NODE_URL";
const web3 = new Web3(NODE_URL);
// Initialize private key
const PRIVATE_KEY = Buffer.from("PRIVATE_KEY", "hex");
// Validate input parameters and return an error message if invalid
const validateInputs = (fromAddress, toAddress) => {
if (!web3.utils.isAddress(fromAddress)) {
throw new Error(`Invalid fromAddress: ${fromAddress}`);
}
if (!web3.utils.isAddress(toAddress)) {
throw new Error(`Invalid toAddress: ${toAddress}`);
}
};
// Async function to create a raw transaction
async function createRawTransaction(fromAddress, toAddress, value) {
validateInputs(fromAddress, toAddress);
const nonce = await web3.eth.getTransactionCount(fromAddress);
const gasPrice = await web3.eth.getGasPrice();
const gasLimit = await web3.eth.estimateGas({
from: fromAddress,
to: toAddress,
});
// Build the transaction object
const transactionObject = {
to: toAddress,
gasPrice: web3.utils.toHex(gasPrice),
gasLimit: web3.utils.toHex(gasLimit),
nonce: web3.utils.toHex(nonce),
value: web3.utils.toHex(value),
};
// Create a new transaction object to sign
const tx = new Tx(transactionObject, { chain: 'mainnet' });
// Sign the transaction using the private key
tx.sign(PRIVATE_KEY);
// Serialize and return the signed transaction as a raw transaction
const serializedTx = tx.serialize();
const rawTransaction = `0x${serializedTx.toString('hex')}`;
return rawTransaction;
}
async function main() {
const rawTransaction = await createRawTransaction('0x6f46cf5569aefa1acc1009290c8e043747172d89', "0xe341b2f448eb190495ed4a89c01f20078b26b0f6" , "100000000000000")
console.log(`Raw transaction: ${rawTransaction}`)
}
main()
nonce, gasPrice, and gasLimit, builds a transaction object and signs it using a private key.
First, the createRawTransaction function calls validateInputs to ensure that the fromAddress and toAddress parameters are valid addresses. If either of these addresses is invalid, the function throws an error with a descriptive message.
Next, the function makes a call to web3.eth.getTransactionCount with the fromAddress as a parameter. This method returns the number of transactions sent from the fromAddress, and is used as the nonce for the transaction.
The function retrieves the gasPrice and gasLimit for the transaction using web3.eth.getGasPrice and web3.eth.estimateGas, respectively. The eth_gasPrice | Polygon is the amount of gas that the transaction sender is willing to pay per unit of gas consumed by the transaction, while the eth_estimateGas | Polygon is an estimate of the maximum amount of gas that the transaction will consume.
With the nonce, gasPrice, and gasLimit values, the function builds a transaction object, which includes the toAddress, gasPrice, gasLimit, nonce, and value of the transaction. The value is the amount transferred from the fromAddress to the toAddress.
The transaction object is then passed to a new Tx instance, which is signed using the private key. The signed transaction is then serialized and returned as a rawTransaction, which can be broadcasted to the network to execute the transaction using eth_sendRawTransaction | Polygon.Was this page helpful?