hardhat/types#HardhatRuntimeEnvironment TypeScript Examples

The following examples show how to use hardhat/types#HardhatRuntimeEnvironment. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts    From eth with GNU General Public License v3.0 7 votes vote down vote up
async function assertChainId({}, hre: HardhatRuntimeEnvironment) {
  const { NETWORK_ID } = hre.contracts;

  if (hre.network.config.chainId !== NETWORK_ID) {
    throw new Error(
      `Hardhat defined network chain id ${hre.network.config.chainId} is NOT same as contracts network id: ${NETWORK_ID}.`
    );
  }
}
Example #2
Source File: admin.ts    From openzeppelin-upgrades with MIT License 6 votes vote down vote up
export function makeChangeProxyAdmin(hre: HardhatRuntimeEnvironment): ChangeAdminFunction {
  return async function changeProxyAdmin(proxyAddress, newAdmin) {
    const admin = await getManifestAdmin(hre);
    const proxyAdminAddress = await getAdminAddress(hre.network.provider, proxyAddress);

    if (admin.address !== proxyAdminAddress) {
      throw new Error('Proxy admin is not the one registered in the network manifest');
    } else if (admin.address !== newAdmin) {
      await admin.changeProxyAdmin(proxyAddress, newAdmin);
    }
  };
}
Example #3
Source File: index.ts    From hardhat-tenderly with GNU General Public License v3.0 6 votes vote down vote up
populateNetworks = (env: HardhatRuntimeEnvironment): void => {
  TenderlyService.getPublicNetworks()
    .then(networks => {
      let network: TenderlyPublicNetwork;
      let slug: string;
      for (network of networks) {
        NetworkMap[network.slug] = network.ethereum_network_id;
        
        if (network?.metadata?.slug) {
          NetworkMap[network.metadata.slug] = network.ethereum_network_id;
        }

        ReverseNetworkMap[network.ethereum_network_id] = network.slug;

        for (slug of network.metadata.secondary_slugs) {
          NetworkMap[slug] = network.ethereum_network_id;
        }
      }
    })
    .catch(e => {
      console.log("Error encountered while fetching public networks");
    });
}
Example #4
Source File: helperFunctions.ts    From aavegotchi-contracts with MIT License 6 votes vote down vote up
export async function getDiamondSigner(
  hre: HardhatRuntimeEnvironment,
  override?: string,
  useLedger?: boolean
) {
  //Instantiate the Signer
  let signer: Signer;
  const owner = await (
    (await hre.ethers.getContractAt(
      "OwnershipFacet",
      maticDiamondAddress
    )) as OwnershipFacet
  ).owner();
  const testing = ["hardhat", "localhost"].includes(hre.network.name);

  if (testing) {
    await hre.network.provider.request({
      method: "hardhat_impersonateAccount",
      params: [override ? override : owner],
    });
    return await hre.ethers.getSigner(override ? override : owner);
  } else if (hre.network.name === "matic") {
    return (await hre.ethers.getSigners())[0];
  } else {
    throw Error("Incorrect network selected");
  }
}
Example #5
Source File: deployReceiptToken.ts    From ghst-staking with MIT License 6 votes vote down vote up
task(
  "deployReceiptToken",
  "Deploys a new receipt token to be used for GHST Staking Pool"
)
  .addParam("name", "Token name")
  .addParam("symbol", "Token symbol")
  .setAction(
    async (
      taskArgs: DeployReceiptTokenTaskArgs,
      hre: HardhatRuntimeEnvironment
    ) => {
      const receiptTokenFactory = (await hre.ethers.getContractFactory(
        "ReceiptToken"
      )) as ReceiptToken__factory;
      const token = (await receiptTokenFactory.deploy(
        maticStakingAddress,
        taskArgs.name,
        taskArgs.symbol
      )) as ReceiptToken;
      await token.deployed();

      if (taskArgs.symbol.slice(0, 3) !== "stk") {
        console.log("sym:", taskArgs.symbol.slice(0, 3));
        throw new Error("Receipt token symbol must be prefixed with 'stk'");
      }

      const address = token.address;

      const minter = await token.minter();
      if (minter !== maticStakingAddress) {
        throw new Error("Minter is not staking address!");
      } else {
        console.log(
          `Receipt token with name ${taskArgs.name} and symbol ${taskArgs.symbol} has been deployed to ${address}`
        );
      }
      return address;
    }
  );
