hardhat/config#task TypeScript Examples

The following examples show how to use hardhat/config#task. 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: creation.ts    From safe-tasks with GNU Lesser General Public License v3.0 6 votes vote down vote up
task("create", "Create a Safe")
    .addFlag("l2", "Should use version of the Safe contract that is more event heave")
    .addFlag("buildOnly", "Indicate whether this transaction should only be logged and not submitted on-chain")
    .addParam("signers", "Comma separated list of signer addresses (dafault is the address of linked account)", "", types.string, true)
    .addParam("threshold", "Threshold that should be used", 1, types.int, true)
    .addParam("fallback", "Fallback handler address", AddressZero, types.string, true)
    .addParam("nonce", "Nonce used with factory", new Date().getTime(), types.int, true)
    .addParam("singleton", "Set to overwrite which singleton address to use", "", types.string, true)
    .addParam("factory", "Set to overwrite which factory address to use", "", types.string, true)
    .setAction(async (taskArgs, hre) => {
        const singleton = taskArgs.l2 ? await safeL2Singleton(hre, taskArgs.singleton) : await safeSingleton(hre, taskArgs.singleton)
        const factory = await proxyFactory(hre, taskArgs.factory)
        const signers: string[] = taskArgs.signers ? parseSigners(taskArgs.signers) : [(await hre.getNamedAccounts()).deployer]
        const fallbackHandler = getAddress(taskArgs.fallback)
        const setupData = singleton.interface.encodeFunctionData(
            "setup",
            [signers, taskArgs.threshold, AddressZero, "0x", fallbackHandler, AddressZero, 0, AddressZero]
        )
        const predictedAddress = await calculateProxyAddress(factory, singleton.address, setupData, taskArgs.nonce)
        console.log(`Deploy Safe to ${predictedAddress}`)
        console.log(`Singleton: ${singleton.address}`)
        console.log(`Setup data: ${setupData}`)
        console.log(`Nonce: ${taskArgs.nonce}`)
        console.log(`To (factory): ${factory.address}`)
        console.log(`Data: ${factory.interface.encodeFunctionData("createProxyWithNonce", [singleton.address, setupData, taskArgs.nonce])}`)
        if (!taskArgs.buildOnly)
            await factory.createProxyWithNonce(singleton.address, setupData, taskArgs.nonce).then((tx: any) => tx.wait())
        // TODO verify deployment
    });
Example #2
Source File: hardhat.config.ts    From BarnBridge-Barn with Apache License 2.0 6 votes vote down vote up
// This is a sample Buidler task. To learn how to create your own go to
// https://buidler.dev/guides/create-task.html
task('accounts', 'Prints the list of accounts', async (args, hre) => {
    const accounts = await hre.ethers.getSigners();

    for (const account of accounts) {
        console.log(await account.getAddress());
    }
});
Example #3
Source File: calculate-new-index-position.ts    From index-rebalance-utils with Apache License 2.0 6 votes vote down vote up
task("calculate-new-index-position", "Calculates new rebalance details for an index")
  .addParam("index", "Index having new positions calculated")
  .addParam("rebalance", "Rebalance month")
  .setAction(async ({index, rebalance}, hre) => {
    const owner: Signer = (await hre.ethers.getSigners())[0];
    const deployHelper: DeployHelper = new DeployHelper(owner);

    const indexInfo: IndexInfo = indices[index];

    const setToken: SetToken = await deployHelper.setV2.getSetToken(indexInfo.address);

    const strategyConstants: StrategyObject = await createStrategyObject(
      setToken,
      indexInfo.strategyInfo,
      owner
    );

    const setTokenValue = calculateSetValue(strategyConstants);

    const rebalanceData: RebalanceSummary[] = await indexInfo.calculateAssetAllocation(
      setToken,
      strategyConstants,
      setTokenValue
    );

    const tradeOrder = createRebalanceSchedule(rebalanceData, strategyConstants);

    const report = await generateReports(
      rebalanceData,
      tradeOrder,
      strategyConstants,
      setToken,
      await deployHelper.setV2.getGeneralIndexModule(GENERAL_INDEX_MODULE)
    );

    writeToOutputs(report, indexInfo.path + rebalance);
  });
