使用 Hardhat 验证合约#
目前有两种方法可以在 OKLink 上验证你的代码。你可以使用推荐的 @okxweb3/hardhat-explorer-verify 插件,也可以根据 Hardhat 的官方文档修改 hardhat.config.js 文件。
重要说明#
- 首先,你需要在 OKLink 浏览器申请一个 API 密钥。
- 部署合约代码后,请至少等待一分钟再进行验证。
使用插件验证(推荐)#
示例#
- 首先,在你的 Hardhat 项目中使用以下命令安装插件:
npm install @okxweb3/hardhat-explorer-verify
- 在 Hardhat 配置文件(通常为 hardhat.config.js 或 hardhat.config.ts)中,导入并配置该插件,确保网络配置和 API 密钥设置正确。以下是一个配置示例:
import
import "@nomicfoundation/hardhat-toolbox";
import '@okxweb3/hardhat-explorer-verify'; // Import the plugin
const config: HardhatUserConfig = {
solidity: "0.8.20",
sourcify: {
enabled: true,
},
networks: {
xlayer: {
url: "https://xlayerrpc.example.com",
accounts: ["<Your Wallet Private Key>"],
},
},
etherscan: {
apiKey: '...'
},
okxweb3explorer: {
apiKey: "<Your API Key>",
}
};
export default config;- 部署合约后,使用 Hardhat 运行验证脚本。这通常需要执行一个特定的 Hardhat 任务,该任务会自动获取合约数据并将其提交至 OKX Chain 浏览器进行验证。 示例命令如下:
npx hardhat okverify --network xlayer <Your Contract Address>
- 验证成功后,你可以在 OKX Chain 区块链浏览器上查看验证状态和合约代码。
- 验证 TransparentUpgradeableProxy(透明可升级代理)合约
示例命令如下:
npx hardhat okxverify --network xlayer --contract <Contract>:<Name> --proxy <address>
--proxy指代理合约地址。
Note
如果你使用的是 897 Contract,则无需添加
--proxy,改用 --contract 代替。通过修改 hardhat.config.js 验证(备选方案)#
示例#
- 首先创建一个 Hardhat 项目,以 Lock 合约为例。
- 然后,按照以下内容修改项目目录中的
hardhat.config.js文件。 适用于 X Layer 测试网或主网:
solidity
module.exports = {
solidity: "0.8.9",
networks: {
xlayer: {
url: "https://testrpc.xlayer.tech/terigon", //or https://rpc.xlayer.tech for mainnet
accounts: [process.env.PRIVKEY]
}
},
etherscan: {
apiKey: process.env.ETHERSCAN_KEY,
customChains: [
{
network: "xlayer",
chainId: 195, //196 for mainnet
urls: {
apiURL: "https://www.oklink.com/api/v5/explorer/contract/verify-source-code-plugin/XLAYER_TESTNET", //or https://www.oklink.com/api/v5/explorer/contract/verify-source-code-plugin/XLAYER for mainnet
browserURL: "https://www.oklink.com/xlayer-test" //or https://www.oklink.com/xlayer for mainnet
}
}
]
}
};
将 process.env.PRIVKEY 替换为你自己部署地址的私钥,process.env.ETHERSCAN_KEY 可填写你的 OKLink API 密钥,可在 https://www.oklink.com/ 的【我的账户 - API 管理】处免费申请。
- 编译 Hardhat 合约代码并使用以下命令部署:
javascript
hh run scripts/deploy.js --network xlayer
- 等待一到两分钟后,运行以下命令并指定要验证的合约文件来验证合约。
javascript
hh verify --contract contracts/Lock.sol:Lock <address> <unlock time> --network xlayer
- 通过访问这里检查合约是否在主网上成功完成验证。
