说在前
区块链很热,去中心化app(DAPP)、智能合约的概念也很多。感觉是谁都需要来弄一下。
看了一下 下面两个兄弟的入门教程,编译不过,发现是 我用的稍微新一点版本,下面记录一下
https://blog.csdn.net/pony_maggie/article/details/79685942
https://www.jianshu.com/u/6c2a9614936b
前期准备
无 一步步来吧
代码在我的github-smartcontract 上
环境
macos
流程
1 用Solidity 语言(类似js,但是缺少很多功能) 编写一个智能合约
2 编写一个部署js 通过node命令 连接eth 节点(或者测试节点ganache) 部署自己的合约
3 编写一个测试js 通过node命令 访问合约 进行数据沟通
最简合约
不写注释了, 很简单
pragma solidity ^0.4.0;
contract Hello {
function say(uint x, uint y) public returns (uint) {
return x+y;
}
}
node 环境准备
建个文件夹,node init
这是依赖项
"dependencies": {
"fs": "0.0.1-security",
"solc": "^0.4.24",
"web3": "^1.0.0-beta.34"
}
部署合约js
1 参考这个兄弟的ganache搭建
https://www.jianshu.com/p/2e42d816a594
2 上面这个兄弟用的web3.js是老版本的,所以我改了一下deploy.js
关于web3.js 1.0 的文档在这:http://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#id13
deploy.js
//设置web3连接
var Web3 = require('web3');
//http://localhost:7545 为Ganache提供的节点链接
var web3 = new Web3(new Web3.providers.HttpProvider('http://127.0.0.1:7545'));
//读取合约
var fs = require('fs');
var contractCode = fs.readFileSync('Hello.sol').toString();
//编译合约代码
var solc = require('solc');
var compileCode = solc.compile(contractCode);
//console.log(compileCode);
//获取合约abi和字节码
var abi = JSON.parse(compileCode.contracts[':Hello'].interface);
var byteCode = compileCode.contracts[':Hello'].bytecode;
//创建合约对象
web3.eth.getAccounts().then(function(data) {
var account = data[0];
var deployedContract = new web3.eth.Contract(abi,'',{});
console.log(deployedContract);
deployedContract.deploy({
data:byteCode
}).send({
from:account, //部署合约的外部账户地址
gas:750000 //部署合约的矿工费
}).then(function(newContractInstance){
console.log(newContractInstance.options.address) // instance with the new contract address
});
});
3 直接运行 node deploy.js
可以在控制台 得到一个地址 xxxxxxxxxxxxxxxxxxxxxxxxxx 这个就是合约地址了
访问合约
run.js
//设置web3连接
var Web3 = require('web3');
//http://localhost:7545 为Ganache提供的节点链接
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:7545'));
//读取合约
var fs = require('fs');
var contractCode = fs.readFileSync('Hello.sol').toString();
//编译合约代码
var solc = require('solc');
var compileCode = solc.compile(contractCode);
//获取合约abi和字节码
var abi = JSON.parse(compileCode.contracts[':Hello'].interface);
var byteCode = compileCode.contracts[':Hello'].bytecode;
//创建合约对象
var myContract = new web3.eth.Contract(abi,'xxxxxxxxxxxxxxxxxxxxxxxxxx',{});
myContract.methods.say(4,5).call({}, function(error, result){
console.log(result)
});
node run.js
ok!
done
网友评论