Example #4
Source File: index.ts    From hardhat-v3-deploy with MIT License 6 votes vote down vote up
task("deploy-uniswap", "Deploys Uniswap V3 contracts", async (args, hre) => {
  const [actor] = await hre.ethers.getSigners();
  const contracts = await UniswapV3Deployer.deploy(actor);

  const table = new Table({
    head: ["Contract", "Address"],
    style: { border: [] },
  });
  for (const item of Object.keys(contracts)) {
    table.push([item, contracts[item].address]);
  }
  console.info(table.toString());
});
Example #5
Source File: swap.ts    From hypervisor with The Unlicense 6 votes vote down vote up
task('run-swap', 'Run Swap contract swap function')
  .addParam('token', 'token which to swap for VISR')
  .addParam('path', 'path to use')
  .addOptionalParam('send', 'flag for sending recipient or not')
  .setAction(async (cliArgs, { ethers, run, network }) => {
    // compile

    const signer = (await ethers.getSigners())[0]
    const swapAddress = "0x92f8964e7e261f872Cf4AAE01C7d845333aeB4C7";
    
    const swap = await ethers.getContractAt(
      'Swap',
      swapAddress,
      signer,
    )

    const _token = ethers.utils.getAddress(cliArgs.token);
    const _path = cliArgs.path;
    const _send = cliArgs.send == 'false' ? false : true;

    await swap.swap(_token, _path, _send);

  });
Example #6
Source File: generateDiamondABI.ts    From aavegotchi-contracts with MIT License 6 votes vote down vote up
task(
  "diamondABI",
  "Generates ABI file for diamond, includes all ABIs of facets"
).setAction(async () => {
  let files = fs.readdirSync("." + basePath);
  let abi: AbiCoder[] = [];
  for (const file of files) {
    const jsonFile = file.replace("sol", "json");
    let json = fs.readFileSync(`./artifacts/${basePath}${file}/${jsonFile}`);
    json = JSON.parse(json);
    abi.push(...json.abi);
  }
  files = fs.readdirSync("." + libraryBasePath);
  for (const file of files) {
    const jsonFile = file.replace("sol", "json");
    let json = fs.readFileSync(
      `./artifacts/${libraryBasePath}${file}/${jsonFile}`
    );
    json = JSON.parse(json);
    abi.push(...json.abi);
  }
  files = fs.readdirSync("." + sharedLibraryBasePath);
  for (const file of files) {
    const jsonFile = file.replace("sol", "json");
    let json = fs.readFileSync(
      `./artifacts/${sharedLibraryBasePath}${file}/${jsonFile}`
    );
    json = JSON.parse(json);
    abi.push(...json.abi);
  }
  let finalAbi = JSON.stringify(abi);
  fs.writeFileSync("./diamondABI/diamond.json", finalAbi);
  console.log("ABI written to diamondABI/diamond.json");
});
Example #7
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 #8
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 #9
Source File: debug.ts    From eth with GNU General Public License v3.0 6 votes vote down vote up
// yarn workspace eth hardhat:dev debug:giveArtifact "0x27fd6eec1e1f3ce4a53b40d5813119d868f7b4e3" PhotoidCannon 5
task('debug:giveArtifact', 'gives the player some amount of a particular type of artifact')
  .addPositionalParam(
    'playerAddress',
    'the address of the player to give the artifacts',
    undefined,
    types.string
  )
  .addPositionalParam(
    'artifactType',
    'one of: [Monolith, Colossus, Spaceship, Pyramid, Wormhole, ' +
      'PlanetaryShield, PhotoidCannon, BloomFilter, BlackDomain]',
    undefined,
    types.string
  )
  .addPositionalParam('amount', 'the amount of this artifact to give', 1, types.int)
  .addPositionalParam('rarity', 'the rarity of the artifact to give', 1, types.int)
  .addPositionalParam('biome', 'the biome of the artifact to give', 1, types.int)
  .addPositionalParam(
    'discoveredOn',
    'the planet ID (decimal string) this was discovered on',
    '0',
    types.string
  )
  .setAction(giveArtifact);
