1. 构造Contract对象,调用deploy,添加已编译的bytecode;
2. 调用contract 的encodeABI函数获取合约编码;
3. 构造交易对象,发送地址to省略,签名交易发送交易完成新建合约;
var Web3 = require("web3");
var Tx = require('ethereumjs-tx');
///new signedTransaction
function newSignedTransaction(rawTx,privateKey) {
var tx = new Tx(rawTx);
tx.sign(privateKey);
return tx.serialize().toString('hex');
}
function toHexStringPrefixZeroPadded(str) {
if (str.indexOf("0x") === 0) {
return str;
}
return "0x" + str;
}
//sendRawTransaction
function sendRawTransaction(signedTxStr) {
web3.eth.sendSignedTransaction(toHexStringPrefixZeroPadded(signedTxStr), function (err, hash) {
if (!err)
console.log(hash);
}).on('transactionHash', function(hash){
console.log(hash);
}).on('receipt', function(receipt){
console.log(receipt);
}).on("error",function(error){
console.log(error);
});
// const receipt = await web3.eth.sendSignedTransaction(`0x${serializedEthTx}`);
// console.log(JSON.stringify(receipt, null, 4));
}
//deploy contract
function deployABI(obj, params) {
var contractObj = new web3.eth.Contract(obj.abi);
var encodedABI = contractObj.deploy({
data: toHexStringPrefixZeroPadded(obj.bytecode), //以0x开头
// data: obj.deployedBytecode, //以0x开头
arguments: (params == undefined ? [] : params)
});
return encodedABI;
}
///
const web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/v3/be5b825be13b4dda87056e6b073066dc"));
const privateKey = Buffer.from('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', 'hex');
const fs = require("fs")
var bfactory = fs.readFileSync("./build/contracts/BFactory.json").toString();
bfactory = JSON.parse(bfactory);
web3.eth.getTransactionCount("0x1084d79A66EF86BFc9c945d4a21159a024dEE14e")
.then(function (num) {
var encodeABI = deployABI(bfactory, []);
// console.log();
var signedTx = newSignedTransaction({
nonce: num,
gasPrice: web3.utils.toHex(20000000000),
gasLimit: web3.utils.toHex(8000000),
// to: '0x0000000000000000000000000000000000000000',
value: '0x0',
data: encodeABI.encodeABI()
}, privateKey);
sendRawTransaction(signedTx);
});