4

I'm using a javascript library (etheremjs) to sign a transaction. When creating it, it asks for the nonce field. I researched about it and partially understood it. But my main problem is:

How do I actually get it? Is the nonce a lifetime transaction number of that wallet or just a number for a set of transactions in a period of time? Does it start at 0 or 1? Is it public? How can I know what nonce I should use for a new transaction?

sigmaxf
  • 1,080
  • 2
  • 13
  • 21

2 Answers2

5

The nonce in the main ethereum network starts at 0 for each account and increases each time a transaction originates from that account.

You can just count the outbound transactions on etherscan.io, or you can call eth_getTransactionCount (or web3.eth.getTransactionCount if you're using that) on any node. Here's a way to do it via Etherscan's API:

https://api.etherscan.io/api?module=proxy&action=eth_getTransactionCount&address=0xYourAddressHere&tag=latest&apikey=YourApiKeyToken

The result is the number of outbound transactions that have happened so far, and thus also the correct nonce to use for the next transaction.

user19510
  • 27,999
  • 2
  • 30
  • 48
1

In case you are using ethers.js you can fetch it through the provider as below:

import { ethers } from "ethers";
const { ethereum } = window;

const provider = new ethers.providers.Web3Provider(ethereum); const signer = provider?.getSigner(); const contract = new ethers.Contract( CONTRACT_ADDRESS, CONTRACT_ABI, signer ); const nonce = await provider.getTransactionCount(contract.address);

const tx = await contract.methodName(param1, param2, { gasLimit:gasLimit, gasPrice:gasPrice, value: ethers.utils.parseEther("0.01"), nonce:nonce, });

Step 2: Reset your Metamask account.

Sometimes the issue is with your metamask account and needs to be reset to get the correct customer nonce value.

To reset your account:

Click Metamask Icon > Advanced Setting > Reset Account

enter image description here