本文环境:
区块链:以太坊POA联盟链;
出块节点数:3;
操作系统:windows 64;
节点版本:Geth1.9.14;
node版本:v10.14.0
参考文档:https://web3js.readthedocs.io/en/v1.2.8/
目录
0.1 使用回调
0.2 批量请求
0.3 大数(Big Number)的处理
一、web3
1.1 web3.version
1.2 web3.setProvider
1.3 web3.providers
1.4 web3.currentProvider
二、web3.eth
2.1 defaultAccount
2.2 defaultBlock
2.3 defaultHardfork
2.4 defaultChain
2.5 transactionBlockTimeout
2.6 transactionConfirmationBlocks
2.7 transactionPollingTimeout
2.8 getProtocolVersion
2.9 isSyncing
2.10 getCoinbase
2.11 isMining
2.12 getHashrate
2.13 getGasPrice
2.14 getAccounts
2.15 getBlockNumber
2.16 getBalance
2.17 getStorageAt
2.18 getCode
2.19 getBlock
2.20 getBlockTransactionCount
2.21 getBlockUncleCount
2.22 getUncle
2.23 getTransaction
2.24 getPendingTransactions
2.25 getTransactionFromBlock
2.26 getTransactionReceipt
2.27 getTransactionCount
2.28 sendTransaction
2.29 sendSignedTransaction
2.30 sign
2.31 signTransaction
2.32 call
2.33 getChainId
2.34 getNodeInfo
2.35 getProof
为了让DAPP在区块链网络上运行起来,用户需要使用web3.js库提供的web3对象。它通过rpc调用与一个本地节点进行通讯。也就是说,web3.js作为开放的rpc层,是与以太坊节点协同工作的。
web3 JavaScript API设计为跟一个本地rpc节点协同工作,默认使用同步HTTP请求。
如果想发出异步HTTP请求,可以采用错误优先(error first)回调方式,把一个可选回调函数作为最后一个参数传进去:
web3.eth.getBlock(48, function(error, result){
if(!error)
//If no error occurred, return result
console.log(result)
else
//If an error occurred, handle it (throw, etc)
console.error(error);
})
批量请求的处理:
var batch = web3.createBatch();
batch.add(web3.eth.getBalance.request('0x0000000000000000000000000000000000000000', 'latest', callback));
batch.add(web3.eth.contract(abi).at(address).balance.request(address, callback2));
batch.execute();
javaScript本质上对大数对象的处理不在行,比如下面的例子:
"101010100324325345346456456456456456456"
// "101010100324325345346456456456456456456"
101010100324325345346456456456456456456
// 1.0101010032432535e+38
因此,web3.js会自动加载BigNumber.js库来处理大数和进行完美计算。
下面的例子中,web3.eth.getBalance()方法获取地址余额,该方法返回一个Big Number对象;此时,需要调用toString(),把它转换成数字字符串。
var balance = new BigNumber('123456786979284780000000000');
// or var balance = web3.eth.getBalance(someAddress);
balance.plus(21).toString(10); // toString(10) converts it to a number string
// "123456786979284780000000021"
下面的例子中,因为是超过20个浮点数位的大数,BigNumber.js仍然无法正确处理;因此推荐以sha为单位存储余额,仅在向用户呈现时再转换成其他单位。web3.js自身总是以sha为单位返回和调取余额。
var balance = new BigNumber('13124.234435346456466666457455567456');
balance.plus(21).toString(10); // toString(10) converts it to a number string, but can only show max 20 floating points
// "13124.23443534645646666646" // you number would be cut after the 20 floating point
为了在node.js中使用web3.js,可以在项目目录中运行:
d:\myProject>npm install web3
本文一直没有安装成功,因此尝试使用以下方式安装:
//安装cnpm
C:\WINDOWS\system32>npm install -g cnpm --registry=https://registry.npm.taobao.org
//安装工具环境windows-build-tools,该步骤包括安装python2.7
C:\WINDOWS\system32>npm install -g --production windows-build-tools
//安装web3
C:\WINDOWS\system32>cnpm install -g web3
Downloading web3 to C:\Program Files\nodejs\node_global\node_modules\web3_tmp
[1/7] [email protected] installed at node_modules\[email protected]@web3-net
[2/7] [email protected] installed at node_modules\[email protected]@web3-eth-personal
[3/7] [email protected] installed at node_modules\[email protected]@web3-shh
[4/7] [email protected] installed at node_modules\[email protected]@web3-utils
[5/7] [email protected] installed at node_modules\[email protected]@web3-eth
[6/7] [email protected] installed at node_modules\[email protected]@web3-core
[7/7] [email protected] installed at node_modules\[email protected]@web3-bzz
execute post install 5 scripts...
.........................................................................................................................................
All packages installed (315 packages installed from npm registry, used 28s(network 6s), speed 1.31MB/s, json 288(688.25kB), tarball 7.52MB)
C:\WINDOWS\system32>
然后在源代码中使用require导入它;一个web3实例代表与节点的一个连接。
Example
var Web3= require('web3');
// create an instance of web3 using the HTTP provider.
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
或者,通过检查web3是否是undefined,来确保代码的可靠运行。
如果web3被定义了,则使用已经可用的实例;否则,通过连接至自定义节点创建一个实例。
if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);
} else {
// set the provider you want from Web3.providers
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}
直接查看web3对象:
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
console.log(web3);
web3.version
查询当前web3.js库版本。
Returns
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
console.log(web3.version); //1.2.8
web3.setProvider(provider)
在创建web3实例之后,可以使用setProvider方法改变provider,它有一个实参,即新provider实例。
Example
var Web3 = require('web3');
var web3 = new Web3('http://localhost:8545');
// or
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
// change 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"
web3.providers
Returns
Example
var Web3 = require('web3');
// use the given Provider, e.g in Mist, or instantiate a new websocket provider
var web3 = new Web3(Web3.givenProvider || 'ws://remotenode.com:8546');
// or
var web3 = new Web3(Web3.givenProvider || new Web3.providers.WebsocketProvider('ws://remotenode.com: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"
Configuration
// ====
// Http
// ====
var Web3HttpProvider = require('web3-providers-http');
var options = {
keepAlive: true,
withCredentials: false,
timeout: 20000, // ms
headers: [
{
name: 'Access-Control-Allow-Origin',
value: '*'
},
{
...
}
],
agent: {
http: http.Agent(...),
baseUrl: ''
}
};
var provider = new Web3HttpProvider('http://localhost:8545', options);
// ==========
// Websockets
// ==========
var Web3WsProvider = require('web3-providers-ws');
var options = {
timeout: 30000, // ms
// Useful for credentialed urls, e.g: ws://username:password@localhost:8546
headers: {
authorization: 'Basic username:password'
},
// Useful if requests result are large
clientConfig: {
maxReceivedFrameSize: 100000000, // bytes - default: 1MiB
maxReceivedMessageSize: 100000000, // bytes - default: 8MiB
},
// Enable auto reconnection
reconnect: {
auto: true,
delay: 5000, // ms
maxAttempts: 5,
onTimeout: false
}
};
var ws = new Web3WsProvider('ws://localhost:8546', options);
web3.currentProvider
web3.currentProvider属性被自动分配给当前的provider实例。
Returns
Example
// Check if eth already set a provider
if(!web3.currentProvider)
web3.setProvider(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.defaultAccount
默认地址用于"from"属性,如果没有"from"属性则用于以下方法:
returns
undefined
)Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
console.log(web3.eth.defaultAccount); //undefined
web3.eth.defaultAccount = "0x0297a8913cc187d60712f095a7e1bf2421bfcd40";
console.log(web3.eth.defaultAccount); //0x0297a8913cc187d60712f095a7e1bf2421bfcd40
web3.eth.defaultBlock
默认区块,默认值 ="latest"。用于以下方法:
returns
默认区块可以是下面的类型值:
Number:区块号;
String:“genesis”,创世区块;
String:“earliest”,创世区块;
String:“latest”,默认值,区块链中最新的区块;
String:“pending”,当前挖矿区块(包含了pending的交易);
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
console.log(web3.eth.defaultBlock); //latest,默认值
web3.eth.defaultBlock = 12345;
console.log(web3.eth.defaultBlock); //12345
web3.eth.defaultBlock = "genesis";
console.log(web3.eth.defaultBlock); //genesis
web3.eth.defaultHardfork
默认分叉属性,用于本地签名交易;
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
console.log(web3.eth.defaultHardfork); //undefined,本文poa私链
web3.eth.defaultHardfork = "istanbul";
console.log(web3.eth.defaultHardfork); //istanbul
web3.eth.defaultChain
默认链属性,用于本地签名交易;
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
console.log(web3.eth.defaultChain); //undefined,本文poa私链
web3.eth.defaultChain = "mainnet";
console.log(web3.eth.defaultChain); //mainnet
web3.eth.transactionBlockTimeout
交易区块超时;
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
console.log(web3.eth.transactionBlockTimeout); //50,默认值
web3.eth.transactionBlockTimeout = 60 ;
console.log(web3.eth.transactionBlockTimeout); //60
web3.eth.transactionConfirmationBlocks
交易确认区块数;
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
console.log(web3.eth.transactionConfirmationBlocks); //24,默认值
web3.eth.transactionConfirmationBlocks = 12 ;
console.log(web3.eth.transactionConfirmationBlocks); //12
web3.eth.transactionPollingTimeout
交易轮询超时,改属性通过HTTP连接使用。此选项定义Web3等待确认交易已被网络挖掘的收据的秒数。
注意:如果此方法超时,则交易可能仍处于pending状态。
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
console.log(web3.eth.transactionPollingTimeout); //750,默认值
web3.eth.transactionPollingTimeout = 600 ;
console.log(web3.eth.transactionPollingTimeout); //600
web3.eth.getProtocolVersion([callback])
节点的以太坊协议版本;
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.getProtocolVersion().then(console.log); //'0x41'
web3.eth.isSyncing([callback])
检查节点当前是否已经与网络同步;
Returns
一个Promise对象,其解析值为Object
或Boolean
。如果节点尚未与网络同步, 则返回false,否则返回一个同步对象,具有以下属性:
startingBlock - Number: 同步起始块编号
currentBlock - Number: 当前已同步块编号
highestBlock - Number: 预估的目标同步块编号
knownStates - Number: 预估的要下载的状态
pulledStates - Number: 已经下载的状态
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.isSyncing().then(console.log);//本文为poa私链节点,仅同步不出块,已经同步到最新区块,结果返回:false
//预期结果:
{
startingBlock: 100,
currentBlock: 312,
highestBlock: 512,
knownStates: 234566,
pulledStates: 123455
}
web3.eth.getCoinbase([callback])
当前接收挖矿奖励的账户地址;
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.getCoinbase().then(console.log); //0x0297a8913cc187d60712f095a7e1bf2421bfcd40
web3.eth.isMining([callback])
检查节点的挖矿状态;
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.isMining().then(console.log); //false or true
web3.eth.getHashrate([callback])
当前挖矿节点的每秒钟哈希值算出数量;
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.getHashrate().then(console.log); //493736;如果返回0,表示本节点没有挖矿
web3.eth.getGasPrice([callback])
获取当前gas价格,该价格由最近的若干区块的gas价格中值决定。
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.getGasPrice().then(console.log); //1000000000
web3.eth.getAccounts([callback])
当前节点控制的账户列表。
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.getAccounts().then(console.log);
[ '0x0297a8913cc187D60712F095a7E1BF2421bFCD40',
'0x38D8B866a1ABeBcA20AFC004622F5355EeFEB568',
'0xDa25997b15a6BeA86116942B8Ab69a5620D82284' ]
web3.eth.getBlockNumber([callback])
当前区块号。
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.getBlockNumber().then(console.log); //206136
web3.eth.getBalance(address [, defaultBlock] [, callback])
获取指定块中特定账户地址的余额。
Parameters
String :address- 要检查余额的账户地址;
Number|String :defaultBlock- 可选,使用该参数覆盖web3.eth.defaultBlock属性值;
Returns
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.getBalance("0x38D8B866a1ABeBcA20AFC004622F5355EeFEB568").then(console.log); //1539182000000000000
eth的单位说明:
{ noether: '0',
wei: '1',
kwei: '1000',
Kwei: '1000',
babbage: '1000',
femtoether: '1000',
mwei: '1000000',
Mwei: '1000000',
lovelace: '1000000',
picoether: '1000000',
gwei: '1000000000',
Gwei: '1000000000',
shannon: '1000000000',
nanoether: '1000000000',
nano: '1000000000',
szabo: '1000000000000',
microether: '1000000000000',
micro: '1000000000000',
finney: '1000000000000000',
milliether: '1000000000000000',
milli: '1000000000000000',
ether: '1000000000000000000',
kether: '1000000000000000000000',
grand: '1000000000000000000000',
mether: '1000000000000000000000000',
gether: '1000000000000000000000000000',
tether: '1000000000000000000000000000000' },
web3.eth.getStorageAt(address, position [, defaultBlock] [, callback])
返回一个以太坊地址的指定位置存储内容。
Parameters
String :address- 要读取的地址
Number :position- 存储中的索引编号
Number|String :defaultBlock- 可选,使用该参数覆盖web3.eth.defaultBlock属性值
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.getStorageAt("0x1e85d960a6fdcc5cb6deaf6567be527a1dd23602",0).then(console.log); //账号地址,返回0x0000000000000000000000000000000000000000000000000000000000000000
web3.eth.getStorageAt("0x1e85d960a6fdcc5cb6deaf6567be527a1dd23602",0).then(console.log); //合约地址,返回0x00000000000000000000000000000000000000000000d3c21bcecceda1000000
web3.eth.getStorageAt("0x1e85d960a6fdcc5cb6deaf6567be527a1dd23602",1).then(console.log); //合约地址,返回0x6b6f6e6766757a69546f6b656e0000000000000000000000000000000000001a
web3.eth.getCode(address [, defaultBlock] [, callback])
返回指定以太坊地址(通常是合约地址)处的代码;
Parameters
String :address- 要读取的地址
Number|String :defaultBlock- 可选,使用该参数覆盖web3.eth.defaultBlock属性值
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.getCode("0x1e85d960a6fdcc5cb6deaf6567be527a1dd23602").then(console.log); //账号地址,返回0x
web3.eth.getCode("0x1e85d960a6fdcc5cb6deaf6567be527a1dd23602").then(console.log); //合约地址,返回整个合约的bytecode,0x6080604052600436106100af576000357c0100........20029
web3.eth.getBlock(blockHashOrBlockNumber [, returnTransactionObjects] [, callback])
通过区块号或区块哈希获取对应的块信息。
Parameters
String|Number :blockHash or blockNumber- 区块号或区块哈希值。
Boolean :returnTransactionObjects- 可选,默认值为false。当设置为true时,返回块中将包括所有交易详情,否则仅返回交易哈希。
Returns
一个Promise对象,其解析值为满足搜索条件的区块对象,具有以下字段:
number - Number: 块编号,处于pending状态的块为null
hash 32 Bytes - String: 块哈希,处于pending状态的块为null
parentHash 32 Bytes - String: 父块哈希
nonce 8 Bytes - String: 生成的proof-of-work的哈希,处于pending状态的块为null
sha3Uncles 32 Bytes - String: 块中叔伯数据的SHA3值
logsBloom 256 Bytes - String: 块中日志的bloom filter,处于pending状态的块为null
transactionsRoot 32 Bytes - String: 块中的交易树根节点
stateRoot 32 Bytes - String: 块中的最终状态树根节点
miner - String: 接收奖励的矿工地址
difficulty - String: 该块的难度值
totalDifficulty - String: 截至该块的全链总难度值
extraData - String: 块 “extra data” 字段
size - Number: 字节为单位的块大小
gasLimit - Number: 该块允许的最大gas值
gasUsed - Number: 该块中所有交易使用的gas总量
timestamp - Number: 出块的unix时间戳
transactions - Array: 交易对象数组,或者32字节长的交易哈希值,取决于returnTransactionObjects的设置
uncles - Array: 叔伯块哈希值数组
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.getBlock(123456).then(console.log);
/*
{ difficulty: '2',
extraData:
'0xd88301090e846765746888676f312e31342e32856c696e757800000000000000fbeba116613305884a5777c34b363086ad78aa95df89c6adeaee35b3988feb2d68441792c211590278e8f6ff7dce44939fa9ebff5b166d56ee7dcb5464e3f49f00',
gasLimit: 8000000,
gasUsed: 0,
hash:
'0x763ac9f4656d79ec99c45634dcbc5ad1e87cf447fa8c36532bf7f96f22f95efe',
logsBloom:
'0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
miner: '0x0000000000000000000000000000000000000000',
mixHash:
'0x0000000000000000000000000000000000000000000000000000000000000000',
nonce: '0x0000000000000000',
number: 123456,
parentHash:
'0xc9537757f0e63b0a72738984776378c12162560730fee0a69fd96dbb80edc875',
receiptsRoot:
'0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421',
sha3Uncles:
'0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347',
size: 609,
stateRoot:
'0x07fd2236ebc14cb11fd6696b05b9d93e7fed1fe05e7ec356307b08462d0b6215',
timestamp: 1590938171,
totalDifficulty: '211001',
transactions: [],
transactionsRoot:
'0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421',
uncles: [] }
*/
web3.eth.getBlock("0xe4025dfba9210e94f7e44e82015a0bba01f97bec1790a7ee145b8a6e65c5b622").then(console.log);
/*
{ difficulty: '1',
extraData:
'0xd88301090e846765746888676f312e31342e32856c696e757800000000000000f0b17923e7c783dc6dc2a15ea798880298505afda350da1feb04f6d9089c6342420e48b7ca6b8572dc53446a49a767536d7852f877273fd80335d176e314b01401',
gasLimit: 8000000,
gasUsed: 1114009,
hash:
'0xe4025dfba9210e94f7e44e82015a0bba01f97bec1790a7ee145b8a6e65c5b622',
logsBloom:
'0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000080000000000000000000010000000000000020000000000000000000800000000000000000000000010000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000000000000200000002020000000000000000000000000000000000000000000000000020000010000000000000000000000000000000000000000000000000000000000000',
miner: '0x0000000000000000000000000000000000000000',
mixHash:
'0x0000000000000000000000000000000000000000000000000000000000000000',
nonce: '0x0000000000000000',
number: 207111,
parentHash:
'0x712f16b98828e5232da0bf218348ed30bab9be95e8b3c50eaf352461202fdf45',
receiptsRoot:
'0xee55a9beb3a3cd48dcbe5a398e56c88cd3e75d60293fdea5b9e6b4ebdaeebca2',
sha3Uncles:
'0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347',
size: 5936,
stateRoot:
'0x106f8885f29db87fa585fce93399d54b2fcd26262c759d5d9356ea81cc329527',
timestamp: 1591774721,
totalDifficulty: '322540',
transactions:
[ '0x7d376d4bf081382d27f55cbf4351e20ff0391607cdac2ed5dbb200add8b7ebf6' ],
transactionsRoot:
'0x3aa021842b20ff925fc47ed4c608d2284bdf5218267e51cfb6bf5a8dfac4dd41',
uncles: [] }
*/
web3.eth.getBlockTransactionCount(blockHashOrBlockNumber [, callback])
通过区块号或区块哈希获取对应的交易数量。
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.getBlockTransactionCount(123456).then(console.log);
//0
web3.eth.getBlockTransactionCount("0xe4025dfba9210e94f7e44e82015a0bba01f97bec1790a7ee145b8a6e65c5b622").then(console.log);
//1
web3.eth.getBlockUncleCount(blockHashOrBlockNumber [, callback])
获取某个区块的叔块数量。
web3.eth.getUncle(blockHashOrBlockNumber, uncleIndex [, returnTransactionObjects] [, callback])
获取某个叔块的信息,信息内容请参考2.19 getBlock。
web3.eth.getTransaction(transactionHash [, callback])
通过交易hash查询交易信息。
Returns
一个Promise对象,其解析值为具有给定哈希值的交易对象,该对象具有如下字段:
hash 32 Bytes - String: 交易的哈希值
nonce - Number: 交易发送方在此交易之前产生的交易数量
blockHash 32 Bytes - String: 交易所在块的哈希值。如果交易处于pending状态,则该值为null
blockNumber - Number: 交易所在块的编号,如果交易处于pending状态,则该值为null
transactionIndex - Number: 交易在块中的索引位置,如果交易处于pending状态,则该值为null
from - String: 交易发送方的地址
to - String: 交易接收方的地址。对于创建合约的交易,该值为null
value - String: 以wei为单位的转账金额
gasPrice - String: 发送方承诺的gas价格,以wei为单位
gas - Number: 发送方提供的gas用量
input - String: 随交易发送的数据
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.getTransaction("0x0854f0450f4c7656c774f24f305a19c5a274f6ebe54779346c69ac9723a77065").then(console.log);
/*
{ blockHash:
'0x3c3d9f151b52b860c855e2d2f72807f2ca84712ce5b4a050a8c5fd32e4cf6b5c',
blockNumber: 26055,
from: '0x1e85D960a6fDcC5cb6Deaf6567Be527a1DD23602',
gas: 21000,
gasPrice: '1000000000',
hash:
'0x0854f0450f4c7656c774f24f305a19c5a274f6ebe54779346c69ac9723a77065',
input: '0x',
nonce: 0,
to: '0x6B7eeaa2fe6bD6C47fB6Ca3835305301C5e759D6',
transactionIndex: 0,
value: '1000000000000000000000000',
v: '0x42d',
r:
'0x8cb775a7c65b3474e2c24f068f9f9dae65cbe438fed8ba64f52631e818a60abe',
s:
'0x43223efb967e43ebed824a0e11c641e6a515cc5fb6c2ac5355fecd2e434ebdbe' }
*/
web3.eth.getPendingTransactions([, callback])
查看处于pending状态的交易列表。信息内容参考2.23 getTransaction。
getTransactionFromBlock(hashStringOrNumber, indexNumber [, callback])
返回某个区块指定序号的交易。信息内容参考2.23 getTransaction。
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.getTransactionFromBlock(26055,0).then(console.log); //第1笔交易
/*
{ blockHash:
'0x3c3d9f151b52b860c855e2d2f72807f2ca84712ce5b4a050a8c5fd32e4cf6b5c',
blockNumber: 26055,
from: '0x1e85D960a6fDcC5cb6Deaf6567Be527a1DD23602',
gas: 21000,
gasPrice: '1000000000',
hash:
'0x0854f0450f4c7656c774f24f305a19c5a274f6ebe54779346c69ac9723a77065',
input: '0x',
nonce: 0,
to: '0x6B7eeaa2fe6bD6C47fB6Ca3835305301C5e759D6',
transactionIndex: 0,
value: '1000000000000000000000000',
v: '0x42d',
r:
'0x8cb775a7c65b3474e2c24f068f9f9dae65cbe438fed8ba64f52631e818a60abe',
s:
'0x43223efb967e43ebed824a0e11c641e6a515cc5fb6c2ac5355fecd2e434ebdbe' }
*/
web3.eth.getTransactionFromBlock(26055,1).then(console.log); //第2笔交易
//null
web3.eth.getTransactionReceipt(hash [, callback])
获取指定交易的收据对象。 如果交易处于pending状态,则返回null。
Returns
一个Promise对象,其解析值为交易的收据对象或者null。收据对象具有如下字段:
status - Boolean: 成功的交易返回true,如果EVM回滚了该交易则返回false
blockHash 32 Bytes - String: 交易所在块的哈希值
blockNumber - Number: 交易所在块的编号
transactionHash 32 Bytes - String: 交易的哈希值
transactionIndex - Number: 交易在块中的索引位置
from - String: 交易发送方的地址
to - String: 交易接收方的地址,对于创建合约的交易,该值为null
contractAddress - String: 对于创建合约的交易,该值为创建的合约地址,否则为null
cumulativeGasUsed - Number: 该交易执行时所在块的gas累计总用量
gasUsed- Number: 该交易的gas总量
logs - Array: 该交易产生的日志对象数组
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.getTransactionReceipt("0x0854f0450f4c7656c774f24f305a19c5a274f6ebe54779346c69ac9723a77065").then(console.log);
/*
{ blockHash:
'0x3c3d9f151b52b860c855e2d2f72807f2ca84712ce5b4a050a8c5fd32e4cf6b5c',
blockNumber: 26055,
contractAddress: null,
cumulativeGasUsed: 21000,
from: '0x1e85d960a6fdcc5cb6deaf6567be527a1dd23602',
gasUsed: 21000,
logs: [],
logsBloom:
'0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
status: true,
to: '0x6b7eeaa2fe6bd6c47fb6ca3835305301c5e759d6',
transactionHash:
'0x0854f0450f4c7656c774f24f305a19c5a274f6ebe54779346c69ac9723a77065',
transactionIndex: 0 }
*/
web3.eth.getTransactionCount(address [, defaultBlock] [, callback])
指定地址发出的交易数量。
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.getTransactionCount("0x38D8B866a1ABeBcA20AFC004622F5355EeFEB568").then(console.log);
//12
web3.eth.sendTransaction(transactionObject [, callback])
Parameters
transactionObject:Object - 要发送的交易对象,包含以下字段:
from - String|Number: 交易发送方账户地址,不设置该字段的话,则使用web3.eth.defaultAccount属性值。可设置为一个地址或本地钱包web3.eth.accounts.wallet中的索引序号
to - String: 可选,消息的目标地址,对于合约创建交易该字段为null
value - Number|String|BN|BigNumber: 可选,交易的数量,单位wei
gas - Number: 可选,默认值:待定,用于交易的gas总量,未用完的gas会退还
gasPrice - Number|String|BN|BigNumber: 可选,该交易的gas价格,单位为wei,默认值为web3.eth.gasPrice属性值
data - String: 可选,可以是包含合约方法数据的ABI字符串,或者是合约创建交易中的初始化代码
nonce - Number: 可选,使用该字段覆盖使用相同nonce值的挂起交易
returns
PromiEvent: 一个整合事件发生器的Promise对象,将在收到交易收据后得到解析。
"transactionHash" 返回String: 在交易发出并得到有效的交易哈希值后立刻触发
"receipt" 返回Object: 当交易收据有效后立刻触发
"confirmation" 返回Number, Object: 在每次确认后立刻触发,最多12次确认。确认编号为第一个参数,收据为第二个参数。从0号确认开始触发
"error" 返回Error对象: 在发送交易的过程中如果出现错误则立刻触发。如果是out of gas错误,则传入第二个参数为交易收据
Example_1:含部署智能合约方法
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
// compiled solidity source code using https://remix.ethereum.org
var code = "0x603d80600c6000396000f3007c01000000000000000000000000000000000000000000000000000000006000350463c6888fa18114602d57005b6007600435028060005260206000f3";
// using the callback
web3.eth.sendTransaction({
from: '0x38D8B866a1ABeBcA20AFC004622F5355EeFEB568', // personal.unlockAccount("0x38D8B866a1ABeBcA20AFC004622F5355EeFEB568","password",300)
data: code // deploying a contracrt
}, function(error, hash){
if (!error){
console.log("succeed: ", hash);
return hash;
}else{
console.log("error:", error);
}
});
//0x65f382e52263326754b62907efb85aa40ed2e6fedd3d27f7e40f702320f9e2f2
Example_2:含交易eth方法
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
// using the promise
web3.eth.sendTransaction({
from: '0x38D8B866a1ABeBcA20AFC004622F5355EeFEB568',
to: '0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe',
value: '1000000000000000'
})
.then(function(receipt){
console.log(receipt);
});
/*
{ blockHash:
'0xe05057c39222457f99c52936ef4af94d72b27a6e5bc7c6486c7fb84302271fa6',
blockNumber: 215553,
contractAddress: null,
cumulativeGasUsed: 21000,
from: '0x38d8b866a1abebca20afc004622f5355eefeb568',
gasUsed: 21000,
logs: [],
logsBloom:
'0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
status: true,
to: '0x11f4d0a3c12e86b4b5f39b213f7e19d048276dae',
transactionHash:
'0xf15d2e516ec5b3615ed2735fca88c92d602ea6a9cfde8ea47ffcdeb31a4682d2',
transactionIndex: 0 }
*/
Example_3:含区块确认
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
// using the event emitter
web3.eth.sendTransaction({
from: '0x38D8B866a1ABeBcA20AFC004622F5355EeFEB568',
to: '0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe',
value: '1000000000000000'
})
.on('transactionHash', function(hash){
console.log(hash);
})
.on('receipt', function(receipt){
console.log(receipt);
})
.on('confirmation', function(confirmationNumber, receipt){
console.log(confirmationNumber);
})
.on('error', console.error); // If a out of gas error, the second parameter is the receipt.
/*
0x925a4f5459601fa7bdfb240a370e8090243901a5fc276d6f0408c6c91201f311
0
{ blockHash:
'0x73fbe08a69232deecd5307ec0b8c8c09460c8bbb0ab6edab98379e158fa653b6',
blockNumber: 215617,
contractAddress: null,
cumulativeGasUsed: 21000,
from: '0x38d8b866a1abebca20afc004622f5355eefeb568',
gasUsed: 21000,
logs: [],
logsBloom:
'0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
status: true,
to: '0x11f4d0a3c12e86b4b5f39b213f7e19d048276dae',
transactionHash:
'0x925a4f5459601fa7bdfb240a370e8090243901a5fc276d6f0408c6c91201f311',
transactionIndex: 0 }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
*/
web3.eth.sendSignedTransaction(signedTransactionData [, callback])
用来发送已经签名的交易。可以使用web3.eth.accounts.signTransaction()
方法进行签名。
Parameters
returns
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
// 请安装[email protected];因为[email protected]版会报错:"(node:10440) UnhandledPromiseRejectionWarning: Error: Returned error: invalid sender"
// var Tx = require('ethereumjs-tx').Transaction; // 原文如此,使用版本[email protected]时取消.Transaction
var Tx = require('ethereumjs-tx');
var privateKey = Buffer.from('a6fe45540000bd3fed9a4794166577b6e62eb674004edc22a6554630d8515654', 'hex');
var rawTx = {
nonce: '0x15',
gasPrice: '0x09184e72a000000', // 本文实际测试时该值有增加,因为报错"(node:10520) UnhandledPromiseRejectionWarning: Error: Returned error: intrinsic gas too low"
gasLimit: '0x27100', // 本文实际测试时该值有增加,因为报错"(node:10520) UnhandledPromiseRejectionWarning: Error: Returned error: intrinsic gas too low"
to: '0x0297a8913cc187d60712f095a7e1bf2421bfcd40',
value: '0x100',
data: '0x010203040506070809'
}
var tx = new Tx(rawTx,{'chain':'ropsten'});
tx.sign(privateKey);
var serializedTx = tx.serialize();
console.log(serializedTx.toString('hex'));
// f87213879184e72b00000083027200940297a8913cc187d60712f095a7e1bf2421bfcd40820100890102030405060708091ca0e2bafcccd3215da81fa21075d52f80ce26abf82f81566bfc6e69f3b75cfc6461a050738216f3088587caa14bb7578923b21bd969a5ccd7b2a77bcc7f4581e0ffe3
web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'))
.on('receipt', console.log);
/*
{ blockHash:
'0x86048b8c11f9d63eb9eaaa2df01df561d6ba29245bd8ba9b273a09473f174458',
blockNumber: 223581,
contractAddress: null,
cumulativeGasUsed: 21144,
from: '0x38d8b866a1abebca20afc004622f5355eefeb568',
gasUsed: 21144,
logs: [],
logsBloom:
'0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
status: true,
to: '0x0297a8913cc187d60712f095a7e1bf2421bfcd40',
transactionHash:
'0xe467cc585d2aefd9479b0ba54228e13f4150651294fe8dc597907f5b2697fe4d',
transactionIndex: 0 }
*/
自动获取nonce并发送签名交易:
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
//请安装[email protected];因为[email protected]版会报错:"(node:10440) UnhandledPromiseRejectionWarning: Error: Returned error: invalid sender"
//var Tx = require('ethereumjs-tx').Transaction; //原文如此,使用版本[email protected]时取消.Transaction
var Tx = require('ethereumjs-tx');
var privateKey = Buffer.from('a6fe45540000bd3fed9a4794166577b6e62eb674004edc22a6554630d8515654', 'hex');
//私钥对应的账号地地址
const account = web3.eth.accounts.privateKeyToAccount("a6fe45540000bd3fed9a4794166577b6e62eb674004edc22a6554630d8515654");
const address = account.address;
console.log("address: ",address);
//address: 0x38D8B866a1ABeBcA20AFC004622F5355EeFEB568
web3.eth.getTransactionCount(address,function(error, result){
if(!error){
//If no error occurred, return result
var nonce = result;
console.log('nonce :',nonce);
var rawTx = {
nonce: nonce,
gasPrice: '0x09184e72a000000', //本文实际测试时该值有增加,因为报错"(node:10520) UnhandledPromiseRejectionWarning: Error: Returned error: intrinsic gas too low"
gasLimit: '0x27100', //本文实际测试时该值有增加,因为报错"(node:10520) UnhandledPromiseRejectionWarning: Error: Returned error: intrinsic gas too low"
to: '0x0297a8913cc187d60712f095a7e1bf2421bfcd40',
value: '0x100',
data: '0x010203040506070809'
}
var tx = new Tx(rawTx,{'chain':'ropsten'});
tx.sign(privateKey);
var serializedTx = tx.serialize();
console.log(serializedTx.toString('hex'));
web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'))
.on('receipt', console.log);
}
else
//If an error occurred, handle it (throw, etc)
console.error(error);
})
web3.eth.sign(dataToSign, address [, callback])
用指定的账户对数据进行签名,该账户必须先解锁。
Parameters
String :dataToSign- 待签名的数据。对于字符串将首先使用web3.utils.utf8ToHex()
方法将其转换为16进制
String|Number :address- 用来签名的账户地址。或者本地钱包web3.eth.accounts.wallet中的地址或其序号
returns
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.sign("Hello world", "0x38D8B866a1ABeBcA20AFC004622F5355EeFEB568").then(console.log);
//0x553774cd3dccf9a5113d4a78a3c267c6dbeeecac719283924fdd0c5d420573d752e7679aafdc14f04c96c952fea622773def64f3e641f906dd221706537bba731b
// the below is the same
web3.eth.sign(web3.utils.utf8ToHex("Hello world"), "0x38D8B866a1ABeBcA20AFC004622F5355EeFEB568").then(console.log);
//0x553774cd3dccf9a5113d4a78a3c267c6dbeeecac719283924fdd0c5d420573d752e7679aafdc14f04c96c952fea622773def64f3e641f906dd221706537bba731b
web3.eth.signTransaction(transactionObject, address [, callback])
对交易进行签名,用来签名的账户地址需要首先解锁。
Parameters
Object :transactionObject- 要签名的交易数据
String :address- 用于签名的账户地址
returns
web3.eth.sendSignedTransaction()
方法来发送交易。Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.signTransaction({
nonce: '25',
from: "0x38D8B866a1ABeBcA20AFC004622F5355EeFEB568",
gasPrice: "20000000000",
gas: "21000",
to: "0x0297a8913cc187d60712f095a7e1bf2421bfcd40",
value: "100",
data: ""
}).then(console.log);
/*
{ raw:
'0xf865198504a817c800825208940297a8913cc187d60712f095a7e1bf2421bfcd40648082042ea0f3f0de7828a76cf9b06459b5c4fda4a26cb3101bf9441d43c71c8c5790e5867e9fe0cc9821a8811ed111176fe92ef4304a1f1f3e9ee8bd1ebf9ee519ae484c0a',
tx:
{ nonce: '0x19',
gasPrice: '0x4a817c800',
gas: '0x5208',
to: '0x0297a8913cc187d60712f095a7e1bf2421bfcd40',
value: '0x64',
input: '0x',
v: '0x42e',
r:
'0xf3f0de7828a76cf9b06459b5c4fda4a26cb3101bf9441d43c71c8c5790e5867e',
s:
'0xe0cc9821a8811ed111176fe92ef4304a1f1f3e9ee8bd1ebf9ee519ae484c0a',
hash:
'0x27b4b94ca62e04f3ac470b77bc2a2118d531f8be318e2c99a4bce14a123102b6' } }
*/
web3.eth.call(callObject [, defaultBlock] [, callback])
执行一个消息调用交易,消息调用交易直接在节点EVM中执行,而不需要通过区块链的挖矿来执行。
Parameters
Object :callObject- 交易对象,消息调用交易的from属性可选
Number|String :defaultBlock- 可选,使用该参数来覆盖默认的web3.eth.defaultBlock属性值
returns
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.call({
to: "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", // contract address
data: "0xc6888fa10000000000000000000000000000000000000000000000000000000000000003"
})
.then(console.log);
// "0x000000000000000000000000000000000000000000000000000000000000000a"
web3.eth.getChainId([callback])
当前连接的节点的chainId;有时叫networkId。
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.getChainId().then(console.log); //517
web3.eth.getNodeInfo([callback])
节点信息。
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.getNodeInfo().then(console.log);
//Geth/v1.9.14-stable-6d74d1e5/windows-amd64/go1.14.2
web3.eth.getProof(address, storageKey, blockNumber, [callback])
返回指定帐户和存储值,包括EIP-1186中描述的Merkle证明。
Parameters
String 20 Bytes: 账号地址或合约地址
Number[] | BigNumber[] | BN[] | String[] 32 Bytes: 存储-键值对列表
Number | String | BN | BigNumber: 区块号,可以是"latest", "earliest", 或 "genesis"
returns
对象 - 一个账号对象
address - String: 账号地址
balance - String: 账号余额
codeHash - String: code的哈希值
nonce - String: 账号Nonce值,交易数量
storageHash - String: 存储根测SHA3值,所有存储都将从这个根哈希开始提供merkle证明
accountProof - String[]: rlp序列化的Merkle树节点的数组,从状态根节点开始,以SHA3(地址)的路径作为键值
storageProof - Object[] :请求的存储项数组
Example
var Web3= require('web3');
var web3= new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.getProof(
"0x38D8B866a1ABeBcA20AFC004622F5355EeFEB568",
["0x0000000000000000000000000000000000000000000000000000000000000000","0x0000000000000000000000000000000000000000000000000000000000000001"],
"latest"
).then(console.log);
/*
{ address: '0x38D8B866a1ABeBcA20AFC004622F5355EeFEB568',
accountProof:
[ '0xf90131a0d67d35b003bcf010b083b765b273c337a14a6f349828815112dcdec77f2571a280a045e72ac735382c4fa9f7a176f34448c5bac9b920786dfbf612a49e2fdb0f8717a031c1eb791903907c7a0a876b796458f535aa769e361c54a933b457fcdf03dba780a0f797a10951c333c988e967204721aa436a78964c02bb5153b3897bbc3a3ca91c80a044b2fccca4176a61f8e360a6d94acc65490336e51f1678e1a85fceb9d67923aa80a0026e45a01956f0c2c0e847b02d200c1522e1fe5303ce31012c48c9db52b6c18080a06cb01cdb809d58854f932a278a58c255f7cadafbf87852f650ca363040e514db80a0ced141fc6a4a9247aa66bd8f8e724b6edf66c8d2fac6de056e051a69e7316425a0854ff34e11b0f6053ed6741da516fea9384c80d77509fc041b5e50548d08223a8080',
'0xf873a0328d3473fa6a5032862dd15a1b9bba23613feb4ca64593dac016c16a028e1316b850f84e198ad278fe7c4a012aede200a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a0c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470' ],
balance: '993928908304622262542848',
codeHash:
'0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470',
nonce: '25',
storageHash:
'0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421',
storageProof:
[ { key: '0x0', value: '0x0', proof: [] },
{ key: '0x1', value: '0x0', proof: [] } ] }
*/