使用的win10
geth --rpc --rpcport "8545" --rpcapi "eth,web3,personal,net" --rpccorsdomain * console 2>>test.log --dev
如下图所示:
参数解析:
miner.start()
const Web3 = require('web3');
const solc = require ('solc');
如果不设置的话,会报错: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)之后
这个时候,挖矿了
参考文献