Are you an LLM? Read llms.txt for a summary of the docs, or llms-full.txt for the full context.
Skip to content

验证智能合约

验证会将您的合约源代码上传到区块浏览器,并证明其编译为已部署的字节码。一旦验证,用户可以在 Stablescan 上读取状态、调用函数和审计源代码,而无需重新托管您的代码。本指南将介绍如何在 Stable 上验证 Foundry 部署的合约。

Stablescan 在 Etherscan 的多链 (V2) API 上运行,因此验证和所有其他浏览器 API 调用都将发送到 https://api.etherscan.io/v2/api 并带有 chainid 参数:

网络链 ID验证器 URL
Stable 测试网2201https://api.etherscan.io/v2/api?chainid=2201
Stable 主网988https://api.etherscan.io/v2/api?chainid=988

前提条件

  • 已经在 Stable 测试网或主网部署的合约。如果您尚未部署,请参阅部署智能合约
  • 已安装 Foundry(forge 在您的 PATH 中可用)。如果 --verifier custom 未被识别,请运行 foundryup
  • forge create 输出中的已部署合约地址。
  • 来自 https://etherscan.io/myapikey 的 Etherscan API 密钥。一个密钥涵盖 V2 API 上的所有链,包括两个 Stable 网络。

1. 确认已部署的地址

请确保您拥有之前部署的 Deployed to 地址。在部署智能合约流程中,这是在 forge create 后打印的值。

cast code 0xDeployedContractAddress --rpc-url https://rpc.testnet.stable.xyz | head -c 20
0x6080604052600436...

非空字节码确认合约已部署在该地址。

2. 导出您的 API 密钥

Foundry 和 curl 都从您的 shell 读取密钥,因此请一次性导出。

export ETHERSCAN_API_KEY=YourApiKey
 
curl "https://api.etherscan.io/v2/api?chainid=2201&module=account&action=balance&address=0xDeployedContractAddress&tag=latest&apikey=$ETHERSCAN_API_KEY"
{"status":"1","message":"OK","result":"0"}

"status":"1" 响应确认密钥在 Stable 测试网上可用。如果您收到 Missing/Invalid API Key,则密钥未设置或尚未激活。

3. 运行 forge verify-contract

将 Foundry 指向链 2201 的 Etherscan V2 端点。

forge verify-contract \
  0xDeployedContractAddress \
  src/Counter.sol:Counter \
  --chain-id 2201 \
  --verifier custom \
  --verifier-url "https://api.etherscan.io/v2/api?chainid=2201" \
  --verifier-api-key $ETHERSCAN_API_KEY \
  --watch
Start verifying contract `0xDeployedContractAddress` deployed on 2201

Submitting verification for [src/Counter.sol:Counter] 0xDeployedContractAddress.
Submitted contract for verification:
        Response: `OK`
        GUID: `abc123...`
Contract verification status:
Response: `OK`
Details: `Pass - Verified`
Contract successfully verified

--watch 会阻塞直到验证完成,这样您就不必轮询了。在主网上,将链 ID 切换到 988,验证器 URL 切换到 https://api.etherscan.io/v2/api?chainid=988

4. 在 Stablescan 上确认验证

在浏览器上打开合约页面。

https://testnet.stablescan.xyz/address/0xDeployedContractAddress

Contract 选项卡现在应该显示源代码、一个绿色的“已验证”徽章和完整的 ABI。用户可以在 Read Contract 下读取状态,在 Write Contract 下发送交易。

故障排除

  • “Invalid API URL endpoint”:您正在直接调用浏览器主机。将 https://testnet.stablescan.xyz/api 替换为 https://api.etherscan.io/v2/api?chainid=2201
  • “Missing/Invalid API Key”ETHERSCAN_API_KEY 在当前 shell 中未设置,或者密钥刚刚创建且尚未激活。重新运行步骤 2 中的 curl 检查。
  • “Bytecode does not match”:您的源代码编译为与已部署的字节码不同的字节码。最常见的原因是 Solidity 版本或优化器设置不匹配。明确传递 --compiler-version--optimizer-runs 以匹配您的 foundry.toml
  • “GUID not found”:验证器尚未注册您的提交。使用 --watch 重新运行或手动检查响应中打印的 URL。
  • 合约使用库:为每个链接的库添加 --libraries src/Lib.sol:Lib:0xDeployedLibAddress

下一步推荐