forge)$ forge init hello-world
$ cd hello-world && tree -L 1
.
├── foundry.toml # 项目的配置入口
├── lib/ # 依赖库目录,用于存放外部依赖(比如 openzeppelin-contracts)
├── README.md # 项目说明文档
├── script/ # 脚本目录,部署或脚本自动化代码的位置
├── src/ # 主合约目录,所有生产环境要部署的合约都应该放在这里
└── test/ # 测试目录,所有测试合约放在这里使用forge init 创建的项目中在 src、script和test目录下有项目的示例文件,在我们的 HelloWorld 合约中并不需要,所有需要将这些文件删除。
编辑 src/HelloWorld.sol:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract HelloWorld {
string public greet = "Hello, World!";
}$ forge build你将看到:
我们可以使用 anvil 在本地启动一条测试链来部署我们的合约,通过 http://127.0.0.1:8545就可以访问测试链:
$ anvil打开另一个终端,创建脚本 script/HelloWorld.s.sol:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "forge-std/Script.sol";
import "../src/HelloWorld.sol";
contract Deploy is Script {
function run() external {
vm.startBroadcast();
new HelloWorld();
vm.stopBroadcast();
}
}部署脚本运行:
$ forge script script/HelloWorld.s.sol --rpc-url http://127.0.0.1:8545 --broadcast --private-key 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80输出会显示部署地址:
Hardhat 我不怎么使用,所以下面的代码中可能误
$ mkdir hello-hardhat
$ cd hello-hardhat
$ npm init -y
$ npm install hardhat
$ npx hardhat选择 Create a basic sample project:
contracts/HelloWorld.sol// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract HelloWorld {
string public greet = "Hello, Hardhat!";
}$ npx hardhat compile$ npx hardhat nodeHardhat 会输出多个预置账户(含私钥),用于测试。
编辑 scripts/deploy.js:
const { ethers } = require("hardhat");
async function main() {
const Hello = await ethers.getContractFactory("HelloWorld");
const hello = await Hello.deploy(); // Already deployed here
await hello.deployed(); // optional, but often included to wait for deployment
console.log("Contract deployed to:", hello.address);
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});运行部署脚本:
$ npx hardhat run scripts/deploy.js --network localhost创建 Hardhat 控制台:
$ npx hardhat console --network localhost在控制台中输入:
const HelloWorld = await ethers.getContractFactory("HelloWorld");
const hello = await HelloWorld.attach("部署时输出的地址");
await hello.greet(); // 应输出 "Hello, Hardhat!"greet 值问题 | 原因 |
|---|---|
为何构造函数没用? | 我们没定义 |
public 变量为何自动生成 getter? | Solidity 会自动为 |
合约地址是怎么算出来的? | 它基于部署者地址 + nonce 生成。下一课我们会讲原理 |
你已经部署了人生第一个 Solidity 合约 🎉!
技术 | 工具 | 关键词 |
|---|---|---|
合约语言 | Solidity | 状态变量、合约部署 |
工具链 | Foundry / Hardhat | 脚本部署、编译、运行本地链 |
平台 | Remix | 快速验证合约逻辑 |
greet 字符串,重新部署。function setGreet(string memory newGreet) 可供外部调用。greet。下一课我们将讲:
第 2 课:《调用、修改、读取:Solidity 合约不是 REST API》