Example #6
Source File: hardhat.config.ts    From balancer-v2-monorepo with GNU General Public License v3.0 6 votes vote down vote up
task('deploy', 'Run deployment task')
  .addParam('id', 'Deployment task ID')
  .addFlag('force', 'Ignore previous deployments')
  .addOptionalParam('key', 'Etherscan API key to verify contracts')
  .setAction(
    async (args: { id: string; force?: boolean; key?: string; verbose?: boolean }, hre: HardhatRuntimeEnvironment) => {
      Logger.setDefaults(false, args.verbose || false);

      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const apiKey = args.key ?? (hre.config.networks[hre.network.name] as any).verificationAPIKey;
      const verifier = apiKey ? new Verifier(hre.network, apiKey) : undefined;
      await new Task(args.id, TaskMode.LIVE, hre.network.name, verifier).run(args);
    }
  );
Example #7
Source File: hardhat.config.ts    From eth with GNU General Public License v3.0 6 votes vote down vote up
extendEnvironment((env: HardhatRuntimeEnvironment) => {
  env.DEPLOYER_MNEMONIC = DEPLOYER_MNEMONIC;
  // cant easily lookup deployer.address here so well have to be ok with undefined and check it later
  env.ADMIN_PUBLIC_ADDRESS = ADMIN_PUBLIC_ADDRESS;

  env.packageDirs = packageDirs;

  env.contracts = lazyObject(() => {
    const contracts = require('@darkforest_eth/contracts');
    return settings.parse(decodeContracts, contracts);
  });

  env.initializers = lazyObject(() => {
    const { initializers = {} } = settings.load(env.network.name);
    return settings.parse(decodeInitializers, initializers);
  });

  env.adminPlanets = lazyObject(() => {
    const { planets = [] } = settings.load(env.network.name);
    return settings.parse(decodeAdminPlanets, planets);
  });
});
Example #8
Source File: singleton-deployment.ts    From zodiac with GNU Lesser General Public License v3.0 6 votes vote down vote up
deployFactory = async (_: null, hardhat: HardhatRuntimeEnvironment) => {
    const factory = await hardhat.ethers.getContractFactory("ModuleProxyFactory")
    const singletonFactory = new hardhat.ethers.Contract(singletonFactoryAddress, singletonFactoryAbi)
    const encodedData = singletonFactory.interface.encodeFunctionData(
        'deploy(bytes memory _initCode, bytes32 _salt)',
        [
            factory.bytecode,
            factorySalt
        ]
    )
    const [deployer] = await hardhat.ethers.getSigners()

    const transactionResponse = await deployer.sendTransaction({
        to: singletonFactoryAddress,
        from: deployer.address,
        data: encodedData,
        gasLimit: 894_693
    })

    console.log("Mining transaction....")
    const result = await transactionResponse.wait(3)
    console.log(`Transaction with hash ${result.transactionHash} mined`)
}
Example #9
Source File: 01_ERC1820Registry.ts    From hoprnet with GNU General Public License v3.0 6 votes vote down vote up
main = async function (hre: HardhatRuntimeEnvironment, signer?: Signer) {
  const { ethers, getNamedAccounts } = hre
  const deployer = signer || (await getNamedAccounts().then((o) => ethers.getSigner(o.deployer)))

  // check if it already exists
  if ((await ethers.provider.getCode(ERC1820_REGISTRY_ADDRESS)).length > '0x'.length) {
    console.log('ERC1820 registry already exists')
    return
  }

  // 0.08 ether is needed to deploy the registry, and those funds need to be transferred to the account that will deploy
  // the contract.
  await deployer.sendTransaction({
    to: ERC1820_DEPLOYER,
    value: ethers.utils.parseEther('0.08')
  })

  // deploy
  await ethers.provider.sendTransaction(ERC1820_REGISTRY_DEPLOY_TX)

  console.log(`"ERC1820Registry" deployed at ${ERC1820_REGISTRY_ADDRESS}`)
}
Example #10
Source File: 0099_Deploy_TestNFT.ts    From swap.kiwi with GNU General Public License v3.0 6 votes vote down vote up
deployFunc: DeployFunction = async function (hre: HardhatRuntimeEnvironment) {
  const {deployments, getNamedAccounts} = hre;
  const {deploy} = deployments;
  const {deployer} = await getNamedAccounts();

  await deploy("TestERC721", {from: deployer});
  await deploy("TestERC1155", {from: deployer});
  await deploy("SwapParticipant", {from: deployer});
}
Example #11
Source File: helpers.ts    From hardhat-etherscan-abi with MIT License 6 votes vote down vote up
export async function getVerifiedContractAt(
  hre: HardhatRuntimeEnvironment,
  address: string,
  signer?: ethers.Signer
): Promise<ethers.Contract> {
  const { isAddress } = await import("@ethersproject/address");
  if (!isAddress(address)) {
    throw new NomicLabsHardhatPluginError(
      pluginName,
      `${address} is an invalid address.`
    );
  }

  const request = toGetAbiRequest({
    // @ts-ignore
    apiKey: hre.config.etherscan.apiKey,
    address,
  });
  const endpoint = await getEtherscanEndpoints(hre.network.provider, hre.network.name);
  const abi = await getAbi(endpoint.apiURL, request);

  return hre.ethers.getContractAt(abi, address, signer);
}
Example #12
Source File: index.ts    From hardhat-circom with GNU General Public License v3.0 6 votes vote down vote up
async function circomTemplate({ zkeys }: { zkeys: ZkeyFastFile[] }, hre: HardhatRuntimeEnvironment) {
  const warning = "// THIS FILE IS GENERATED BY HARDHAT-CIRCOM. DO NOT EDIT THIS FILE.\n";

  const snarkjsRoot = path.dirname(require.resolve("snarkjs"));
  const templateDir = existsSync(path.join(snarkjsRoot, "templates")) ? "templates" : "../templates";

  const verifierGroth16TemplatePath = path.join(snarkjsRoot, templateDir, "verifier_groth16.sol.ejs");
  const verifierPlonkTemplatePath = path.join(snarkjsRoot, templateDir, "verifier_plonk.sol.ejs");

  const groth16Template = await fs.readFile(verifierGroth16TemplatePath, "utf8");
  const plonkTemplate = await fs.readFile(verifierPlonkTemplatePath, "utf8");
  for (const zkey of zkeys) {
    const circuitSol = await snarkjs.zKey.exportSolidityVerifier(zkey, {
      groth16: groth16Template,
      plonk: plonkTemplate,
    });

    const finalSol = warning + circuitSol;

    const name = camelcase(zkey.name, {
      pascalCase: true,
      preserveConsecutiveUppercase: true,
      locale: false,
    });

    const verifier = path.join(hre.config.paths.sources, `${name}Verifier.sol`);

    await fs.mkdir(path.dirname(verifier), { recursive: true });

    await fs.writeFile(verifier, finalSol);
  }
}
Example #13
Source File: deploymentUtils.ts    From gateway-sol with GNU General Public License v3.0 6 votes vote down vote up
setupGetExistingDeployment =
    (hre: HardhatRuntimeEnvironment) =>
    async <T extends BaseContract>(name: string): Promise<T | null> => {
        const { deployments, getNamedAccounts, ethers, network } = hre;
        const { getOrNull } = deployments;

        if (network.name === "hardhat") {
            return null;
        }

        const { deployer } = await getNamedAccounts();
        const result = await getOrNull(name);

        return result ? await ethers.getContractAt<T>(name, result.address, deployer) : result;
    }