Example #10
Source File: hardhat.config.ts    From hoprnet with GNU General Public License v3.0 6 votes vote down vote up
task<FaucetCLIOPts>('faucet', 'Faucets a local development HOPR node account with ETH and HOPR tokens', faucet)
  .addOptionalParam<string>('address', 'HoprToken address', undefined, types.string)
  .addOptionalParam<string>('amount', 'Amount of HOPR to fund', DEFAULT_FUND_AMOUNT, types.string)
  .addFlag('useLocalIdentities', `Fund all identities stored in identity directory`)
  .addOptionalParam<string>(
    'password',
    `Password to decrypt identities stored in identity directory`,
    undefined,
    types.string
  )
  .addOptionalParam<string>(
    'identityDirectory',
    `Overwrite default identity directory, default ['/tmp']`,
    DEFAULT_IDENTITY_DIRECTORY,
    types.string
  )
  .addOptionalParam<string>('identityPrefix', `only use identity files with prefix`, undefined, types.string)
Example #11
Source File: create-proposal.ts    From nouns-monorepo with GNU General Public License v3.0 6 votes vote down vote up
task('create-proposal', 'Create a governance proposal')
  .addOptionalParam(
    'nounsDaoProxy',
    'The `NounsDAOProxy` contract address',
    '0x610178dA211FEF7D417bC0e6FeD39F05609AD788',
    types.string,
  )
  .setAction(async ({ nounsDaoProxy }, { ethers }) => {
    const nounsDaoFactory = await ethers.getContractFactory('NounsDAOLogicV1');
    const nounsDao = nounsDaoFactory.attach(nounsDaoProxy);

    const [deployer] = await ethers.getSigners();
    const oneETH = utils.parseEther('1');

    const receipt = await (
      await nounsDao.propose(
        [deployer.address],
        [oneETH],
        [''],
        ['0x'],
        '# Test Proposal\n## This is a **test**.',
      )
    ).wait();
    if (!receipt.events?.length) {
      throw new Error('Failed to create proposal');
    }
    console.log('Proposal created');
  });
Example #12
Source File: hardhat.config.ts    From perpetual-protocol with GNU General Public License v3.0 6 votes vote down vote up
task(TASK_SIMULATE, "Execute migration on mainnet fork node")
    .addParam("fork", "The URL of the JSON-RPC server to fork from")
    .addPositionalParam("migrationPath", "Target migration")
    .setAction(async ({ fork: forkTarget, migrationPath }, hre) => {
        // TODO: better way to ensure not running on real network?
        if (hre.network.name !== "hardhat") {
            throw new Error(`You should only run this on the "hardhat" network`)
        }

        // reset "hardhat" network to fork from specified target
        await hre.network.provider.request({
            method: "hardhat_reset",
            params: [
                {
                    forking: {
                        jsonRpcUrl: forkTarget,
                        // blockNumber: 11095000,
                    },
                },
            ],
        })

        await hre.run(TASK_MIGRATE, { stage: "test", migrationPath })
    })
