【web3.js】基本操作

web3.js 核心操作

连接节点

var Web3 = require('web3');
var web3 = new Web3('http://localhost:8545');
// or 或者 ? 这里直接用URL和用Web3.providers.HttpProvider 有什么区别?
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));

// change provider 更换provider
web3.setProvider('ws://localhost:8546');
// or
web3.setProvider(new Web3.providers.WebsocketProvider('ws://localhost:8546'));

// Using the IPC provider in node.js
var net = require('net');
var web3 = new Web3('/Users/myuser/Library/Ethereum/geth.ipc', net); // mac os path
// or
var web3 = new Web3(new Web3.providers.IpcProvider('/Users/myuser/Library/Ethereum/geth.ipc', net)); // mac os path
// on windows the path is: "\\\\.\\pipe\\geth.ipc"
// on linux the path is: "/users/myuser/.ethereum/geth.ipc"

账号相关

1. 生成账号

  1. 创建账号:
 const a = web3.eth.accounts.create()
  1. 通过私钥生成账号
const privateKey = '0xe096cbf3fd506f950dd323a459bd394b7bf1021607262d10bbde492d43a1f09f'
const account = web3.eth.accounts.privateKeyToAccount(privateKey)

2. 生成钱包(待研究使用方法)

web3.eth.accounts.wallet.add(account);
web3.eth.defaultAccount = account.address;

二、合约相关

1. 初始化合约实例

//初始化合约实例
var myContract = new web3.eth.Contract(DidRegistryContract,registryAddress)

2. 发送交易

  1. 使用web3ethereumjs-tx , 使用本地私钥发送交易,调用合约中的方法
let Web3 = require('web3')
const web3 = new Web3('http://192.168.11.22:8547')
const EthereumTx = require('ethereumjs-tx')

//智能合约地址
const registryAddress = "0xa45bEA07Ed18B6ddF82f9403c02192aBC4e13178"
//智能合约对应Abi文件
const DidRegistryContract = require('./build/contracts/ethr-registry.json')

const privateKey =  Buffer.from('e096cbf3fd506f950dd323a459bd394b7bf1021607262d10bbde492d43a1f09f',"hex")
//私钥转换为账号
const account = web3.eth.accounts.privateKeyToAccount("0xe096cbf3fd506f950dd323a459bd394b7bf1021607262d10bbde492d43a1f09f");
//私钥对应的账号地地址
const address = account.address
console.log("address: ",address)

//获取合约实例
var myContract = new web3.eth.Contract(DidRegistryContract,registryAddress)

//获取nonce,使用本地私钥发送交易
web3.eth.getTransactionCount(address).then(
    nonce => {
        console.log("nonce: ",nonce)
        const txParams = {
            nonce: nonce,
            gasLimit: '0x271000',
            gasPrice: '0x271000',
            value:'0x00',
            to: registryAddress,
            data: myContract.methods.set(10).encodeABI(), //智能合约中set方法的abi
           
          }
          const tx = new EthereumTx(txParams)
        tx.sign(privateKey)
        const serializedTx = tx.serialize()
        //同步方式
        web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'))
.on('receipt', console.log);
		/** 异步方式
		 web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'),function(err,hash){
		        if (!err) {
		            console.log("hash: ",hash)
		            return hash 
		        }
		    })
		*/

          
    },
    e => console.log(e)
)
  1. 获取abi(encodeABI)
myContract.methods.set(10).encodeABI()
  1. 调用合约方法,需要unlockAccount
// 同步方式更新智能合约中的方法
var myContract = new web3.eth.Contract(DidRegistryContract,registryAddress)
myContract.methods.set(10).send({from:address})
.then(function(receipt){
    console.log("receipt: ",receipt)
});
  1. 查询合约中的方法,不发生交易
 //调用智能合约(仅查询,不发生交易)
myContract.methods.get().call({from: address})
.then(function(receipt){
    console.log("receipt: ",receipt)
});

3. Gas相关

 // 预估需要消耗的Gas
  myContract.methods.setAttribute(address,stringToBytes32(key),attributeToHex(key,value)
,86400
).estimateGas({gas: 5000000}, function(error, gasAmount){
    console.log("gasAmount: ",gasAmount)
    if(gasAmount == 5000000)
        console.log('Method ran out of gas');
});

你可能感兴趣的:(以太坊)