一 编译
npx hardhat compile
二 测试
npx hardhat test
三部署
注意部署的时候2.0和3版本有所区别,3.0如下
# 部署到本地网络(如已运行 npx hardhat node)
npx hardhat ignition deploy ./ignition/modules/MyModule.ts --network localhost# 部署到测试网(如 Sepolia)
npx hardhat ignition deploy ./ignition/modules/MyModule.ts --network sepolia
2.0版本
npx hardhat run scripts/deploy.js --network localhost
部署成功后会返回合约名称和地址,
查看部署后信息
npx hardhat ignition
3.1查询部署id,如chain-31337
npx hardhat ignition deployments
3.2查询部署状态
npx hardhat ignition status + 部署id
四 npx hardhat console --network localhost
npx hardhat console --network localhost
是一个用于与本地Hardhat网络进行交互式对话的命令行工具,它极大地简化了智能合约的开发和调试过程。你可以把它想象成区块链版的“浏览器开发者工具控制台。
启动控制台后,你处在一个预配置了 ethers.js
的 JavaScript 交互环境(REPL)中,可以快速查询区块链的当前状态
const signers = await ethers.getSigners(); // 获取所有签名者对象
const account0 = signers[0];
console.log("第一个账户的地址:", account0.address);
const balanceWei = await ethers.provider.getBalance(signers[0].address);
console.log("账户余额 (Ether):", ethers.formatEther(balanceWei)); // 格式化为ETH单位
与已部署的合约交互:这是控制台最核心的功能,让你可以动态地调用合约函数,无需编写额外的脚本
// 附着到已部署的合约
const MyContract = await ethers.getContractFactory("YourContractName");
const contract = await MyContract.attach("YOUR_DEPLOYED_CONTRACT_ADDRESS");// 调用只读函数
const data = await contract.getSomeData();
console.log("Data:", data.toString());// 调用写入函数
const tx = await contract.setSomeData(123);
await tx.wait();
console.log("Transaction confirmed!");
npx hardhat console
的核心价值在于它极大地提升了开发效率和调试体验:
- ∙
快速验证:无需为了一次简单的函数调用或状态查询而编写和运行完整的脚本。
- ∙
即时反馈:提供了一个“所见即所得”的游乐场,让你可以立即看到操作的结果。
- ∙
交互式调试:在开发过程中,可以随时测试和调整参数,快速定位问题。
⚠️ 注意事项
- ∙
确保网络配置正确:
--network localhost
表示连接到你本地运行的 Hardhat 节点(通常在http://127.0.0.1:8545
)。确保你已运行npx hardhat node