Example #13
Source File: hardhat.config.ts    From hardhat-foundation with MIT License 6 votes vote down vote up
// This is a sample Hardhat task. To learn how to create your own go to
// https://hardhat.org/guides/create-task.html
task("accounts", "Prints the list of accounts", async (args, { ethers }) => {
  const accounts = await ethers.getSigners();

  for (const account of accounts) {
    console.log(await account.address);
  }
});
Example #14
Source File: hardhat.config.ts    From shoyu with MIT License 6 votes vote down vote up
// This is a sample Hardhat task. To learn how to create your own go to
// https://hardhat.org/guides/create-task.html
task("accounts", "Prints the list of accounts", async (args, { ethers }) => {
    const accounts = await ethers.getSigners();

    for (const account of accounts) {
        console.log(await account.address);
    }
});
Example #15
Source File: hardhat.config.ts    From sushi-oracle with The Unlicense 6 votes vote down vote up
// This is a sample Hardhat task. To learn how to create your own go to
// https://hardhat.org/guides/create-task.html
task("accounts", "Prints the list of accounts", async (args, { ethers }) => {
  const accounts = await ethers.getSigners();

  for (const account of accounts) {
    console.log(await account.address);
  }
});
Example #16
Source File: accounts.ts    From trident with GNU General Public License v3.0 6 votes vote down vote up
// This is a sample Hardhat task. To learn how to create your own go to
// https://hardhat.org/guides/create-task.html
task("accounts", "Prints the list of signers", async (args, { ethers: { getSigners } }) => {
  const accounts = await getSigners();

  for (const account of accounts) {
    console.log(await account.address);
  }
});
Example #17
Source File: hardhat.config.ts    From nft-marketplace with European Union Public License 1.2 6 votes vote down vote up
// This is a sample Hardhat task. To learn how to create your own go to
// https://hardhat.org/guides/create-task.html
task('accounts', 'Prints the list of accounts', async (args, hre) => {
  const accounts = await hre.ethers.getSigners();

  for (const account of accounts) {
    console.log(await account.address);
  }
});
Example #18
Source File: index.ts    From hardhat-deploy with MIT License 6 votes vote down vote up
task(TASK_TEST, 'Runs mocha tests')
  .addFlag('deployFixture', 'run the global fixture before tests')
  .addFlag('noImpersonation', 'do not impersonate unknown accounts')
  .setAction(async (args, hre, runSuper) => {
    if (args.noImpersonation) {
      deploymentsManager.disableAutomaticImpersonation();
    }
    if (args.deployFixture || process.env.HARDHAT_DEPLOY_FIXTURE) {
      if (!args.noCompile) {
        await hre.run('compile');
      }
      await hre.deployments.fixture(undefined, {
        keepExistingDeployments: true, // by default reuse the existing deployments (useful for fork testing)
      });
      return runSuper({...args, noCompile: true});
    } else {
      return runSuper(args);
    }
  });
