【链下签名】Ropsten测试网发布合约

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);
    });

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值