使用Hardhat验证 Solidity 源码 (Ethereum or BSC)
hardhat-etherscan 这个插件可以帮助你在Etherscan上验证 Solidity 合约的源代码。
- 只需提供部署地址和构造函数参数,插件将在本地检测要验证的合约。
- 如果您的合约使用 Solidity库,插件将检测它们并自动处理它们。你不需要对它们做任何事情。
- 验证过程的模拟将在本地运行,允许插件检测和传达过程中的任何错误。
- 一旦模拟成功,合同将使用 Etherscan API 进行验证。
安装:
npm install --save-dev @nomiclabs/hardhat-etherscan
并将以下语句添加到您的hardhat.config.js:
require("@nomiclabs/hardhat-etherscan");
将以下 Etherscan 配置添加到您的hardhat.config.js文件中:
module.exports = {
solidity: {
version: '0.8.4',
settings: {
optimizer: {
enabled: true,
runs: 200,
},
},
},
contractSizer: {
alphaSort: true,
runOnCompile: true,
disambiguatePaths: false,
},
networks: {
tbsc: {
url: "https://data-seed-prebsc-1-s1.binance.org:8545/",
accounts:
["你的私钥"],
},
ropsten: {
url: "https://ropsten.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161",
accounts:
["你的私钥"],
},
},
etherscan: {
// etherscan:
// bscscan:
apiKey: "your apiKey",
},
};
部署到bsc测试链:
D:MySCDMToken>npx hardhat run scripts/yourtoken.js --network tbsc
Compiling 9 files with 0.8.4
Compilation finished successfully
YourToken deployed to: 0x915D4D9aEe18F4c22ab6e2dA51aD9473E4b929B3
运行verify任务(合约源代码、部署网络、合约的地址)
D:MySCDMToken>npx hardhat verify --contract contracts/Greeter2.sol:YourToken --network tbsc 0x915D4D9aEe18F4c22ab6e2dA51aD9473E4b929B3
Nothing to compile
Compiling 1 file with 0.8.4
Successfully submitted source code for contract
contracts/Greeter2.sol:YourToken at 0x915D4D9aEe18F4c22ab6e2dA51aD9473E4b929B3
for verification on Etherscan. Waiting for verification result...
Successfully verified contract YourToken on Etherscan.
https://testnet.bscscan.com/address/0x915D4D9aEe18F4c22ab6e2dA51aD9473E4b929B3#code
另附:
scripts/yourtoken.js
const hre = require("hardhat");
async function main() {
// We get the contract to deploy
const Greeter = await hre.ethers.getContractFactory("YourToken");
const greeter = await Greeter.deploy();
await greeter.deployed();
console.log("YourToken deployed to:", greeter.address);
}
// We recommend this pattern to be able to use async/await everywhere
// and properly handle errors.
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
contracts/YourToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract YourToken is ERC20, ERC20Burnable, Pausable, Ownable {
constructor() ERC20("YourToken", "YTK") {
_mint(msg.sender, 10000 * 10 ** decimals());
}
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
function mint(address to, uint256 amount) public onlyOwner {
_mint(to, amount);
}
function _beforeTokenTransfer(address from, address to, uint256 amount)
internal
whenNotPaused
override
{
super._beforeTokenTransfer(from, to, amount);
}
}