使用 Foundry 部署合约#

本教程将逐步介绍如何使用 Foundry(智能合约开发工具链)在 X Layer 测试网上创建、编译并部署一个简单的智能合约。

什么是 Foundry#

Foundry 提供了一套完整的工具,用于在以太坊区块链上构建和部署去中心化应用(DApp)。借助 Foundry,你可以使用 Solidity 编程语言编写智能合约,并在以太坊区块链上完成编译、部署和交互。

配置开发环境#

如果尚未安装 Foundry,请访问 book.getfoundry,从侧边菜单选择 Installation,按照说明使用 Foundryup 进行下载。

shell
curl -L https://foundry.paradigm.xyz | bash

安装成功后,终端将可使用以下四个 CLI 工具:forge、cast、anvil 和 chisel。

创建合约#

使用以下命令初始化项目:

shell
forge init hello_contract
cd hello_contract

hello_contract/src 目录下,可以编辑 Counter.sol 文件:

solidity
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;

contract Counter {
    uint256 public number;

    function setNumber(uint256 newNumber) public {
        number = newNumber;
    }

    function increment() public {
        number++;
    }
}

编译合约#

接下来,使用 forge 命令编译合约:

shell
forge build

成功后,将看到如下信息:

shell
[] Compiling...
[] Compiling 22 files with 0.8.16
[] Solc 0.8.16 finished in 2.75s
Compiler run successful!

部署合约#

运行 forge create 命令部署合约。将 HTTP_URL 替换为你实际的 RPC 端点,将 PRIVATE_KEY 替换为你的实际私钥。

bash
forge create --rpc-url HTTP_URL \
--private-key PRIVATE_KEY \
src/Counter.sol: Counter

部署成功后,将看到如下信息:

shell
[] Compiling...
No files changed, compilation skipped
Deployer: 0x9536354AE32852A7E7C4BFe7415b104016d5Fb04
Deployed to: 0xF0D4950d45CFf612A02f453771CF93418dCaaA0B
Transaction hash: 0xc09923e09e5f4a72053bcf72ca66e0fdf434ab63380481ab39ae281c63a716a0

与合约交互#

运行 cast 命令与合约进行交互。 使用 setNumber 函数发起写调用,例如:

bash
cast send CONTRACT_ADDRESS "setNumber(uint256)" 10 --rpc-url HTTP_URL --private-key PRIVATE_KEY

成功后,将看到如下信息:

bash
blockHash               0xf1ceea989197708be58264f3e7ebeae3ebffc5d6f345d053fd73c932627ea7fb
blockNumber             9760236
contractAddress         
cumulativeGasUsed       2638507
effectiveGasPrice       3000000070
gasUsed                 43494
logs                    []
logsBloom               0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
root                    
status                  1
transactionHash         0xd17510371187101f37e96a6287dea64467eeeddae56207e45807e8626c4b01b4
transactionIndex        6
type                    2

使用 number 函数发起读调用,例如:

bash
cast call CONTRACT_ADDRESS "number()" --rpc-url HTTP_URL

成功后,将看到如下信息:

bash
0x000000000000000000000000000000000000000000000000000000000000000a