web3.js 1.3.5版本部署智能合约方法2021最新版

前言

web3js更新有点快,各种函数又不向后兼容,老版本的博客根本跑不了,旧文档很多地方都有问题,所以只能多百度多琢磨.

部署智能合约(私链)

  • geth 启动参数(参考)
geth  --datadir "./" --ethash.dagdir "./ethash" --syncmode fast --networkid 989898 --rpc console --port 30304 --rpcport 8545 --rpccorsdomain "*" --rpcapi "eth,web3,admin,personal,net" --ws --wsorigins="*" --wsaddr 0.0.0.0 --wsapi="eth,web3,personal,net,txpool,miner"

注意开启rpcapi即可:--rpcapi "eth,web3,admin,personal,net"

  • js代码
var Web3 = require('web3');
var fs = require('fs');    // fs模块读取.sol合约文件
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
var currentAccount = "0x4f49e0014748218c3734acd58a1a4157ab4bcd32"
// 查询以太币余额
web3.eth.getBalance(currentAccount).then(console.log);

function unlockAccount(account,password){
  web3.eth.personal.unlockAccount(account,password,(err,res)=>{
	if (err)
		console.log('Error: ', err);
	else 
        console.log('账户已解锁');
	})
}
//解锁账户
unlockAccount(currentAccount,"你的账户密码")

var abi = JSON.parse(fs.readFileSync("./CompiledSolidity/supChainMgr.abi"));  // 读取编译合约的abi文件。
var bytecode = fs.readFileSync("./CompiledSolidity/supChainMgr.bin");  // 读取编译合约的二进制文件。
var contract = new web3.eth.Contract(abi);  // 创建合约对象。
// 使用回调函数
contract.deploy({data:"0x"+bytecode.toString()}).send({
    from: currentAccount,
    gas: 1500000,
    gasPrice: '300000000'
}).on('transactionHash', function(transactionHash){
    console.log("交易地址"+transactionHash)
}).then(function(newContractInstance){
    //异步回调
    console.log("合约地址"+newContractInstance.options.address) // instance with the new contract address
});

// 估算gas
contract.deploy({
    data: "0x"+bytecode.toString()
}).estimateGas(function(err, gas){
    console.log(gas);
});

你可能感兴趣的:(区块链,js,区块链)