1

Ropsten, Mainnet, or Ganache for example.

1

Use the JSON-RPC method net_version

See https://github.com/ethereum/wiki/wiki/JSON-RPC#net_version

Returns string of the current network id.

"1": Ethereum Mainnet
"2": Morden Testnet (deprecated)
"3": Ropsten Testnet
"4": Rinkeby Testnet
"42": Kovan Testnet

Web3 exposes these methods: https://github.com/ethereum/wiki/wiki/JavaScript-API#web3versionnetwork


Or to invoke the request manually:

    // The ganache GUI I have running returns "5777".
    // My embedded testRPC version returns whatever network ID is 
    // specified in truffle.js config, such as "*"
    let networkID = (await this.promisify(web3.currentProvider.sendAsync, {
        jsonrpc: "2.0",
        method: "net_version",
        params: [],
        id: 0
    })).result;

    // Both ganache and my embedded testRPC version return "63"
    let protocolVersion = (await this.promisify(web3.currentProvider.sendAsync, {
        jsonrpc: "2.0",
        method: "eth_protocolVersion",
        params: [],
        id: 0
    })).result;
0

If you are looking to know which truffle network key from the truffle.js was selected you can use the truffle object deployer which is passed as the first argument on the migration files ($ROOT/migrations/*.js), then add the value to the process.env, as in the following example:

/migration/1_initial_migration.js

const Migrations = artifacts.require("./Migrations.sol");

module.exports = (deployer) => {
  process.env.NETWORK = deployer.network; // Network Id, for instance "ganache"

  deployer.deploy(Migrations).then(() => {
    console.log("Deployment of `Migrations.sol` completed");
  });
};

/test/01_test.js

describe('Test', () => {
  let NETWORK = process.env.NETWORK;

  ...
  it("should ...", async () => {
  ....

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.