以太坊智能合约入门:Ganache + Truffle

 原创    2022-12-22

借助Ganache和Truffle,可以快速入门以太坊智能合约开发,本文将通过一个Demo,演示智能合约开发、编译至部署过程。

在浏览本文之前,你应该已经初步了解了以下内容:

  • Web3、区块链(Blockchain)及以太坊(Ethereum)的基础知识;
  • 什么是智能合约(Smart Contract )?
  • 什么是Solidity语言?

一、开发准备

本文介绍的两款开发工具均出自:https://trufflesuite.com

1、Ganache

Ganache是一个可以在本地模拟以太坊环境的客户端,新手入门时可以使用Ganache进行开发,因为其免费(虚拟的交易)且响应速度快,可以节省大量的开发时间,让开发者更专注业务本身。下载地址:https://www.trufflesuite.com/ganache

下载对应系统的版本安装即可。Ganache很容易上手,可以通过主页面的「QUICKSTART」一键启动一个本地以太坊环境。在设置的SERVER标签页,有RPC服务的地址和端口号,记下来后续会用到。

确保Ganache客户端已经启动了本地的以太坊环境。

2、Truffle:以太坊开发框架

Truffle是基于Javascript的以太坊Solidity语言开发框架,当我们需要在以太坊(Ethereum)部署智能合约时,Truffle框架能为我们提供从模版开发、编译、调试至部署的全面支持,简化了智能合约的开发流程。

安装Truffle

npm install truffle -g

安装完成后查看版本信息:truffle version

Truffle v5.7.0 (core: 5.7.0)
Ganache v7.5.0
Solidity v0.5.16 (solc-js)
Node v15.12.0
Web3.js v1.7.4

自动安装了依赖?看到这里将Ganache的命令行工具也安装了。

二、Smart Contract Demo

下面我们通过一个Hello World的例子,演示如何通过Truffle框架开发、编译并将智能合约部署至本地的Ganache。

1、从模版初始化项目

mkdir kanchuan
cd Kanchuan

//从模版新建项目
truffle init

Starting init...
================

> Copying project files to /Users/kanchuan

Init successful, sweet!

Try our scaffold commands to get started:
  $ truffle create contract YourContractName # scaffold a contract
  $ truffle create test YourTestName         # scaffold a test

http://trufflesuite.com/docs

初始化完成后,会在当前目录生成:

  • contracts

智能合约源文件目录。

  • migrations

迁移文件目录,智能合约编译之后会生成迁移javascript脚本,功能是将智能合约内容部署至以太坊网络。

  • test

测试用例代码目录。

  • truffle-config.js

配置文件。

我们按提示新建一个合约:

truffle create contract EaseContract

会在contracts目录生成{Contract_NAME}.sol的Solidity代码文件。

2、修改truffle-config.js

module.exports = {
	...
	networks: {
		development: {
			host: "127.0.0.1", 
			port: 7545,//本地Ganache RPC端口号
			network_id: "*", 
		},
	}
	...
	compilers: {
		solc: {
		//version: "0.8.17"
		settings: {
			optimizer: {
				enabled: true,
				runs: 200
			},
		}
	}
	...
}

3、一个Hello World例子

修改刚新建的contracts/EaseContract.sol内容:

// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;

contract EaseContract {
  string value;

  constructor() public {
    value = "hello world";
  }

  function getValue() public view returns(string memory) {
    return value;
  }

  function setValue(string memory _value) public {
    value = _value;
  }
}

这个智能合约非常简单,提供了两个方法getValuesetValue以便读写value属性,value默认值为hello world

在项目根目录执行编译:

truffle complie

完成后会生成build目录,包含合约文件:EaseContract.json

4、准备迁移脚本

在migrations目录新建文件1_deploy_contracts.js(多个脚本按数字序号递增,序号即为执行的顺序)。

var EaseContract = artifacts.require("../contracts/EaseContract.sol");
module.exports = function(deployer) {
  //部署合约
  deployer.deploy(EaseContract);
};

执行迁移部署:

truffle migrate
Compiling your contracts...
===========================
> Everything is up to date, there is nothing to compile.


Starting migrations...
======================
> Network name:    'development'
> Network id:      5777
> Block gas limit: 6721975 (0x6691b7)


1_deploy_contracts.js
=====================

   Deploying 'EaseContract'
   ------------------------
   > transaction hash:    0xc35871dd61fbad4f6437fe73dd6eaa51c5d930ead98ad7057f7b02a48489bc8c
   > Blocks: 0            Seconds: 0
   > contract address:    0xf56E28608D603A3B7c876c1c71be8A3CEde46ca4
   > block number:        38
   > block timestamp:     1671689352
   > account:             0x214d567CEd56f50cc4C29536F9be1a9F34A52169
   > balance:             99.827531129999999991
   > gas used:            246952 (0x3c4a8)
   > gas price:           20 gwei
   > value sent:          0 ETH
   > total cost:          0.00493904 ETH

   > Saving artifacts
   -------------------------------------
   > Total cost:          0.00493904 ETH

Summary
=======
> Total deployments:   1
> Final cost:          0.00493904 ETH

一切正常的话,切换到Ganache客户端,在TRANSACTIONS标签页可以看到新增了一个CONTRACT CREATIONTX DATA即为EaseContract.jsonbytecode节点的内容。

到此,我们已经完成了通过Truffle开发框架开发合约,并将合约部署至Ganache的本地以太坊环境中。在后续的博客中我讲继续介绍合约的调用等操作。

相关文章:

cocoapods-packager 插件的错误修复和适配
iOS安全:Tweak clang: warning: libstdc++ is deprecated
xcodebuild build failed:Use the $(inherited) flag
SQLite开发文档:SQLCipher加密
Swift并发编程 - 理解结构化和结构化并发的底层技术

发表留言

您的电子邮箱地址不会被公开,必填项已用*标注。发布的留言可能不会立即公开展示,请耐心等待审核通过。