3

If I a have a Connection object from web3js, is there a way I can determine from this if it is operating on mainnet or devnet (or some local network)? The only thing in this direction I could think of was to check it's rpcEndpoint property against some known rpc urls for which I know if they are on mainnet or devnet. This is not portable and breaks as soon as someone uses a different endpoint I don't have saved. Is there a general solution for this?

Edit: I'm basically looking for a reverse clusterApiUrl method

1 Answer 1

3

You could check if the rpcEndpoint includes the words mainnet-beta, devnet or testnet

Apart from that you could make a simple function that checks cluster nodes albeit it's a bit hacky

async function checkCluster(connection: Connection) {
  const mainnet = new Connection(clusterApiUrl('mainnet-beta'),"singleGossip");
  const devnet = new Connection(clusterApiUrl('devnet'),"singleGossip");
  const testnet = new Connection(clusterApiUrl('testnet'),"singleGossip");
 
 let nodes = await connection.getClusterNodes();
  switch (nodes[0].pubkey) {
    case (await mainnet.getClusterNodes())[0].pubkey:
      return "mainnet-beta"
    case (await devnet.getClusterNodes())[0].pubkey:
      return "devnet"
    case (await testnet.getClusterNodes())[0].pubkey:
      return "testnet"
    default:
      console.log("unknown error")
      return null;
  }
}

Checkout the code

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.