npm的web3
1.获取账户地址
var localhost = "http://127.0.0.1:8545"
var Web3 = require("web3")
var web3 = new Web3(new Web3.providers.HttpProvider(localhost))
web3.eth.getAccounts(function (error, result) {
console.log("账户列表地址:");
console.log(result);
});
部署合约测试
var localhost = "http://127.0.0.1:8545"
var Web3 = require("web3")
var web3 = new Web3(new Web3.providers.HttpProvider(localhost))
async function getAccount(){
return new Promise((resolve,reject)=>{
web3.eth.getAccounts((err,result)=>{
if(err){reject(err);return}
resolve(result)
})
})
}
async function readContractFile(fileName){
return new Promise((resolve, reject) => {
let filePath = path.resolve(__dirname,fileName)
fs.readFile(filePath,'utf8',(err,res)=>{
if(err){reject(err);return}
resolve(res)
})
})
}
async function deploy(AbiInfo,ByteCode,arguments,account,gas,){
var currentContract = new web3.eth.Contract(JSON.parse(AbiInfo))
currentContract.deploy({
data:JSON.parse(ByteCode).object,
arguments:arguments
}).send({
from:account,
gas:gas
},function(e,contract){
console.log(e, contract);
if (typeof contract.address !== 'undefined') {
console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);
}
})
}
//部署测试
async function deployContract(){
let account = (await getAccount())[0]
let AbiInfo = await readContractFile("file/ABI.json")
let ByteCode = await readContractFile("file/ByteCode.json")
await deploy(AbiInfo,ByteCode,[],account,'4700000')
}
deployContract()
和合约交互
合约部署完后得到合约地址,把地址放在web3.eth.Contract里