Skip to content

ockerm698-coder/local-chain

Repository files navigation

Truffle 本地链部署指南

这是一个使用 Truffle 框架开发和部署智能合约到本地区块链的项目。

项目结构

local-chain/
├── contracts/          # 智能合约文件
│   └── testContract.sol
├── migrations/         # 部署脚本
│   └── 1763457336_test_contract.js
├── test/              # 测试文件
├── build/             # 编译输出目录
├── web-test/          # Web 测试目录
└── truffle-config.js  # Truffle 配置文件

环境要求

  • Node.js (推荐 v14 或更高版本)
  • Truffle: npm install -g truffle
  • Ganache (本地区块链)

从零创建 Truffle 项目

第一步: 安装 Truffle

# 全局安装 Truffle
npm install -g truffle

# 验证安装
truffle version

第二步: 初始化项目

创建空白项目

# 创建项目目录
mkdir my-truffle-project
cd my-truffle-project

# 初始化 Truffle 项目
truffle init

初始化后的项目结构:

my-truffle-project/
├── contracts/          # 智能合约目录
├── migrations/         # 部署脚本目录
├── test/              # 测试文件目录
└── truffle-config.js  # Truffle 配置文件

第三步: 创建智能合约、部署脚本和测试

使用 truffle create 命令可以快速创建合约相关文件:

# 创建合约、部署脚本和测试文件 (推荐)
truffle create all MyContract

这个命令会自动创建:

  • contracts/MyContract.sol - 智能合约文件
  • migrations/####_my_contract.js - 部署脚本
  • test/my_contract.js - 测试文件

或者分别创建:

# 只创建合约
truffle create contract MyContract

# 只创建 migration
truffle create migration DeployMyContract

# 只创建测试
truffle create test MyContract

第四步: 编写智能合约

编辑 contracts/MyContract.sol:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract MyContract {
    string public message;
    uint256 public count;

    constructor(string memory _message) {
        message = _message;
        count = 0;
    }

    function setMessage(string memory _message) public {
        message = _message;
        count++;
    }

    function getMessage() public view returns (string memory) {
        return message;
    }
}

第五步: 编写部署脚本

编辑 migrations/####_my_contract.js:

const MyContract = artifacts.require("MyContract");

module.exports = function(deployer) {
  // 部署合约,传入构造函数参数
  deployer.deploy(MyContract, "Hello Blockchain!");
};

第六步: 配置网络

编辑 truffle-config.js,配置本地开发网络:

module.exports = {
  networks: {
    development: {
      host: "127.0.0.1",     // Ganache 地址
      port: 7545,            // Ganache 端口
      network_id: "*",       // 匹配任何网络
    }
  },

  compilers: {
    solc: {
      version: "0.8.21",     // Solidity 版本
    }
  }
};

第七步: 启动本地区块链

# 使用 Ganache GUI (推荐)
# 1. 下载并安装 Ganache: https://trufflesuite.com/ganache/
# 2. 启动 Ganache,确保运行在 127.0.0.1:7545

# 或使用 Ganache CLI
npm install -g ganache
ganache --port 7545

# 或使用 Truffle 内置开发环境
truffle develop

第八步: 编译和部署

# 编译合约
truffle compile

# 部署合约到本地网络
truffle migrate

# 如果需要重新部署
truffle migrate --reset

第九步: 与合约交互

# 进入 Truffle 控制台
truffle console --network development

在控制台中:

// 获取已部署的合约实例
let instance = await MyContract.deployed()

// 调用方法
await instance.getMessage()
// 输出: 'Hello Blockchain!'

await instance.setMessage("New Message")
await instance.getMessage()
// 输出: 'New Message'

// 查看计数
let count = await instance.count()
console.log(count.toString())
// 输出: '1'

快速开始

1. 安装依赖

npm install

2. 启动本地区块链

方式一: 使用 Ganache GUI

  • 下载并安装 Ganache
  • 启动 Ganache,默认运行在 127.0.0.1:7545
  • 确保 Ganache 端口与 truffle-config.js 中配置的端口一致

方式二: 使用 Ganache CLI

# 安装 ganache
npm install -g ganache

# 启动 ganache (端口 7545)
ganache --port 7545

方式三: 使用 Truffle 内置开发环境

truffle develop

这会启动一个内置的区块链实例,运行在 127.0.0.1:9545

3. 编译智能合约

truffle compile

编译后的合约文件会保存在 build/contracts/ 目录下。

4. 部署智能合约

# 部署到本地网络 (development)
truffle migrate

# 或者指定网络
truffle migrate --network development

# 重新部署 (重置)
truffle migrate --reset

5. 与合约交互

使用 Truffle Console

truffle console --network development

在控制台中交互:

// 获取合约实例
let instance = await testContract.deployed()

// 调用合约方法
await instance.sayHi()
// 输出: 'Hello Chain!'

await instance.getInfo()
// 输出: [ 'whh', 123n ]

// 修改合约状态
await instance.setInfo("Alice", 25)

// 再次查询
await instance.getInfo()
// 输出: [ 'Alice', 25n ]

6. 运行测试

truffle test

网络配置

当前项目配置了以下网络 (在 truffle-config.js 中):

Development Network

development: {
  host: "127.0.0.1",
  port: 7545,        // Ganache 默认端口
  network_id: "*",   // 匹配任何网络 ID
}

testContract 智能合约说明

合约功能

  • name: 存储名字的状态变量
  • age: 存储年龄的状态变量
  • setInfo(string, uint256): 设置名字和年龄
  • sayHi(): 返回问候语 "Hello Chain!"
  • getInfo(): 获取当前名字和年龄
  • setSuccess 事件: 在信息更新时触发

部署脚本

位于 migrations/1763457336_test_contract.js:

const testContract = artifacts.require("testContract");
module.exports = function(deployer) {
  deployer.deploy(testContract);
};

常用命令

# 编译合约
truffle compile

# 部署合约
truffle migrate

# 进入交互式控制台
truffle console

# 运行测试
truffle test

# 查看网络状态
truffle networks

# 查看网络中的账户
truffle networks --clean  # 清理网络配置

故障排查

端口冲突

如果 7545 端口被占用,可以修改 truffle-config.js 中的端口配置,或在 Ganache 中使用不同端口。

网络连接失败

确保 Ganache 正在运行,并且端口号与配置文件一致。

合约部署失败

# 尝试重新编译和部署
truffle compile
truffle migrate --reset

Gas 不足

truffle-config.js 中增加 gas 配置:

development: {
  host: "127.0.0.1",
  port: 7545,
  network_id: "*",
  gas: 6721975,
  gasPrice: 20000000000
}

更多资源

编译器配置

当前使用的 Solidity 版本: 0.8.21

如需修改,请编辑 truffle-config.js 中的 compilers 部分。

About

Truffle 本地区块链开发项目 - 智能合约学习与测试

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published