Is it possible to detect from the smart contract in solidity if it runs on mainnet or testnet? Or if it runs on ganache?

Maybe by getting the network ID? But I'm not sure it's possible from the smart contract itself.


You can use the CHAINID opcode to get the current chain ID. AFAIK, Solidity does not have a built-in function for this, but you can use inline assembly to get the chain ID in a Solidity contract, e.g.:

function getChainId() private view returns (uint256 chainId) {
  assembly {
    chainId := chainid()

Then you can check if the chain ID is 1 for mainnet, or another value for the testnet you are using. Make sure that you configure Ganache to not use chain ID 1.

  • Perfect, very useful ! So chainID is the only difference I can detect between a ganache simulation or testnet vs mainnet? – cazoute Apr 13 at 19:25
  • I don't know if it's the only way, but it's certainly an easy way to accomplish that. – Morten Apr 13 at 23:09

If you are running the smart comtract in truffle, you will have a migrations file and a config file. The config file will have different networks that you configure. In the 2nd migrations file that you create yourself, you can log the current network being used. Something like this

module.exports=function(deployer,network){ console.log(network); deployer.deploy(your_conract); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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