验证智能合约
验证会将您的合约源代码上传到区块浏览器,并证明其编译为已部署的字节码。一旦验证,用户可以在 Stablescan 上读取状态、调用函数和审计源代码,而无需重新托管您的代码。本指南将介绍如何在 Stable 上验证 Foundry 部署的合约。
Stablescan 在 Etherscan 的多链 (V2) API 上运行,因此验证和所有其他浏览器 API 调用都将发送到 https://api.etherscan.io/v2/api 并带有 chainid 参数:
| 网络 | 链 ID | 验证器 URL |
|---|---|---|
| Stable 测试网 | 2201 | https://api.etherscan.io/v2/api?chainid=2201 |
| Stable 主网 | 988 | https://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 200x6080604052600436...非空字节码确认合约已部署在该地址。
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 \
--watchStart 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/0xDeployedContractAddressContract 选项卡现在应该显示源代码、一个绿色的“已验证”徽章和完整的 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。
下一步推荐
- 索引合约事件:使用 ethers.js 订阅链上事件并构建实时事件流。
- 部署智能合约:搭建一个新的 Foundry 项目并部署到 Stable 测试网。
- JSON-RPC 参考:查看 Stable 支持哪些
eth_*方法用于链上交互。

