2

Recently I found out that you can add smart-contracts to the genesis block (genesis.json) of your local ethereum network.

Since normally, when you add a smart-contract via a transaction, you can call the constructor, which can initialize the contract. I also know that the constructor is optional, so I assume when adding the byte-code of a contract to an address in the genesis block, there is no way to call the constructor anymore. Is this correct? If so, is there a way to initialize some variables (e.g. owner address) besides hardcoding them?

Thanks :)

1 Answer 1

0

Your're correct that there's no way to have a constructor run with contracts defined in the genesis.json. Though there is a way to set state in the contract at genesis time, and that's by using the storage parameter, similar to the code parameter. See the below sample, taken from this question.

{
  "alloc": {
    "0x0000000000000000000000000000000000000020": {
      "code": "606060405236156100c45760e060020a60003504631290948581146100...<truncated>...",
      "storage": {
        "0x0000000000000000000000000000000000000000000000000000000000000001": "0x02",
        "0x0000000000000000000000000000000000000000000000000000000000000002": "0x04",
        "0x29ecdbdf95c7f6ceec92d6150c697aa14abeb0f8595dd58d808842ea237d8494": "0x01",
        "0x6aa118c6537572d8b515a9f9154be55a3377a8de7991cd23bf6e5ceb368688e3": "0x01",
        ...
      }
    },
    "0xed9d02e382b34818e88b88a309c7fe71e65f419d": {
      "balance": "1000000000000000000000000000"
    },
    "0xca843569e3427144cead5e4d5999a3d0ccf92b8e": {
      "balance": "1000000000000000000000000000"
    },
    "0x0fbdc686b912d7722dc86510934589e0aaf3b55a": {
      "balance": "1000000000000000000000000000"
    },
    ...
   }
  },
  "coinbase": "0x0000000000000000000000000000000000000000",
  "config": {
    "homesteadBlock": 0
  },
  "difficulty": "0x0",
  "extraData": "0x",
  "gasLimit": "0x2FEFD800",
  "mixhash": "0x00000000000000000000000000000000000000647572616c65787365646c6578",
  "nonce": "0x0",
  "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "timestamp": "0x00"
}

The storage section allows you to set the state at indivudual storage slots in the contract. The difficulty of course is knowing which ones to set to what, but you can figure that out by examining either the constructor bytecode or by deploying your contract on a testnet and examining the storage slots the constructor allocates.

1
  • 1
    That was exactly what I was looking for. Thanks big time!
    – EvenDance
    Commented Jun 25, 2020 at 19:59

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.