After the deployment of the contract, let's say MyContract, can we literally count how many times MyContract has been instantiated?

Here's the code of MyContract:

contract MyContract {
  uint public counter = 0;

  function MyContract() public {

After the deployment, which I used truffle deploy, I do the following code to instantiate a new MyContract instance, inside truffle console:

          .then(function(c){return c.counter.call()})

I expected every time I execute this line, I will have an increment on the counter, which looks like 1,2,3,4,... by steps.

But I keep on receive 1 as the result, without any changes. Thanks for any help.

2 Answers 2


You are creating a new contract instance every time. There is no way for each contract instance to be aware of how many other ones have been created, so the value will always be 1.

What you want to do is have a parent contract which is able to create the child contract that you would like to count. Here is some sample code:

contract Parent {
    uint counter;

    function createChild() {
        Child child = new Child();

And the Child contract could be anything you want. I think this answers your question.


Each time you instantiate/deploy your contract it is a new contract with new storage, so it is correctly reporting that it it has been created once. Each contract has its own independent version of counter.

You could have a single Counter contract that each of the contracts you deploy calls as it is created. That would be able to maintain a single counter that increments each time. I don't know how you could protect that from being called by any third-party, though, and messing up your count.

Or, perhaps best, you should make a "Factory" contract that only takes instruction from your own account. When you call it, it deploys your contract itself and keeps count for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.