Example #19
Source File: creation.ts    From safe-tasks with GNU Lesser General Public License v3.0 5 votes vote down vote up
task("create-bulk", "Create multiple Safes from CSV")
    .addFlag("buildOnly", "Indicate whether this transaction should only be logged and not submitted on-chain")
    .addPositionalParam("csv", "CSV file with the information of the Safes that should be created", undefined, types.inputFile)
    .addParam("fallback", "Fallback handler address", undefined, types.string, true)
    .addParam("nonce", "Nonce used with factory", "0", types.string, true)
    .addParam("singleton", "Set to overwrite which singleton address to use", "", types.string, true)
    .addParam("factory", "Set to overwrite which factory address to use", "", types.string, true)
    .addFlag("l2", "Should use version of the Safe contract that is more event heave")
    .addParam("export", "If specified instead of executing the data will be exported as a json file for the transaction builder", undefined, types.string, true)
    .setAction(async (taskArgs, hre) => {
        const singleton = taskArgs.l2 ? await safeL2Singleton(hre, taskArgs.singleton) : await safeSingleton(hre, taskArgs.singleton)
        const factory = await proxyFactory(hre, taskArgs.factory)
        const fallbackHandler = await compatHandler(hre, taskArgs.fallback)

        const inputs: { threshold: string, signers: string, address: string }[] = await readCsv(taskArgs.csv)
        const encodedSetups: { data: string, signers: string[], threshold: string, expectedAddress?: string }[] = inputs.filter(entry => entry.signers.trim().length !== 0).map(entry => {
            const parsedThreshold = entry.threshold.split("/")[0]
            const expectedSignerCount = entry.threshold.split("/")[1]
            const parsedSigners = entry.signers.replace(/\n/g, ",").split(",")
            console.log({ parsedThreshold, expectedSignerCount, parsedSigners })
            if (expectedSignerCount && parseInt(expectedSignerCount) !== parsedSigners.length) throw Error(`Expected ${expectedSignerCount} Signers, got ${parsedSigners}`)
            return {
                data: singleton.interface.encodeFunctionData(
                    "setup",
                    [parsedSigners, parsedThreshold, AddressZero, "0x", fallbackHandler.address, AddressZero, 0, AddressZero]
                ),
                signers: parsedSigners,
                threshold: parsedThreshold,
                expectedAddress: entry.address
            }
        })
        const deploymentTxs: MetaTransaction[] = encodedSetups.map(setup => {
            const data = factory.interface.encodeFunctionData("createProxyWithNonce", [singleton.address, setup.data, taskArgs.nonce])
            return { to: factory.address, data, operation: 0, value: "0" }
        })
        const multiSend = await multiSendCallOnlyLib(hre)
        console.log(`Singleton: ${singleton.address}`)
        console.log(`Nonce: ${taskArgs.nonce}`)
        console.log(`Factory: ${factory.address}`)
        console.log(`Data: ${multiSend.interface.encodeFunctionData("multiSend", [encodeMultiSend(deploymentTxs)])}`)
        console.log(`Predicted Safes:`)
        for (const setupData of encodedSetups) {
            console.log(`   Signers:`, setupData.signers.join(","), `Treshold:`, setupData.threshold, "of", setupData.signers.length)
            const calculatedAddress = await calculateProxyAddress(factory, singleton.address, setupData.data, taskArgs.nonce)
            console.log(`   Address:`, calculatedAddress)
            if (setupData.expectedAddress && setupData.expectedAddress !== calculatedAddress)
                console.log(`      Unexpected Safe address! Expected ${setupData.expectedAddress}.`)
            const onChainCode = await hre.ethers.provider.getCode(calculatedAddress)
            if (onChainCode !== "0x")
                console.log(`      Safe already exists on this address.`)
            console.log()
        }

        if (taskArgs.export) {
            const chainId = (await hre.ethers.provider.getNetwork()).chainId.toString()
            await writeTxBuilderJson(taskArgs.export, chainId, deploymentTxs, "Batched Safe Creations")
        } else if (!taskArgs.buildOnly) {
            await multiSend.multiSend(encodeMultiSend(deploymentTxs)).then((tx: any) => tx.wait())
        }
        // TODO verify deployment
    });
