1.安装solc
使用npm安装solc的前提是已经安装了nodejs
若没有可以自行前往下载:nodejs官网
测试安装是否成功:
安装好nodejs后,nodejs自带npm,使用npm安装solc:
可以修改npm的存储路径:
npm config set prefix “D:\nodejs\node_global”
npm config set cache “D:\nodejs\node_cache”
solc安装命令:
npm intall -g solc
默认安装的是最新版
若要安装具体版本则:
npm install -g solc@0.4.22
2.配置环境变量
如果没有配置环境变量就使用这个命令,则会遇到提示:
无法将“solcjs”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确
环境变量设置
此电脑 ->属性 -> 高级系统设置 -> 环境变量
选中Path然后点击编辑,添加之前设置过的安装目录
3.使用solcjs编译合约
首先来看一份合约
myContract.sol
pragma solidity >=0.4.22 <0.7.0;
contract HelloWorld {
event CreatePeopleLog(address indexed creator,string name,uint age);
event SendEthToUserLog(address indexed sender,address indexed accepter,uint money);
enum Sex{man,woman}
struct Human{
address payable addr;
string name;
uint age;
Sex sex;
}
mapping(address => Human) public people;
uint numOfPeople = 0;
function CreatePeople(string memory _name,uint _age,Sex _sex) public{
Human memory human = Human({
addr:msg.sender,
name:_name,
age:_age,
sex:_sex
});
numOfPeople += 1;
people[msg.sender] = human;
emit CreatePeopleLog(msg.sender,people[msg.sender].name,people[msg.sender].age);
}
function SendEthToUser(address payable _accepter) public payable{
_accepter.transfer(msg.value);
emit SendEthToUserLog(msg.sender,_accepter,msg.value);
}
uint public luckyNum;
constructor() public{
luckyNum = 888;
}
function SetLuckyNum(uint _num) public{
luckyNum = _num;
}
function printHelloWorld() public returns(string memory){
return 'Hello,World!';
}
}
如果直接使用命令:
solcjs --abi E:\BlockChain\contract\myContract.sol
势必会编译失败,因为刚刚安装的是最新版,合约上的版本限制为:>=0.4.22 <0.7.0
而且新版与旧版的语法也有不一致的地方
解决方案一:
安装旧版的solc进行编译
npm install -g solc@0.6.0
如果是用solc.exe也可以编译只不过是直接输出到屏幕的
提示:cmd 与powershell 编译后的文件处理有些差异,在cmd中直接使用命令可以得到一个输出文件,在powershell可能不会输出文件,不过可以使用输出重定向。
解决方案二:
修改myContract.sol
pragma solidity >=0.4.22 <0.9.0;
contract HelloWorld {
event CreatePeopleLog(address indexed creator,string name,uint age);
event SendEthToUserLog(address indexed sender,address indexed accepter,uint money);
enum Sex{man,woman}
struct Human{
address payable addr;
string name;
uint age;
Sex sex;
}
mapping(address => Human) public people;
uint numOfPeople = 0;
function CreatePeople(string memory _name,uint _age,Sex _sex) public{
Human memory human = Human({
addr:payable(msg.sender),
name:_name,
age:_age,
sex:_sex
});
numOfPeople += 1;
people[msg.sender] = human;
emit CreatePeopleLog(msg.sender,people[msg.sender].name,people[msg.sender].age);
}
function SendEthToUser(address payable _accepter) public payable{
_accepter.transfer(msg.value);
emit SendEthToUserLog(msg.sender,_accepter,msg.value);
}
uint public luckyNum;
constructor() public{
luckyNum = 888;
}
function SetLuckyNum(uint _num) public{
luckyNum = _num;
}
function printHelloWorld() public returns(string memory){
return 'Hello,World!';
}
}
修改的地方:
① 版本限制:pragma solidity >=0.4.22 <0.9.0;
② addr:msg.sender => addr:payable(msg.sender)