起始公式

var Web3= require(‘web3’)
const rpcURL = “https://goerli.infura.io/v3/+key
const web3 = new Web3(rpcURL)

消息签名

1
2
3
4
let dataHash = "0x"
let privateKey = "0x"
let sign = web3.eth.accounts.sign(dataHash, privateKey)
console.log("signature", sign.signature)

区块信息查询

1
2
3
4
5
6
7
web3.eth.getBlockNumber().then(console.log);
web3.eth.getBlock();//'latest','earliest','pending'


//1.false默认不返回交易详细信息,true返回详细的交易信息
//2.getBlock中可以通过区块哈希区块高度来查看区块信息
web3.eth.getBlock("latest",false);

账户

1
2
3
4
5
6
7
8
9
10
//查询所有账户地址
web3.eth.getAccounts().then(console.log);

//创建新的账户
//(password,[callback])
web3.eth.personal.newAccount('jjk1323423').then(console.log);

//查看挖矿获奖的账户
web3.eth.getCoinbase().then(console.log);
web3.eth.isMining().then(console.log);//挖矿是否正在进行

查询用户余额及平均gas

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//查询用户余额
//(address ,[,defaultBlock])
//1.defaultBlock:表示执行到指定区块的余额
//function为回调函数
web3.eth.getBalance('0x8aC8215492Ce132Eb4d1db7EcE3eF0caF670deFf',function(error,result){
var balance=result.toString();
console.log(web3.utils.fromWei(balance,"ether"))
})

//gas价格查询
web3.eth.getGasPrice().then((result)=>{
console.log("wei:"+result)
console.log("ether:"+web3.utils.fromWei(result,"ether"))
})

交易有关内容

1. 发送交易

(transactionObiect,[,callback])
transactionObject{
from:
to:
value:
gas:
gasPrice:
data:若发送的为合约,则为合约的ABI文件,否则,则说明信息
noce:这是账号的前一个交易计数,这个值必须为16进制
可以使用Web3.js的web3.utils.toHex()转化

}

1
2
3
4
5
6
7
var transactionObiect={
from:"",
to:"",
value:web3.utils.toWei('1','ether'),
data:''
}
web3.eth.sendTransaction(transactionObiect).then(console.log)

2.查询交易信息

getTransactionFromBlock(hashStringOrNumber,indexNumber,[,callback])
1.hashStringOrNumber为: 区块号or区块哈希or earliest等
2.indexNumber为区块中交易索引,索引从0开始

1
web3.eth.getTransactionFromBlock(2,3);

或者这个也可以

1
web3.eth.getTransaction('hash').then(console.log)
1
2
3
4
5
//返回指定区块发出的交易数量
web3.eth.getBlockTransactionCount();

//查询交易收据
web3.eth.getTransactionReceipt("hash").then(console.log);