Example #20
Source File: hardhat.config.ts    From BarnBridge-YieldFarming with Apache License 2.0 5 votes vote down vote up
task('accounts', 'Prints the list of accounts', async (_, { ethers }) => {
    const accounts = await ethers.getSigners()

    for (const account of accounts) {
        console.log(await account.getAddress())
    }
})
Example #21
Source File: validate-index-params.ts    From index-rebalance-utils with Apache License 2.0 5 votes vote down vote up
task("validate-index-params", "Validates on-chain params match generated params")
.addParam("index", "Index having new positions calculated")
.addParam("rebalance", "Rebalance month")
.setAction(async ({index, rebalance}, hre) => {
  const owner: Signer = (await hre.ethers.getSigners())[0];
  const deployHelper: DeployHelper = new DeployHelper(owner);

  const indexInfo: IndexInfo = indices[index];

  const setToken: SetToken = await deployHelper.setV2.getSetToken(indexInfo.address);
  const indexModule: GeneralIndexModule = await deployHelper.setV2.getGeneralIndexModule(GENERAL_INDEX_MODULE);

  const filepath = indexInfo.path + `${rebalance}.json`;
  const expectedParams: RebalanceReport = JSON.parse(fs.readFileSync(filepath, "utf8"));

  // const positionMultiplier: BigNumber = await setToken.positionMultiplier();

  // if (!positionMultiplier.eq(BigNumber.from(expectedParams.rebalanceParams.positionMultiplier))) {
  //   throw Error("Different position multiplier used!")
  // }

  await Promise.all(expectedParams.summary.map(async (obj, i) => {
    const address = indexInfo.strategyInfo[obj.asset].address;

    const info: any = await indexModule.executionInfo(setToken.address, address);

    // if (!BigNumber.from(obj.newUnit.hex).eq(info.targetUnit)) {
    //   throw Error(`Target unit for ${obj.asset} is wrong should be ${BigNumber.from(obj.newUnit.hex).toString()} instead of ${info.targetUnit}`);
    // }

    const scaledMaxTradeSize = preciseMul(indexInfo.strategyInfo[obj.asset].maxTradeSize, await getTokenDecimals(deployHelper, address));
    if (!scaledMaxTradeSize.eq(info.maxSize)) {
      throw Error(
        `Max trade size for ${obj.asset} is wrong should be ${indexInfo.strategyInfo[obj.asset].maxTradeSize.toString()} instead of ${info.maxSize}`
      );
    }

    if (indexInfo.strategyInfo[obj.asset].exchange != info.exchangeName) {
      throw Error(
        `Exchange for ${obj.asset} is wrong should be ${indexInfo.strategyInfo[obj.asset].exchange} instead of ${info.exchange}`
      );
    }

    if (!indexInfo.strategyInfo[obj.asset].coolOffPeriod.eq(info.coolOffPeriod)) {
      throw Error(
        `Cool off period for ${obj.asset} is wrong should be ${indexInfo.strategyInfo[obj.asset].coolOffPeriod.toString()} instead of ${info.coolOffPeriod}`
      );
    }
  }));
  console.log("All parameters verified!");
});
Example #22
Source File: compile.ts    From nova with GNU Affero General Public License v3.0 5 votes vote down vote up
task(TASK_COMPILE).setAction(async (args, hre: any, runSuper) => {
  // Don't run typechain for OVM because they will get included with the L1 types.
  if (hre.network.config.ovm) {
    return runSuper({ ...args, noTypechain: true });
  } else {
    return runSuper(args);
  }
});
Example #23
Source File: index.ts    From hardhat-tenderly with GNU General Public License v3.0 5 votes vote down vote up
task("tenderly:verify", "Verifies contracts on Tenderly")
  .addOptionalVariadicPositionalParam(
    "contracts",
    "Addresses and names of contracts that will be verified formatted ContractName=Address"
  )
  .setAction(verifyContract);
Example #24
Source File: hypervisor.ts    From hypervisor with The Unlicense 5 votes vote down vote up
task('deploy-hypervisor-factory', 'Deploy Hypervisor contract')
  .setAction(async (cliArgs, { ethers, run, network }) => {

    const args = {
      uniswapFactory: "0x1f98431c8ad98523631ae4a59f267346ea31f984",
    };

    console.log('Network')
    console.log('  ', network.name)
    console.log('Task Args')
    console.log(args)

    // compile

    await run('compile')

    // get signer

    const signer = (await ethers.getSigners())[0]
    console.log('Signer')
    console.log('  at', signer.address)
    console.log('  ETH', formatEther(await signer.getBalance()))

    // deploy contracts

    const hypervisorFactoryFactory = await ethers.getContractFactory('HypervisorFactory')

    const hypervisorFactory = await deployContract(
      'HypervisorFactory',
      await ethers.getContractFactory('HypervisorFactory'),
      signer,
      [args.uniswapFactory]
    )

    await hypervisorFactory.deployTransaction.wait(5)
    await run('verify:verify', {
      address: hypervisorFactory.address,
      constructorArguments: [args.uniswapFactory],
    })
})
Example #25
Source File: addBaadgeSvgs.ts    From aavegotchi-contracts with MIT License 5 votes vote down vote up
task("addBaadgeSvgs", "Adds itemTypes and SVGs")
  .addParam("itemManager", "Address of the item manager", "0")

  .addParam("svgFile", "Name of the itemType SVGs")
  .addParam("svgIds", "List of SVG IDs to add or update")

  .setAction(
    async (taskArgs: AddBaadgeTaskArgs, hre: HardhatRuntimeEnvironment) => {
      const svgFile: string = taskArgs.svgFile;
      const itemManager = taskArgs.itemManager;
      const svgIds: string[] = taskArgs.svgIds
        .split(",")
        .filter((str) => str.length > 0);
      const svgArrayIndex = Number(taskArgs.svgArrayIndex);

      console.log("svg ids:", svgIds);

      const { baadges } = require(`../svgs/${svgFile}.ts`);

      const svgsArray: string[] = baadges;

      let signer: Signer;

      let owner = itemManager;
      const testing = ["hardhat", "localhost"].includes(hre.network.name);
      if (testing) {
        await hre.network.provider.request({
          method: "hardhat_impersonateAccount",
          params: [owner],
        });
        signer = await hre.ethers.provider.getSigner(owner);
      } else if (hre.network.name === "matic") {
        signer = await (await hre.ethers.getSigners())[0];
        // signer = new LedgerSigner(
        //   hre.ethers.provider,
        //   "hid",
        //   "m/44'/60'/2'/0/0"
        // );
      } else {
        throw Error("Incorrect network selected");
      }

      let svgFacet = (await hre.ethers.getContractAt(
        "SvgFacet",
        maticDiamondAddress,
        signer
      )) as SvgFacet;

      for (let index = 0; index < svgIds.length; index++) {
        const svgId = svgIds[index];

        console.log("array id:", svgArrayIndex);
        console.log("svg length:", svgsArray[svgArrayIndex].length);

        try {
          await uploadOrUpdateSvg(
            svgsArray[svgArrayIndex],
            "wearables",
            Number(svgId),
            svgFacet,
            hre.ethers
          );
        } catch (error) {
          console.log("error uploading", svgId, error);
        }
      }
    }
  );
