Solidity 开发环境搭建

 

本章介绍如何搭建 Solidity 开发环境。

我们推荐使用在线集成开发环境 Remix,来学习 Solidity 语言。

本教程的所有例子,都将使用 Remix 进行编写、编译和部署运行。

Remix的地址是 https://remix.ethereum.org/,我们可以直接打开使用。

当然,我们也可以使用下面的一些方法,来搭建 Solidity 开发环境。

 

1. 安装本地编译器

1) 安装 nodejs / npm

node官方网站下载 node,推荐 LTS 版本,按提示完成安装,npm 会同时装上。

安装步骤可以参照 Node.js 安装配置

验证 Node 版本,例如:

> node -v
v10.16.3

> npm -v
6.11.3

2) 安装 Solidity 编译器 solc

一旦安装了 Node.js 包管理器,就可以按照下面的步骤安装 Solidity 编译器:

$ npm install -g solc

上面的命令将会安装 solcjs 程序,并且能够在整个系统中都可用。

验证 solc 安装是否正确:

$ solcjs --version

如果一切顺利,这将打印如下内容

0.5.11+commit.c082d0b4.Emscripten.clang

现在,可以使用solcjs了,它比标准的 solidity 编译器少很多特性,但对于学习来说足够了。

 

2. 使用 solc-js

全局安装 solc-js 工具后,即可在命令行中直接使用此工具,可以通过 solcjs --help 来查看此工具支持的参数说明。

solcjs --help
Usage: C:\Program Files\nodejs\node_global\node_modules\@alipay\solc\solcjs
[options] [input_file...]

Options:
  --version         Show version number                                [boolean]
  --optimize        Enable bytecode optimizer.                         [boolean]
  --bin             Binary of the contracts in hex.                    [boolean]
  --abi             ABI of the contracts.                              [boolean]
  --standard-json   Turn on Standard JSON Input / Output mode.         [boolean]
  --output-dir, -o  Output directory for the contracts.                 [string]
  --help            Show help                                          [boolean]

我们创建名为 hello.sol 的 Solidity 合约示例:

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

contract Hello {
    string name;
  
    constructor()  {
        name = 'Hello world!';
    }
 
    function hello() view public returns (string memory) {
        return name;
    }
}

运行以下命令行,编译 hello.sol 合约并得到编译字节码结果:

solcjs --bin hello.sol

如果编译通过,此目录会得到包含字节码的结果文件 hello_sol_Hello.bin,如果编译失败则提示错误信息。

运行以下命令行,编译 hello.sol 合约并得得到合约接口说明(ABI):

solcjs --abi hello.sol

如果编译通过,此目录会得到包含合约接口说明(ABI)的结果文件 hello_sol_Hello.abi。

 

3. Remix IDE的安装

3.1 源码安装:

git clone https://github.com/ethereum/remix-ide.git
cd remix-ide
npm install
npm run build && npm run serve

3.2 docker 安装:

docker pull remixproject/remix-ide:latest
docker run -p 8080:8080 remixproject/remix-ide:latest

然后通过浏览器访问 127.0.0.1:8080 即可使用 remix。

 

4. Remix IDE 在线版

我们也可以直接使用在线版本:

https://remix.ethereum.org/

或者

http://remix.zhiguxingtu.com/

 

5. Remix 访问本地文件

首先安装 remixd:

npm install -g @remix-project/remixd

运行 remixd:

remixd -s /localdir --remix-ide url

其中 localdir 就是本地存放 solidity 文件的目录,--remix-ide 的参数是访问 IDE 的 url。

如果使用了本地安装的 remix IDE,那么参数 url 就是 http://localhost:8080。

如果使用了在线 remix IDE,比如 https://remix.ethereum.org,那么参数 url 就是 https://remix.ethereum.org:8080。

最后,激活 IDE 中的 remixd 插件,在 remix 的 workspaces 中选择 localhost 就可以了。

 

如果所示,激活 remixd 插件:

 

如果所示,选择 localhost,连接本地工作目录:

Solidity 语法:一个 Solidity 源文件可以包含任意数量的合约 contract 定义、import 指令和 pragma 指令。让我们从一个简单的 Solidity 源程序开始。下面是一个 Solidity 源文件的例子:p ...