Example #14
Source File: Greeter.ts    From hardhat-foundation with MIT License 6 votes vote down vote up
func: DeployFunction = async function ({
  getNamedAccounts,
  deployments,
}: HardhatRuntimeEnvironment) {
  const { deploy } = deployments;

  const { deployer } = await getNamedAccounts();

  const { address } = await deploy("Greeter", {
    from: deployer,
    args: ["Hello, world!"],
  });

  console.log(`Greeter deployed to ${address}`);
}
Example #15
Source File: BentoBox.ts    From trident with GNU General Public License v3.0 6 votes vote down vote up
deployFunction: DeployFunction = async function ({
  ethers,
  deployments,
  getNamedAccounts,
  getChainId,
}: HardhatRuntimeEnvironment) {
  const { deploy } = deployments;

  const { deployer } = await getNamedAccounts();

  const weth9 = await ethers.getContract<WETH9>("WETH9");

  await deploy("BentoBoxV1", {
    from: deployer,
    args: [weth9.address],
    deterministicDeployment: false,
  });
}
Example #16
Source File: index.ts    From hardhat-deploy with MIT License 6 votes vote down vote up
function createNetworkFromConfig(
  env: HardhatRuntimeEnvironment,
  networkName: string,
  config: NetworkConfig
): Network {
  const tags: {[tag: string]: boolean} = {};
  const tagsCollected = config.tags || [];
  for (const tag of tagsCollected) {
    tags[tag] = true;
  }

  const network = {
    name: networkName,
    config,
    live: config.live,
    saveDeployments: config.saveDeployments,
    zksync: config.zksync,
    tags,
    deploy: config.deploy || env.config.paths.deploy,
    companionNetworks: {},
  };
  networkFromConfig(env, network as Network, false);
  return network as Network;
}
Example #17
Source File: 000_admin_for_greeter.ts    From hardhat-deploy-ts-test with MIT License 6 votes vote down vote up
func: DeployFunction = async function (hre: HardhatRuntimeEnvironment) {
  const {deployments, getNamedAccounts} = hre;
  const {execute, log, read} = deployments;
  const {deployer, admin} = await getNamedAccounts();

  const currentAdmin = await read('Greeter', 'getAdmin');
  if (currentAdmin !== admin) {
    log(`setting admin from ${currentAdmin} to ${admin}...`);
    await execute(
      'Greeter',
      {from: currentAdmin, log: true},
      'setAdmin',
      admin
    );
    log(`admin set to ${admin}`);
  }
}
Example #18
Source File: proposing.ts    From safe-tasks with GNU Lesser General Public License v3.0 5 votes vote down vote up
parseMultiSendJsonFile = async (hre: HardhatRuntimeEnvironment, txs: MetaTransaction[], nonce: number, multiSendAddress?: string): Promise<SafeTransaction> => {
    if (txs.length == 1) {
        return buildSafeTransaction({ ...txs[0], nonce: nonce })
    }
    const multiSend = await multiSendLib(hre, multiSendAddress)
    return buildMultiSendSafeTx(multiSend, txs, nonce)
}
Example #19
Source File: cli.ts    From openzeppelin-transpiler with MIT License 5 votes vote down vote up
async function getPaths() {
  const hardhat = require.resolve('hardhat', { paths: [process.cwd()] });
  const hre: HardhatRuntimeEnvironment = await import(hardhat);
  return hre.config.paths;
}
Example #20
Source File: propose-upgrade.ts    From openzeppelin-upgrades with MIT License 5 votes vote down vote up
export function makeProposeUpgrade(hre: HardhatRuntimeEnvironment): ProposeUpgradeFunction {
  return async function proposeUpgrade(proxyAddress, ImplFactory, opts = {}) {
    if (!hre.config.defender) {
      throw new Error(`Missing Defender API key and secret in hardhat config`);
    }
    const client = new AdminClient(hre.config.defender);

    const chainId = await getChainId(hre.network.provider);
    const network = fromChainId(chainId);
    if (network === undefined) {
      throw new Error(`Network ${chainId} is not supported in Defender Admin`);
    }

    const { title, description, proxyAdmin, multisig, multisigType, ...moreOpts } = opts;

    if (await isBeaconProxy(hre.network.provider, proxyAddress)) {
      throw new Error(`Beacon proxy is not currently supported with defender.proposeUpgrade()`);
    } else if (await isBeacon(hre.network.provider, proxyAddress)) {
      throw new Error(`Beacon is not currently supported with defender.proposeUpgrade()`);
    } else if (
      !multisig &&
      (await isTransparentOrUUPSProxy(hre.network.provider, proxyAddress)) &&
      !(await isTransparentProxy(hre.network.provider, proxyAddress))
    ) {
      throw new Error(`Multisig address is a required property for UUPS proxies`);
    } else {
      // try getting the implementation address so that it will give an error if it's not a transparent/uups proxy
      await getImplementationAddress(hre.network.provider, proxyAddress);
    }

    const newImplementation = await hre.upgrades.prepareUpgrade(proxyAddress, ImplFactory, moreOpts);
    const contract = { address: proxyAddress, network, abi: ImplFactory.interface.format(FormatTypes.json) as string };
    return client.proposeUpgrade(
      {
        newImplementation,
        title,
        description,
        proxyAdmin,
        via: multisig,
        viaType: multisigType,
      },
      contract,
    );
  };
}