关于智能合约:如何通过-Hardhat-来验证智能合约

1次阅读

共计 6300 个字符,预计需要花费 16 分钟才能阅读完成。

在很大水平上,因为部署到通用区块链的智能合约的不变性,平安始终是用户和企业的首要任务。因而,在以太坊上开发智能合约的关键步骤之一是初始部署后的 Etherscan 验证。Etherscan 使任何人,从用户到经验丰富的开发人员和 bug hunter,都能够查看代码的有效性、正确性和安全性。

在之前的文章中,咱们学习了如何浏览 Etherscan 上的智能合约以及如何应用 Remix IDE 验证 Etherscan 上的智能合约。在本教程中,咱们的指标是理解如何应用最罕用的智能合约开发框架之一——Hardhat 来实现验证。

让咱们开始吧。

创立一个 Hardhat 我的项目

让咱们先创立一个新的 Hardhat 我的项目。首先,咱们要查看咱们机器上装置的 npm 版本。关上你的终端并输出:

npm -v

如果你没有装置 npm,请依照这个指南进行操作。而后,输出以下命令装置 Hardhat:

npm install --save-dev hardhat

如果你应用的是 yarn 而非 npm,请输出:

yarn add --dev hardhat

如果你应用的是 Windows,强烈建议应用 WSL 2。

要创立示例我的项目,请在我的项目文件夹中运行以下命令,而后抉择“创立 TypeScript 我的项目”:

npx hardhat

开发一个智能合约

如果后面的步骤工作失常,你当初应该可能看到三个次要的 Hardhat 文件夹:“contracts”、“test”和“scripts”。转到“contracts”文件夹,创立一个新的 Solidity 文件,并将其命名为“PriceFeedConsumer.sol”。而后,复制以下来自 Chainlink 官网文档的源代码。

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract PriceConsumerV3 {

    AggregatorV3Interface internal priceFeed;

    /**
     * Network: Goerli
     * Aggregator: ETH/USD
     * Address: 0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e
     */
    constructor(address priceFeedAddress) {priceFeed = AggregatorV3Interface(priceFeedAddress);
    }

    /**
     * Returns the latest price
     */
    function getLatestPrice() public view returns (int) {
        (
            /*uint80 roundID*/,
            int price,
            /*uint startedAt*/,
            /*uint timeStamp*/,
            /*uint80 answeredInRound*/
        ) = priceFeed.latestRoundData();
        return price;
    }
}

当初通过以下命令装置 @chainlink/contracts 依赖包:

npm install --save-dev @chainlink/contracts

而后,通过运行以下命令编译合约

npx hardhat compile

选项 1:在部署脚本中应用 hardhat-etherscan 插件验证你的合约

应用 Hardhat,你能够应用 hardhat-etherscan 插件在 Etherscan 上验证你的智能合约。

首先,你须要一个 Etherscan API 密钥。要取得一个,请拜访 Etherscan 网站,收费创立一个新帐户并登录。之后,单击“API 密钥”选项卡。最初,单击“增加”按钮生成新的 API 密钥。

咱们将把咱们的智能合约部署到 Goerli 测试网络。如果你以前从未做过,你可能须要晓得,为了从 Hardhat 部署智能合约,你必须提供私钥和 JSON RPC URL。你能够收费注册 Alchemy 以取得密钥。

你还须要一些测试用的 ETH,你能够从 Chainlink Faucet 轻松取得。

导航回你的 Hardhat 我的项目。批改“hardhat.config.ts”文件:

export default {
  // rest of the config
  networks: {hardhat: {},
    goerli: {url: `https://eth-goerli.alchemyapi.io/v2/${ALCHEMY_API_KEY}`,
      accounts: [GOERLI_PRIVATE_KEY],
    },
  },
  etherscan: {apiKey: "ABCDE12345ABCDE12345ABCDE123456789", // Your Etherscan API key},
};

在“scripts”文件夹中创立新文件,并将其命名为“deployPriceFeedConsumer.ts”。该脚本将部署 PriceFeedConsumer.sol 智能合约,出于平安起因,期待几个区块,并尝试在 Etherscan 上对其进行验证。

import {ethers, network, run} from "hardhat";

async function main() {
  const priceFeedAddress =“0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e”;

  const priceFeedConsumerFactory = await ethers.getContractFactory(“PriceConsumerV3”);
  const priceFeedConsumer = await priceFeedConsumerFactory.deploy(priceFeedAddress);

  const WAIT_BLOCK_CONFIRMATIONS = 6;
  await priceFeedConsumer.deployTransaction.wait(WAIT_BLOCK_CONFIRMATIONS);

  console.log(`Contract deployed to ${priceFeedConsumer.address} on ${network.name}`);

  console.log(`Verifying contract on Etherscan...`);

  await run(`verify:verify`, {
    address: priceFeedConsumer.address,
    constructorArguments: [priceFeedAddress],
  });
}

main().catch((error) => {console.error(error);
  process.exitCode = 1;
});

保留文件并从终端运行下一个命令:

npx hardhat run scripts/deployPriceFeedConsumer.ts --network goerli

你的合约当初应该部署到 Goerli 测试网并在 Etherscan 浏览器上进行验证。

选项 2:从你的 CLI 应用 hardhat-etherscan 插件验证合约

咱们将再次应用 hardhat-etherscan 插件来验证咱们的智能合约。

首先,返回 Etherscan 并注册一个帐户。在您的帐户设置下,找到“API 密钥”局部。应用收费打算生成一个 API 密钥。

咱们将再次将咱们的智能合约部署到 Goerli 测试网。如果你须要测试通证,请拜访 Chainlink Faucet。

批改“hardhat.config.ts”文件

export default {
  // rest of the config
  networks: {hardhat: {},
    goerli: {url: `https://eth-goerli.alchemyapi.io/v2/${ALCHEMY_API_KEY}`,
      accounts: [GOERLI_PRIVATE_KEY],
    },
  },
  etherscan: {apiKey: "ABCDE12345ABCDE12345ABCDE123456789", // Your Etherscan API key},
};

在“scripts”文件夹中创立新文件,并将其命名为“deployPriceFeedConsumer.ts”。这将部署 PriceFeedConsumer.sol 智能合约并期待几个区块。

import {ethers, network} from "hardhat";

async function main() {
  const priceFeedAddress =“0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e”;

  const priceFeedConsumerFactory = await ethers.getContractFactory(“PriceConsumerV3”);
  const priceFeedConsumer = await priceFeedConsumerFactory.deploy(priceFeedAddress);

  const WAIT_BLOCK_CONFIRMATIONS = 6;
  await priceFeedConsumer.deployTransaction.wait(WAIT_BLOCK_CONFIRMATIONS);

  console.log(`Contract deployed to ${priceFeedConsumer.address} on ${network.name}`);
}

main().catch((error) => {console.error(error);
  process.exitCode = 1;
});

应用以下命令部署你的智能合约:

npx hardhat run scripts/deployPriceFeedConsumer.ts --network goerli

咱们当初将应用 Hardhat 的“验证”工作从 CLI 在 Etherscan 上验证这个智能合约。此命令的个别语法如下所示:

npx hardhat verify --network <network> <contract address> <constructor parameters>

咱们将通过以下形式对其进行调整:

npx hardhat verify --network goerli <contract address> 
0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e

你应该可能在 Etherscan 上看到咱们合约的公开验证源代码的链接。如果你收到一条谬误音讯说地址没有字节码,这可能意味着 Etherscan 还没有为你的合约建设索引。在这种状况下,请稍等片刻,而后重试。

选项 3:应用 hardhat flatten 工作验证你的合约

应用 Hardhat 进行 Etherscan 验证的第三个选项相似于通过 Remix IDE 进行的验证过程,这在咱们之前的一篇文章中有所形容。

咱们再次部署到 Goerli 测试网络,如果你须要测试通证,请导航至 Chainlink Faucet。为此,你不须要 Etherscan API 密钥。

你的“hardhat.config.ts”文件应如下所示:

export default {
  // rest of the config
  solidity: "0.8.9",
  networks: {hardhat: {},
    goerli: {url: `https://eth-goerli.alchemyapi.io/v2/${ALCHEMY_API_KEY}`,
      accounts: [GOERLI_PRIVATE_KEY],
    },
  }
};

咱们将再次应用上一章的部署脚本:

import {ethers, network} from "hardhat";

async function main() {
  const priceFeedAddress =“0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e”;

  const priceFeedConsumerFactory = await ethers.getContractFactory(“PriceConsumerV3”);
  const priceFeedConsumer = await priceFeedConsumerFactory.deploy(priceFeedAddress);

  const WAIT_BLOCK_CONFIRMATIONS = 6;
  await priceFeedConsumer.deployTransaction.wait(WAIT_BLOCK_CONFIRMATIONS);

  console.log(`Contract deployed to ${priceFeedConsumer.address} on ${network.name}`);
}

main().catch((error) => {console.error(error);
  process.exitCode = 1;
});

运行部署脚本:

npx hardhat run scripts/deployPriceFeedConsumer.ts --network goerli

如果你在 Etherscan 上搜寻你的合约地址,单击 Contract 选项卡时你只会看到合约的字节码。

要开始验证过程,请单击“Verify and Publish”链接。将显示以下页面。

如果没有自动弹出,请在第一个输出字段中输出你的合约地址。

而后,从“Compiler Type”下拉列表中,抉择“Solidity(单个文件)”。

之后,将显示“Compiler Version”下拉列表。在这里你须要抉择你在部署之前用于编译这个智能合约的同一个 Solidity 编译器版本。如果你回顾一下“hardhat.config.ts”文件,你会发现在咱们的例子中,编译器的版本是 0.8.9。

最初,从“Open Source License Type”下拉列表中,在 Solidity 文件结尾抉择 License 许可,指定为“SPDX-License-Identifier”,在本例中为 MIT。点击“持续”进入下一页。

在下一页上,你应该粘贴智能合约的源代码。可怜的是,如果你像咱们一样导入了其余合约或接口,则不能只在此处复制粘贴。Etherscan 还须要晓得这些导入合约的源代码。为此,你须要通过键入以下命令来“flatten”你所有的智能合约:

npx hardhat flatten

你的智能合约“flatten”版本将在终端中打印进去。或者,你可能心愿将其保留在独自的文件中,你能够通过输出以下内容来实现:

npx hardhat flatten contracts/PriceFeedConsumer.sol > cotracts/PriceFeedConsumer_flat.sol

当初你能够将合约的源代码粘贴到“Enter the Solidity Contract Code below”输入框中。而后,解决验证码并单击蓝色的“Verify and Publish”按钮。你应该可能在 Contract 选项卡上看到绿色复选标记。这意味着你已胜利验证你的合约。

总结

在本文中,咱们介绍了如何应用三种不同的办法从 Hardhat 验证 Etherscan 上的智能合约。智能合约验证是部署过程中的关键步骤之一,因为它容许社区在应用之前查看源代码。

欢送关注 Chainlink 预言机并且私信退出开发者社区,有大量对于智能合约的学习材料以及对于区块链的话题!

正文完
 0