Example #26
Source File: updateRates.ts    From ghst-staking with MIT License 5 votes vote down vote up
task("updateRates", "Updates the pool rates with specified pools and rates")
  .addParam("rateManagerAddress", "Address of the multisig signer")
  .addParam("epoch", "The current epoch")
  .addParam("poolsAndRates", "Stringified array of pools and rates to add")
  .setAction(
    async (taskArgs: UpdateRateTaskArgs, hre: HardhatRuntimeEnvironment) => {
      const signer = await getDiamondSigner(
        hre.ethers,
        hre.network,
        taskArgs.rateManagerAddress,
        false
      );

      const pools = convertStringToPoolsAndRates(taskArgs.poolsAndRates);

      for (let index = 0; index < pools.length; index++) {
        const pool = pools[index];

        await validateReceiptToken(pool._poolReceiptToken, hre);
        validatePoolToken(pool._poolAddress, hre);
      }

      const stakingFacet = (await hre.ethers.getContractAt(
        "StakingFacet",
        maticStakingAddress,
        signer
      )) as StakingFacet;

      const data = await stakingFacet.populateTransaction.updateRates(
        taskArgs.epoch,
        pools,
        {
          gasPrice: gasPrice,
        }
      );

      console.log("GNOSIS SAFE DATA");
      console.log(data);

      const tx = await stakingFacet.updateRates(taskArgs.epoch, pools, {
        gasPrice: gasPrice,
      });
      console.log("Initiating epoch:", tx.hash);
      let receipt = await tx.wait();
      if (!receipt.status) {
        throw Error(`Updating accounts failed: ${tx.hash}`);
      }
      console.log("Epoch created");
    }
  );
Example #27
Source File: hardhat.config.ts    From solidity-starter with MIT License 5 votes vote down vote up
// Tasks

task('accounts', 'Prints the list of accounts', async (taskArgs, bre) => {
  const accounts = await bre.ethers.getSigners()
  for (const account of accounts) {
    console.log(await account.getAddress())
  }
})
Example #28
Source File: hardhat.config.ts    From balancer-v2-monorepo with GNU General Public License v3.0 5 votes vote down vote up
task(TASK_TEST)
  .addOptionalParam('fork', 'Optional network name to be forked block number to fork in case of running fork tests.')
  .addOptionalParam('blockNumber', 'Optional block number to fork in case of running fork tests.', undefined, types.int)
  .setAction(test);
Example #29
Source File: artifact.ts    From eth with GNU General Public License v3.0 5 votes vote down vote up
task('artifact:read', 'Read Artifact data from Tokens contract').setAction(artifactsRead);