5

This is a follow-up to this question. The accepted answer says:

Yes, contracts have nonces. A nonce of a contract is only incremented when that contract creates another contract [...]. When a contract invokes a function on another contract, a so called "internal transaction" (in http://live.ether.camp), the nonce is not incremented.

The nonce can be obtained by using web3.eth.getTransactionCount.

So far, so good. But when I use web3.eth.getTransactionCount with a recently deployed contract, the value is 1, not 0, despite that contract not having created any other contract.

Why is that happening?

Franco Victorio
  • 2,862
  • 17
  • 27

2 Answers2

6

From https://github.com/ethereum/EIPs/blob/master/EIPS/eip-161.md:

a. Account creation transactions and the CREATE operation SHALL, prior to the execution of the initialisation code, increment the nonce over and above its normal starting value by one (for normal networks, this will be simply 1, however test-nets with non-zero default starting nonces will be different).

This is a fairly recent change, which explains why you can find older contracts with a nonce of 0.

As to the why, my (limited) understanding is that it's an attempt to make sure that "empty" accounts and "non-existent" accounts are the same (zero nonce, zero balance, and empty code), which allows for clean-up of empty accounts.

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

@smarx found the answer with EIP 161.

Before EIP 161 contract nonces do start at 0. You are probably passing in your address instead of the contract's address to web3.eth.getTransactionCount (or the contract you passed in did create another contract).

Here's an example of a contract that has a nonce of 0.

> web3.eth.getTransactionCount('0xab7c74abc0c4d48d1bdad5dcb26153fc8780f83e')
0
eth
  • 85,679
  • 53
  • 285
  • 406
  • See this gist: https://gist.github.com/fvictorio/bc5e0fa302f0812a99f680d7564c7e1e (using web3 1.0). Maybe I'm doing something wrong, but it prints "1". I tested it with ganache-cli. – Franco Victorio Nov 28 '17 at 17:04
  • 1
    Thanks for your question and @smarx for answering, and I've updated the answer to https://ethereum.stackexchange.com/questions/764/do-contracts-also-have-a-nonce – eth Dec 05 '17 at 07:01