0%

web3.js的基本使用

基本介绍

• web3.js 是一个JavaScript API库。要使DApp在以太坊上运行,我们可以使用web3.js库提供的web3对象

• web3.js 通过RPC调用与本地节点通信,它可以用于任何暴露了RPC层的以太坊节点

基本使用

设置Provider

1
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));

获取账户

web3.eth.defaultAccount

web3.eth.getTransaction() 获取具有指定哈希值的交易对象。

入参:交易的哈希值,回调函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// web3.eth.getTransaction(transactionHash [, callback])

web3.eth.getTransaction('0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b§234')
.then(console.log);
> {
"hash": "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b",
"nonce": 2,
"blockHash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46",
"blockNumber": 3,
"transactionIndex": 0,
"from": "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b",
"to": "0x6295ee1b4f6dd65047762f924ecd367c17eabf8f",
"value": '123450000000000000',
"gas": 314159,
"gasPrice": '2000000000000',
"input": "0x57cb2fc4"
}

web3.eth.sendTransaction – 发送交易

web3.eth.sendTransaction()方法向以太坊网络提交一个交易。
入参:transactionObject

1
2
3
4
5
6
7
8
{
from: 我的交易地址,
to: 目标地址,
value: 交易价值,
gas: gas总量,
gasPrice: gas加个,
data: 合约方法数据
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// web3.eth.sendTransaction(transactionObject [, callback])

web3.eth.sendTransaction({
from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe',
to: '0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe',
value: '1000000000000000'
})
// 在交易发出并得到有效的交易哈希值后立刻触发
.on('transactionHash', function(hash){
...
})
// 当交易收据有效后立刻触发
.on('receipt', function(receipt){
...
})
// 在每次确认后立刻触发,最多12次
.on('confirmation', function(confirmationNumber, receipt){ ... })
// 交易失败触发
.on('error', console.error);