一、环境准备
-
安装Node.js
-
需安装Node.js 14及以上版本(推荐16或18 LTS)6
-
验证安装:
cssbashCopy Code node -v npm -v
-
-
更新npm
cssbashCopy Code npm install -g npm
二、Truffle安装
-
全局安装Truffle
cssbashCopy Code npm install -g truffle
- 验证安装:
truffle version
56
- 验证安装:
-
可选工具Ganache
-
桌面版:从Ganache官网下载
-
CLI版:
cssbashCopy Code npm install -g ganache-cli
-
三、项目创建
-
初始化空项目
bashbashCopy Code mkdir my_project && cd my_project truffle init
-
生成目录结构:
initextCopy Code contracts/ # Solidity合约目录 migrations/ # 部署脚本目录 test/ # 测试文件目录 truffle-config.js # 配置文件 ```:ml-citation{ref="3,4" data="citationList"}
-
-
使用模板项目(推荐)
bashbashCopy Code truffle unbox metacoin # 官方MetaCoin示例
或Webpack模板:
inibashCopy Code truffle unbox webpack ```:ml-citation{ref="2,7" data="citationList"}
四、开发流程
-
编写合约
-
在
contracts/
目录下创建.sol
文件(如MyContract.sol
) -
示例代码结构:
inisolidityCopy Code pragma solidity .8.0; contract MyContract { // 合约逻辑 } ```:ml-citation{ref="3" data="citationList"}
-
-
编译合约
cssbashCopy Code truffle compile
- 生成ABI和字节码到
build/contracts/
5
- 生成ABI和字节码到
-
部署合约
-
配置
truffle-config.js
中的网络设置(如Ganache) -
运行部署:
inibashCopy Code truffle migrate ```:ml-citation{ref="4,5" data="citationList"}
-
truffle migrate --reset 覆盖部署第二个 Truffle exec .\scripts\test Truffle exec E:\workspace\truffle\test\test.js
五、测试与调试
-
运行测试
bashbashCopy Code truffle test
- 支持JavaScript和Solidity测试脚本7
-
控制台交互
cssbashCopy Code truffle console
- 可直接调用合约方法3
jq 下载地址 github.com/stedolan/jq... Git Bash 用户注意 :需将 jq.exe
放入 Git 安装目录的 mingw64\bin
下4。
scss
npm install -g solc
生成abi 文件
jq ".abi" build/contracts/StudentStorage.json > build/StudentStorage.abi
//生成go
abigen --combined-json build/contracts/StudentStorage.json --pkg=store --out=StudentStorage.go
- 安装jq工具
jq是轻量级JSON处理命令行工具,支持数据提取和格式转换。在Linux系统中可通过sudo apt-get install jq
或yum install jq
安装,MacOS使用brew install jq
56。 - 全局安装Solidity编译器
npm install -g solc
通过Node.js包管理器全局安装Solidity编译器,使开发者能在任何目录使用solc
命令编译智能合约28。安装后可通过solc --version
验证版本2。 - 提取ABI文件
jq ".abi" build/contracts/StudentStorage.json > build/StudentStorage.abi
使用jq从合约编译产物中提取ABI(应用二进制接口)并保存为独立文件。ABI定义了合约方法与参数结构,是调用合约的必要描述文件34。 - 生成Go语言绑定
abigen --combined-json build/contracts/StudentStorage.json --pkg=store --out=StudentStorage.go