起始公式
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();
web3.eth.getBlock("latest",false);
|
账户
1 2 3 4 5 6 7 8 9 10
| web3.eth.getAccounts().then(console.log);
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
|
web3.eth.getBalance('0x8aC8215492Ce132Eb4d1db7EcE3eF0caF670deFf',function(error,result){ var balance=result.toString(); console.log(web3.utils.fromWei(balance,"ether")) })
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);
|