ethereum测试部署合约
我们尝试在ganache-cli环境来部署合约
先来写一个简单的合约
pragma solidity ^0.4.24;
contract SimpleStorage {
string str;
constructor(string _str) public{
str=_str;
}
function setValue(string _str) public{
str=_str;
}
function getValue() public view returns(string){
return str;
}
}
合约写好了,
然后我们需要编译合约
我们来创建一个compile.js文件
let fs = require('fs');
let solc = require('solc');
let contractInfo = fs.readFileSync('./simplestorage.sol');
let compileInfo = solc.compile(contractInfo.toString(), 1);
module.exports = compileInfo['contracts'][':SimpleStorage'];
1.先导入fs和solc,fs是文件系统,solc是编译器
2.读取sol文件,然后用solc来编译读取出的数据
3.然后导出
然后创建一个deploy.js文件
//导入
let {bytecode, interface} = require('./compile')
//大写Web3导入的是构造函数,需要实例化
let Web3 = require('web3')
//实例化web3对象, 并且设置网络
let web3 = new Web3('http://127.0.0.1:7545')
//地址,付款账户
let account1 = '0xd5957914c31e1d785c......'
//部署
let deploy = async () => {
//1. 实例化合约数据,填写ABI
// JSON.parse() : string => json
// stringfy() : json => string
let contractInstance = new web3.eth.Contract(JSON.parse(interface))
//2. 填写bytecode,构造函数参数
let res = await contractInstance.deploy({
data: bytecode,
arguments: ["hello world!"]
}).send({
//用哪个账户
from: account1,
// gas : 10000000000, //gas过大,超过区块的上限
gas: '1000000'
})
console.log('address : ', res.options.address)
}
deploy()
这里我们要node deploy.js一下
看一下最后打印出来的合约地址
然后我们把ganache-cli打开
ganache-cli -h 127.0.0.1 -p 7545 -m "scout same naive ...."
然后我们打开remix
打开Run
我们要把environment改成Web3 Provider环境
然后改成localhost:7545
然后我们在At Address里输入合约地址
然后就可以调用getValue了
获取到的就是hello world