使用的win10
1、安装geth
1.1 启动一个私有链
geth --rpc --rpcport "8545" --rpcapi "eth,web3,personal,net" --rpccorsdomain * console 2>>test.log --dev
如下图所示:
参数解析:
- –rpc:激活节点上的RPC
- –rpcapi:配置什么API可以通过rpc,geth默认会激活IPC上的所有API,以及RPC上的db、eth、net、web3
- –rpcport:配置端口,geth默认的是8080
- –rpccorsdomain:指定什么url可以连接到你的节点来执行RPC任务。
1.2 挖矿
miner.start()
node.js代码
const Web3 = require('web3');
const solc = require ('solc');
设置Provider
如果不设置的话,会报错:Error: Provider not set or invalid
let web3 = new Web3();
web3.setProvider(new Web3.providers.HttpProvider("http://127.0.0.1:8545"));
类似命令行中的:
geth attach http://localhost:8545
智能合约代码
const solidity=`pragma solidity ^0.4.20;
contract HelloWorldContract {
function sayHi() constant returns (string){
return 'Hello World';
}
}`;
编译智能合约
const output = solc.compile(solidity.toString(), 1);
const bytecode = output.contracts[':HelloWorldContract'].bytecode;
const abi = output.contracts[':HelloWorldContract'].interface;
创建智能合约对象
//创建一个Solidity的合约对象,用来在某个地址上初始化合约
const helloWorldContract = web3.eth.contract(JSON.parse(abi));
部署合约
const helloWorldContractInstance = helloWorldContract.new({
data: '0x' + bytecode,
from: web3.eth.coinbase,
gas: 1000000
}, (err, res) => {
if (err) {
console.log(err);
return;
}
// If we have an address property, the contract was deployed
console.log("res.address",res.address);
if (res.address) {//得有人挖矿(miner.start()),不然这个地址就是undifined
console.log('Contract address: ' + res.address);
console.log(helloWorldContract.at(res.address).sayHi({gas: 22222}))
}
});
输出:
res.address undefined
res.address 0x466e386e1707f4fa9fe34deaabb6f500429521d4
Contract address: 0x466e386e1707f4fa9fe34deaabb6f500429521d4
Hello World
可以看出new的回调函数执行了2次,参考文献1
第一次回调是发送交易(sendTransaction)之后,第二次是得到交易的收据(getTransactionReceipt)之后
这个时候,挖矿了
参考文献