'Connect ganache fork to metamask

Below is my code for the ganache local fork

const Web3 = require("web3");

const ganache = require("ganache-cli");
const options = {
  fork: `my infura key`,
  unlocked_accounts: ["0x6262998ced04146fa42253a5c0af90ca02dfd2a3"],
  account_keys_path: "keys.json",
  host: "127.0.0.1",
  port: 7545,
  seed: 1306,
};

const server = ganache.server(options);
const PORT = 7545;
server.listen(PORT, async (err, blockchain) => {
  if (err) throw err;

  console.log(`ganache listening on port ${PORT}`);
  const provider = server.provider;
  const web3 = new Web3(provider);
  const accounts = await web3.eth.getAccounts();
  console.log(accounts);
});

it gives me the output like this

$ npm run ganache

> [email protected] ganache
> node ganache

ganache listening on port 7545
[
  '0xCfc597a8793E0ca94FC8310482D9e11367cfCA24',
  '0x2AAc0eb300FA402730bCEd0B4C43a7Fe6BF6491e',
  '0xb6C3582AccD194Fd224F579042A9888F8051C6D9',
  '0x89f575343b90a41963E4bD8085c0AA9CcdF4B0D3',
  '0xf9F4b92B599F3A3163de316c35982b63F1536BC5',
  '0xc6E02a81a6A565Fe9c2C663FfE9e306C07F6F938',
  '0x3d5EE2e3989a07e2D365E145DA9dD14B071AE2B1',
  '0xEA1f26b4C53949889Bfac507E95814E8216793F7',
  '0x37ad9130eFBaAC6Cd0B1213e3c30484BE0aa9D5c',
  '0x9A49a0adaE0f5A0c170029dF4718A963e2Ebb329'
]

My problem is how can I connect following accounts to metamask? I can't find the private key.

My keys.json file is like this,

{"addresses":
{"0xcfc597a8793e0ca94fc8310482d9e11367cfca24":{"secretKey":{"type":"Buffer","data":[52,175,236,60,8,34,120,164,71,142,52,15,138,23,240,244,113,210,240,100,215,210,221,3,213,212,225,204,135,248,15,23]},.....


Solution 1:[1]

From https://www.npmjs.com/package/ganache-cli:

"account_keys_path": String - Specifies a file to save accounts and private keys to, for testing.

So based on your snippet

account_keys_path: "keys.json"

you'll find the private keys in the keys.json file.


Edit: The private key is stored as decimal values of each byte, you can convert them to hex string using the Buffer function toString():

const privKey = Buffer.from([52,175,236,60,8,34,120,164,71,142,52,15,138,23,240,244,113,210,240,100,215,210,221,3,213,212,225,204,135,248,15,23]);

// prints 0x34afec3c082278a4478e340f8a17f0f471d2f064d7d2dd03d5d4e1cc87f80f17
console.log('0x' + privKey.toString("hex"));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1