Web3js Readthedocs Io en v1.10.0
Web3js Readthedocs Io en v1.10.0
js Documentation
Release 1.0.0
1 Getting Started 3
1.1 Adding web3.js . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
3 Glossary 7
3.1 json interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
4 Web3 11
4.1 Web3.modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
4.2 Web3 Instance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
4.3 version . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
4.4 utils . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
4.5 setProvider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
4.6 providers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
4.7 givenProvider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
4.8 currentProvider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
4.9 BatchRequest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
4.10 extend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
5 web3.eth 21
5.1 Note on checksum addresses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
5.2 subscribe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
5.3 Contract . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
5.4 Iban . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
5.5 personal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
5.6 accounts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
5.7 ens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
5.8 abi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
5.9 net . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
5.10 setProvider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
5.11 providers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
5.12 givenProvider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
5.13 currentProvider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
5.14 BatchRequest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
5.15 extend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
5.16 defaultAccount . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
i
5.17 defaultBlock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
5.18 defaultHardfork . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
5.19 defaultChain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
5.20 defaultCommon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
5.21 transactionBlockTimeout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
5.22 blockHeaderTimeout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
5.23 transactionConfirmationBlocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
5.24 transactionPollingTimeout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
5.25 transactionPollingInterval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
5.26 handleRevert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
5.27 maxListenersWarningThreshold . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
5.28 getProtocolVersion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
5.29 isSyncing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
5.30 getCoinbase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
5.31 isMining . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
5.32 getHashrate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
5.33 getGasPrice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
5.34 getFeeHistory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
5.35 getAccounts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
5.36 getBlockNumber . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
5.37 getBalance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
5.38 getStorageAt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
5.39 getCode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
5.40 getBlock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
5.41 getBlockTransactionCount . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
5.42 getBlockUncleCount . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
5.43 getUncle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
5.44 getTransaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
5.45 getPendingTransactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
5.46 getTransactionFromBlock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
5.47 getTransactionReceipt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
5.48 getTransactionCount . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
5.49 sendTransaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
5.50 sendSignedTransaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
5.51 sign . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
5.52 signTransaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
5.53 call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
5.54 estimateGas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
5.55 getPastLogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
5.56 getWork . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
5.57 submitWork . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
5.58 requestAccounts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
5.59 getChainId . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
5.60 getNodeInfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
5.61 getProof . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
5.62 createAccessList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
6 web3.eth.subscribe 65
6.1 subscribe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
6.2 clearSubscriptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
6.3 subscribe(“pendingTransactions”) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
6.4 subscribe(“newBlockHeaders”) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
6.5 subscribe(“syncing”) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
6.6 subscribe(“logs”) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
ii
7 web3.eth.Contract 73
7.1 new contract . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
7.2 = Properties = . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
7.3 defaultAccount . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
7.4 defaultBlock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
7.5 defaultHardfork . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
7.6 defaultChain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
7.7 defaultCommon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
7.8 transactionBlockTimeout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
7.9 blockHeaderTimeout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
7.10 transactionConfirmationBlocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
7.11 transactionPollingTimeout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
7.12 transactionPollingInterval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
7.13 handleRevert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
7.14 options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
7.15 options.address . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
7.16 options.jsonInterface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
7.17 = Methods = . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
7.18 clone . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
7.19 deploy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
7.20 methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
7.21 methods.myMethod.call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
7.22 methods.myMethod.send . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
7.23 methods.myMethod.estimateGas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
7.24 methods.myMethod.encodeABI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
7.25 methods.myMethod.createAccessList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
7.26 = Events = . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
7.27 once . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
7.28 events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
7.29 events.allEvents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
7.30 getPastEvents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
8 web3.eth.accounts 97
8.1 create . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
8.2 privateKeyToAccount . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
8.3 signTransaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
8.4 recoverTransaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
8.5 hashMessage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
8.6 sign . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
8.7 recover . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
8.8 encrypt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
8.9 decrypt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
8.10 wallet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
8.11 wallet.create . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
8.12 wallet.add . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
8.13 wallet.remove . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
8.14 wallet.clear . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
8.15 wallet.encrypt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
8.16 wallet.decrypt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
8.17 wallet.save . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
8.18 wallet.load . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
9 web3.eth.personal 115
9.1 setProvider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
iii
9.2 providers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
9.3 givenProvider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
9.4 currentProvider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
9.5 BatchRequest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
9.6 extend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
9.7 newAccount . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
9.8 sign . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
9.9 ecRecover . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
9.10 signTransaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
9.11 sendTransaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
9.12 unlockAccount . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
9.13 lockAccount . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
9.14 getAccounts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
9.15 importRawKey . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
10 web3.eth.ens 129
10.1 registryAddress . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
10.2 registry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
10.3 resolver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
10.4 getResolver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
10.5 setResolver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
10.6 getOwner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
10.7 setOwner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
10.8 getTTL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
10.9 setTTL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
10.10 setSubnodeOwner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
10.11 setRecord . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
10.12 setSubnodeRecord . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
10.13 setApprovalForAll . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
10.14 isApprovedForAll . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
10.15 recordExists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
10.16 getAddress . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
10.17 setAddress . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
10.18 getPubkey . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
10.19 setPubkey . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
10.20 getContent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
10.21 setContent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
10.22 getContenthash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
10.23 setContenthash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
10.24 getMultihash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
10.25 supportsInterface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
10.26 setMultihash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
10.27 ENS events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
11 web3.eth.Iban 151
11.1 Iban instance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
11.2 Iban contructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
11.3 toAddress . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
11.4 toIban . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
11.5 fromAddress . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
11.6 fromBban . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
11.7 createIndirect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
11.8 isValid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
11.9 prototype.isValid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
iv
11.10 prototype.isDirect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
11.11 prototype.isIndirect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
11.12 prototype.checksum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
11.13 prototype.institution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
11.14 prototype.client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
11.15 prototype.toAddress . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
11.16 prototype.toString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
12 web3.eth.abi 161
12.1 encodeFunctionSignature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
12.2 encodeEventSignature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
12.3 encodeParameter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
12.4 encodeParameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
12.5 encodeFunctionCall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
12.6 decodeParameter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
12.7 decodeParameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
12.8 decodeLog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
13 web3.*.net 171
13.1 getId . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
13.2 isListening . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
13.3 getPeerCount . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
14 web3.bzz 175
14.1 setProvider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
14.2 givenProvider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
14.3 currentProvider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
14.4 upload . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
14.5 download . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
14.6 pick . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
15 web3.shh 181
15.1 setProvider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
15.2 providers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
15.3 givenProvider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
15.4 currentProvider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
15.5 BatchRequest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
15.6 extend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
15.7 getId . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
15.8 isListening . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
15.9 getPeerCount . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
15.10 getVersion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
15.11 getInfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
15.12 setMaxMessageSize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
15.13 setMinPoW . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
15.14 markTrustedPeer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
15.15 newKeyPair . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
15.16 addPrivateKey . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
15.17 deleteKeyPair . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
15.18 hasKeyPair . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
15.19 getPublicKey . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
15.20 getPrivateKey . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
15.21 newSymKey . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
15.22 addSymKey . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
15.23 generateSymKeyFromPassword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
v
15.24 hasSymKey . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
15.25 getSymKey . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
15.26 deleteSymKey . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
15.27 post . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
15.28 subscribe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
15.29 clearSubscriptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
15.30 newMessageFilter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
15.31 deleteMessageFilter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
15.32 getFilterMessages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
16 web3.utils 205
16.1 Bloom Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
16.2 randomHex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
16.3 BN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
16.4 isBN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
16.5 isBigNumber . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
16.6 sha3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
16.7 sha3Raw . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
16.8 soliditySha3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
16.9 soliditySha3Raw . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
16.10 isHex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
16.11 isHexStrict . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
16.12 isAddress . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
16.13 toChecksumAddress . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
16.14 checkAddressChecksum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
16.15 toHex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
16.16 stripHexPrefix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
16.17 toBN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
16.18 hexToNumberString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
16.19 hexToNumber . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
16.20 numberToHex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
16.21 hexToUtf8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
16.22 hexToAscii . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
16.23 utf8ToHex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
16.24 asciiToHex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
16.25 hexToBytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
16.26 bytesToHex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
16.27 toWei . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
16.28 fromWei . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
16.29 unitMap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
16.30 padLeft . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
16.31 padRight . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
16.32 toTwosComplement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
Index 229
vi
web3.js Documentation, Release 1.0.0
web3.js is a collection of libraries that allow you to interact with a local or remote ethereum node using HTTP, IPC or
WebSocket.
The following documentation will guide you through installing and running web3.js as well as providing an API
reference documentation with examples.
Note: Web3.js 4.x has been released. Checkout 4.x API documentation and migration guide for testing, early feedback
and contributions.
Contents:
Keyword Index, Search Page
User Documentation 1
web3.js Documentation, Release 1.0.0
2 User Documentation
CHAPTER 1
Getting Started
The web3.js library is a collection of modules that contain functionality for the ethereum ecosystem.
• web3-eth is for the ethereum blockchain and smart contracts.
• web3-shh is for the whisper protocol, to communicate p2p and broadcast.
• web3-bzz is for the swarm protocol, the decentralized file storage.
• web3-utils contains useful helper functions for Dapp developers.
First you need to get web3.js into your project. This can be done using the following methods:
• npm: npm install web3
• yarn: yarn add web3
• pure js: link the dist/web3.min.js
After that you need to create a web3 instance and set a provider.
Most Ethereum-supported browsers like MetaMask have an EIP-1193 compliant provider available at window.
ethereum.
For web3.js, check Web3.givenProvider.
If this property is null you should connect to a remote/local node.
3
web3.js Documentation, Release 1.0.0
To help web3 integrate into all kinds of projects with different standards we provide multiple ways to act on asyn-
chronous functions.
Most web3.js objects allow a callback as the last parameter, as well as returning promises to chain functions.
Ethereum as a blockchain has different levels of finality and therefore needs to return multiple “stages” of an action.
To cope with this requirement we return a “promiEvent” for functions like web3.eth.sendTransaction or
contract methods. This “promiEvent” is a promise combined with an event emitter to allow acting on different stages
of action on the blockchain, like a transaction.
PromiEvents work like a normal promises with added on, once and off functions. This way developers can watch
for additional events like on “receipt” or “transactionHash”.
5
web3.js Documentation, Release 1.0.0
Glossary
The json interface is a json object describing the Application Binary Interface (ABI) for an Ethereum smart contract.
Using this json interface web3.js is able to create JavaScript object representing the smart contract and its methods and
events using the web3.eth.Contract object.
3.1.1 Specification
Functions:
• type: "function", "constructor" (can be omitted, defaulting to "function"; "fallback" also
possible but not relevant in web3.js);
• name: the name of the function (only present for function types);
• constant: true if function is specified to not modify the blockchain state;
• payable: true if function accepts ether, defaults to false;
• stateMutability: a string with one of the following values: pure (specified to not read blockchain state),
view (same as constant above), nonpayable and payable (same as payable above);
• inputs: an array of objects, each of which contains:
– name: the name of the parameter;
– type: the canonical type of the parameter.
• outputs: an array of objects same as inputs, can be omitted if no outputs exist.
Events:
• type: always "event"
7
web3.js Documentation, Release 1.0.0
3.1.2 Example
"anonymous": false,
},
{
"type": "event"
"name": "Event2",
"inputs": [{"indexed":true,"internalType":"uint256","name":"b","type":"uint256
˓→"},{"indexed":false,"internalType":"bytes32","name":"c","type":"bytes32"}],
"anonymous": false,
},
{
"type": "function"
"name": "foo",
"stateMutability": "nonpayable",
"inputs": [{"internalType":"uint256","name":"b","type":"uint256"},{
˓→"internalType":"bytes32","name":"c","type":"bytes32"}],
(continues on next page)
8 Chapter 3. Glossary
web3.js Documentation, Release 1.0.0
10 Chapter 3. Glossary
CHAPTER 4
Web3
> Web3.utils
> Web3.version
> Web3.givenProvider
> Web3.providers
> Web3.modules
4.1 Web3.modules
Web3.modules
Will return an object with the classes of all major sub modules, to be able to instantiate them manually.
4.1.1 Returns
11
web3.js Documentation, Release 1.0.0
4.1.2 Example
Web3.modules
> {
Eth: Eth(provider),
Net: Net(provider),
Personal: Personal(provider),
Shh: Shh(provider),
Bzz: Bzz(provider),
}
The Web3 class is an umbrella package to house all Ethereum related modules.
> web3.eth
> web3.shh
> web3.bzz
> web3.utils
> web3.version
4.3 version
Static accessible property of the Web3 class and property of the instance as well.
Web3.version
web3.version
4.3.1 Returns
4.3.2 Example
web3.version;
> "1.2.3"
12 Chapter 4. Web3
web3.js Documentation, Release 1.0.0
4.4 utils
Static accessible property of the Web3 class and property of the instance as well.
Web3.utils
web3.utils
Utility functions are also exposed on the Web3 class object directly.
See web3.utils for more.
4.5 setProvider
web3.setProvider(myProvider)
web3.eth.setProvider(myProvider)
web3.shh.setProvider(myProvider)
web3.bzz.setProvider(myProvider)
...
Note: When called on the umbrella package web3 it will also set the provider for all sub modules web3.eth,
web3.shh, etc. EXCEPT web3.bzz which needs a separate provider at all times.
4.5.1 Parameters
4.5.2 Returns
Boolean
// change provider
web3.setProvider('ws://localhost:8546');
// or
web3.setProvider(new Web3.providers.WebsocketProvider('ws://localhost:8546'));
4.4. utils 13
web3.js Documentation, Release 1.0.0
4.6 providers
web3.providers
web3.eth.providers
web3.shh.providers
web3.bzz.providers
...
4.6.1 Value
4.6.2 Example
14 Chapter 4. Web3
web3.js Documentation, Release 1.0.0
4.6.3 Configuration
// ====
// Http
// ====
var options = {
keepAlive: true,
withCredentials: false,
timeout: 20000, // ms
headers: [
{
name: 'Access-Control-Allow-Origin',
value: '*'
},
{
...
}
],
agent: {
http: http.Agent(...),
baseUrl: ''
}
};
// ==========
// Websockets
// ==========
var options = {
timeout: 30000, // ms
clientConfig: {
// Useful if requests are large
maxReceivedFrameSize: 100000000, // bytes - default: 1MiB
maxReceivedMessageSize: 100000000, // bytes - default: 8MiB
4.6. providers 15
web3.js Documentation, Release 1.0.0
More information for the Http and Websocket provider modules can be found here:
• HttpProvider
• WebsocketProvider
4.7 givenProvider
web3.givenProvider
web3.eth.givenProvider
web3.shh.givenProvider
web3.bzz.givenProvider
...
When using web3.js in an Ethereum compatible browser, it will set with the current native provider by that browser.
Will return the given provider by the (browser) environment, otherwise null.
4.7.1 Returns
4.7.2 Example
4.8 currentProvider
web3.currentProvider
web3.eth.currentProvider
web3.shh.currentProvider
web3.bzz.currentProvider
...
16 Chapter 4. Web3
web3.js Documentation, Release 1.0.0
4.8.1 Returns
4.8.2 Example
4.9 BatchRequest
new web3.BatchRequest()
new web3.eth.BatchRequest()
new web3.shh.BatchRequest()
new web3.bzz.BatchRequest()
4.9.1 Parameters
none
4.9.2 Returns
4.9.3 Example
batch.add(contract.methods.balance(address).call.request({from:
˓→'0x0000000000000000000000000000000000000000'}, callback2));
batch.execute();
4.10 extend
web3.extend(methods)
web3.eth.extend(methods)
web3.shh.extend(methods)
web3.bzz.extend(methods)
...
4.9. BatchRequest 17
web3.js Documentation, Release 1.0.0
Note: You also have *.extend.formatters as additional formatter functions to be used for input and output
formatting. Please see the source file for function details.
4.10.1 Parameters
1. methods - Object: Extension object with array of methods description objects as follows:
• property - String: (optional) The name of the property to add to the module. If no property is
set it will be added to the module directly.
• methods - Array: The array of method descriptions:
– name - String: Name of the method to add.
– call - String: The RPC method name.
– params - Number: (optional) The number of parameters for that function. Default 0.
– inputFormatter - Array: (optional) Array of inputformatter functions. Each array item
responds to a function parameter, so if you want some parameters not to be formatted, add a
null instead.
– outputFormatter - ``Function: (optional) Can be used to format the output of the
method.
4.10.2 Returns
4.10.3 Example
web3.extend({
property: 'myModule',
methods: [{
name: 'getBalance',
call: 'eth_getBalance',
params: 2,
inputFormatter: [web3.extend.formatters.inputAddressFormatter, web3.extend.
˓→formatters.inputDefaultBlockNumberFormatter],
outputFormatter: web3.utils.hexToNumberString
},{
name: 'getGasPriceSuperFunction',
call: 'eth_gasPriceSuper',
params: 2,
inputFormatter: [null, web3.utils.numberToHex]
}]
});
web3.extend({
methods: [{
name: 'directCall',
call: 'eth_callForFun',
(continues on next page)
18 Chapter 4. Web3
web3.js Documentation, Release 1.0.0
console.log(web3);
> Web3 {
myModule: {
getBalance: function(){},
getGasPriceSuperFunction: function(){}
},
directCall: function(){},
eth: Eth {...},
bzz: Bzz {...},
...
}
4.10. extend 19
web3.js Documentation, Release 1.0.0
20 Chapter 4. Web3
CHAPTER 5
web3.eth
The web3-eth package allows you to interact with an Ethereum blockchain and Ethereum smart contracts.
// -> web3.eth
All Ethereum addresses returned by functions of this package are returned as checksum addresses. This means some
letters are uppercase and some are lowercase. Based on that it will calculate a checksum for the address and prove its
correctness. Incorrect checksum addresses will throw an error when passed into functions. If you want to circumvent
the checksum check you can make an address all lower- or uppercase.
5.1.1 Example
web3.eth.getAccounts(console.log);
> ["0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe" ,
˓→"0x85F43D8a49eeB85d32Cf465507DD71d507100C1d"]
21
web3.js Documentation, Release 1.0.0
5.2 subscribe
5.3 Contract
5.4 Iban
5.5 personal
5.6 accounts
5.7 ens
5.8 abi
22 Chapter 5. web3.eth
web3.js Documentation, Release 1.0.0
5.9 net
5.10 setProvider
web3.setProvider(myProvider)
web3.eth.setProvider(myProvider)
web3.shh.setProvider(myProvider)
web3.bzz.setProvider(myProvider)
...
Note: When called on the umbrella package web3 it will also set the provider for all sub modules web3.eth,
web3.shh, etc. EXCEPT web3.bzz which needs a separate provider at all times.
5.10.1 Parameters
5.10.2 Returns
Boolean
// change provider
web3.setProvider('ws://localhost:8546');
// or
web3.setProvider(new Web3.providers.WebsocketProvider('ws://localhost:8546'));
5.9. net 23
web3.js Documentation, Release 1.0.0
5.11 providers
web3.providers
web3.eth.providers
web3.shh.providers
web3.bzz.providers
...
5.11.1 Value
5.11.2 Example
24 Chapter 5. web3.eth
web3.js Documentation, Release 1.0.0
5.11.3 Configuration
// ====
// Http
// ====
var options = {
keepAlive: true,
withCredentials: false,
timeout: 20000, // ms
headers: [
{
name: 'Access-Control-Allow-Origin',
value: '*'
},
{
...
}
],
agent: {
http: http.Agent(...),
baseUrl: ''
}
};
// ==========
// Websockets
// ==========
var options = {
timeout: 30000, // ms
clientConfig: {
// Useful if requests are large
maxReceivedFrameSize: 100000000, // bytes - default: 1MiB
maxReceivedMessageSize: 100000000, // bytes - default: 8MiB
5.11. providers 25
web3.js Documentation, Release 1.0.0
More information for the Http and Websocket provider modules can be found here:
• HttpProvider
• WebsocketProvider
5.12 givenProvider
web3.givenProvider
web3.eth.givenProvider
web3.shh.givenProvider
web3.bzz.givenProvider
...
When using web3.js in an Ethereum compatible browser, it will set with the current native provider by that browser.
Will return the given provider by the (browser) environment, otherwise null.
5.12.1 Returns
5.12.2 Example
5.13 currentProvider
web3.currentProvider
web3.eth.currentProvider
web3.shh.currentProvider
web3.bzz.currentProvider
...
5.13.1 Returns
26 Chapter 5. web3.eth
web3.js Documentation, Release 1.0.0
5.13.2 Example
5.14 BatchRequest
new web3.BatchRequest()
new web3.eth.BatchRequest()
new web3.shh.BatchRequest()
new web3.bzz.BatchRequest()
5.14.1 Parameters
none
5.14.2 Returns
5.14.3 Example
batch.add(contract.methods.balance(address).call.request({from:
˓→'0x0000000000000000000000000000000000000000'}, callback2));
batch.execute();
5.15 extend
web3.extend(methods)
web3.eth.extend(methods)
web3.shh.extend(methods)
web3.bzz.extend(methods)
...
Note: You also have *.extend.formatters as additional formatter functions to be used for input and output
formatting. Please see the source file for function details.
5.14. BatchRequest 27
web3.js Documentation, Release 1.0.0
5.15.1 Parameters
1. methods - Object: Extension object with array of methods description objects as follows:
• property - String: (optional) The name of the property to add to the module. If no property is
set it will be added to the module directly.
• methods - Array: The array of method descriptions:
– name - String: Name of the method to add.
– call - String: The RPC method name.
– params - Number: (optional) The number of parameters for that function. Default 0.
– inputFormatter - Array: (optional) Array of inputformatter functions. Each array item
responds to a function parameter, so if you want some parameters not to be formatted, add a
null instead.
– outputFormatter - ``Function: (optional) Can be used to format the output of the
method.
5.15.2 Returns
5.15.3 Example
web3.extend({
property: 'myModule',
methods: [{
name: 'getBalance',
call: 'eth_getBalance',
params: 2,
inputFormatter: [web3.extend.formatters.inputAddressFormatter, web3.extend.
˓→formatters.inputDefaultBlockNumberFormatter],
outputFormatter: web3.utils.hexToNumberString
},{
name: 'getGasPriceSuperFunction',
call: 'eth_gasPriceSuper',
params: 2,
inputFormatter: [null, web3.utils.numberToHex]
}]
});
web3.extend({
methods: [{
name: 'directCall',
call: 'eth_callForFun',
}]
});
console.log(web3);
> Web3 {
myModule: {
getBalance: function(){},
getGasPriceSuperFunction: function(){}
(continues on next page)
28 Chapter 5. web3.eth
web3.js Documentation, Release 1.0.0
5.16 defaultAccount
web3.eth.defaultAccount
This default address is used as the default "from" property, if no "from" property is specified in for the following
methods:
• web3.eth.sendTransaction()
• web3.eth.call()
• new web3.eth.Contract() -> myContract.methods.myMethod().call()
• new web3.eth.Contract() -> myContract.methods.myMethod().send()
5.16.1 Property
String - 20 Bytes: Any ethereum address. You should have the private key for that address in your node or keystore.
(Default is undefined)
5.16.2 Example
web3.eth.defaultAccount;
> undefined
5.17 defaultBlock
web3.eth.defaultBlock
The default block is used for certain methods. You can override it by passing in the defaultBlock as last parameter.
The default value is "latest".
• web3.eth.getBalance()
• web3.eth.getCode()
5.16. defaultAccount 29
web3.js Documentation, Release 1.0.0
• web3.eth.getTransactionCount()
• web3.eth.getStorageAt()
• web3.eth.call()
• new web3.eth.Contract() -> myContract.methods.myMethod().call()
5.17.1 Property
5.17.2 Example
web3.eth.defaultBlock;
> "latest"
5.18 defaultHardfork
web3.eth.defaultHardfork
5.18.1 Property
30 Chapter 5. web3.eth
web3.js Documentation, Release 1.0.0
• "byzantium" - String
• "constantinople" - String
• "petersburg" - String
• "istanbul" - String
• "berlin" - String
• "london" - String
Default is "london"
5.18.2 Example
web3.eth.defaultHardfork;
> "london"
5.19 defaultChain
web3.eth.defaultChain
5.19.1 Property
5.19.2 Example
web3.eth.defaultChain;
> "mainnet"
5.19. defaultChain 31
web3.js Documentation, Release 1.0.0
5.20 defaultCommon
web3.eth.defaultCommon
5.20.1 Property
The default common property does contain the following Common object:
• customChain - Object: The custom chain properties
– name - string: (optional) The name of the chain
– networkId - number: Network ID of the custom chain
– chainId - number: Chain ID of the custom chain
• baseChain - string: (optional) mainnet, goerli, kovan, rinkeby, or ropsten
• hardfork - string: (optional) chainstart, homestead, dao, tangerineWhistle,
spuriousDragon, byzantium, constantinople, petersburg, istanbul, berlin, or london
Default is undefined.
5.20.2 Example
web3.eth.defaultCommon;
> {customChain: {name: 'custom-network', chainId: 1, networkId: 1}, baseChain:
˓→'mainnet', hardfork: 'petersburg'}
5.21 transactionBlockTimeout
web3.eth.transactionBlockTimeout
The transactionBlockTimeout is used over socket-based connections. This option defines the amount of new
blocks it should wait until the first confirmation happens, otherwise the PromiEvent rejects with a timeout error.
5.21.1 Returns
5.21.2 Example
32 Chapter 5. web3.eth
web3.js Documentation, Release 1.0.0
web3.eth.transactionBlockTimeout;
> 50
5.22 blockHeaderTimeout
web3.eth.Contract.blockHeaderTimeout
contract.blockHeaderTimeout // on contract instance
The blockHeaderTimeout is used over socket-based connections. This option defines the amount seconds it
should wait for “newBlockHeaders” event before falling back to polling to fetch transaction receipt.
5.22.1 Returns
5.22.2 Example
web3.eth.blockHeaderTimeout;
> 5
5.23 transactionConfirmationBlocks
web3.eth.transactionConfirmationBlocks
This defines the number of blocks it requires until a transaction is considered confirmed.
5.23.1 Returns
5.23.2 Example
web3.eth.transactionConfirmationBlocks;
> 24
5.22. blockHeaderTimeout 33
web3.js Documentation, Release 1.0.0
5.24 transactionPollingTimeout
web3.eth.transactionPollingTimeout
The transactionPollingTimeout is used over HTTP connections. This option defines the number of seconds
Web3 will wait for a receipt which confirms that a transaction was mined by the network. Note: If this method times
out, the transaction may still be pending.
5.24.1 Returns
5.24.2 Example
web3.eth.transactionPollingTimeout;
> 750
5.25 transactionPollingInterval
web3.eth.transactionPollingInterval
The transactionPollingInterval is used over HTTP connections. This option defines the number of seconds
between Web3 calls for a receipt which confirms that a transaction was mined by the network.
5.25.1 Returns
5.26 handleRevert
web3.eth.handleRevert
The handleRevert options property defaults to false and returns the revert reason string if enabled for the
following methods:
• web3.eth.call()
• web3.eth.sendTransaction()
• contract.methods.myMethod(. . . ).send(. . . )
• contract.methods.myMethod(. . . ).call(. . . )
34 Chapter 5. web3.eth
web3.js Documentation, Release 1.0.0
Note: The revert reason string and signature exist as a property on the returned error.
5.26.1 Returns
5.26.2 Example
web3.eth.handlRevert;
> false
5.27 maxListenersWarningThreshold
web3.eth.maxListenersWarningThreshold
This defines the threshold above which a warning about the number of event listeners attached to a provider which
supports sockets subscriptions will be written to the console. You may see this warning if you call setProvider on
large numbers of Web3 contract objects.
5.27.1 Returns
5.27.2 Example
web3.eth.maxListenersWarningThreshold;
> 100
5.28 getProtocolVersion
web3.eth.getProtocolVersion([callback])
5.27. maxListenersWarningThreshold 35
web3.js Documentation, Release 1.0.0
5.28.1 Returns
5.28.2 Example
web3.eth.getProtocolVersion()
.then(console.log);
> "63"
5.29 isSyncing
web3.eth.isSyncing([callback])
Checks if the node is currently syncing and returns either a syncing object, or false.
5.29.1 Returns
Promise returns Object|Boolean - A sync object when the node is currently syncing or false:
• startingBlock - Number: The block number where the sync started.
• currentBlock - Number: The block number where the node is currently synced to.
• highestBlock - Number: The estimated block number to sync to.
• knownStates - Number: The number of estimated states to download.
• pulledStates - Number: The number of already downloaded states.
5.29.2 Example
web3.eth.isSyncing()
.then(console.log);
> {
startingBlock: 100,
currentBlock: 312,
highestBlock: 512,
knownStates: 234566,
pulledStates: 123455
}
5.30 getCoinbase
36 Chapter 5. web3.eth
web3.js Documentation, Release 1.0.0
getCoinbase([callback])
5.30.1 Returns
Promise returns String - bytes 20: The coinbase address set in the node for mining rewards.
5.30.2 Example
web3.eth.getCoinbase()
.then(console.log);
> "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe"
5.31 isMining
web3.eth.isMining([callback])
5.31.1 Returns
5.31.2 Example
web3.eth.isMining()
.then(console.log);
> true
5.32 getHashrate
web3.eth.getHashrate([callback])
Returns the number of hashes per second that the node is mining with.
5.32.1 Returns
5.31. isMining 37
web3.js Documentation, Release 1.0.0
5.32.2 Example
web3.eth.getHashrate()
.then(console.log);
> 493736
5.33 getGasPrice
web3.eth.getGasPrice([callback])
Returns the current gas price oracle. The gas price is determined by the last few blocks median gas price.
5.33.1 Returns
Promise returns String - Number string of the current gas price in wei.
See the A note on dealing with big numbers in JavaScript.
5.33.2 Example
web3.eth.getGasPrice()
.then(console.log);
> "20000000000"
5.34 getFeeHistory
Transaction fee history Returns base fee per gas and transaction effective priority fee per gas history for the requested
block range if available. The range between headBlock-4 and headBlock is guaranteed to be available while retrieving
data from the pending block and older history are optional to support. For pre-EIP-1559 blocks the gas prices are
returned as rewards and zeroes are returned for the base fee per gas.
5.34.1 Parameters
1. String|Number|BN|BigNumber - Number of blocks in the requested range. Between 1 and 1024 blocks
can be requested in a single query. Less than requested may be returned if not all blocks are available.
2. String|Number|BN|BigNumber - Highest number block of the requested range.
3. Array of numbers - A monotonically increasing list of percentile values to sample from each block’s
effective priority fees per gas in ascending order, weighted by gas used. Example: [“0”, “25”, “50”, “75”,
“100”] or [“0”, “0.5”, “1”, “1.5”, “3”, “80”]
4. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.
38 Chapter 5. web3.eth
web3.js Documentation, Release 1.0.0
5.34.2 Returns
Promise returns Object - Fee history for the returned block range. The object:
• Number oldestBlock - Lowest number block of the returned range.
• Array of strings baseFeePerGas - An array of block base fees per gas. This includes the next block after
the newest of the returned range, because this value can be derived from the newest block. Zeroes are returned
for pre-EIP-1559 blocks.
• Array of numbers gasUsedRatio - An array of block gas used ratios. These are calculated as the ratio of
gasUsed and gasLimit.
• Array of string arrays reward - An array of effective priority fee per gas data points from a single
block. All zeroes are returned if the block is empty.
5.35 getAccounts
web3.eth.getAccounts([callback])
5.35.1 Returns
5.35.2 Example
web3.eth.getAccounts()
.then(console.log);
> ["0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe",
˓→"0xDCc6960376d6C6dEa93647383FfB245CfCed97Cf"]
5.36 getBlockNumber
web3.eth.getBlockNumber([callback])
5.36.1 Returns
5.35. getAccounts 39
web3.js Documentation, Release 1.0.0
5.36.2 Example
web3.eth.getBlockNumber()
.then(console.log);
> 2744
5.37 getBalance
5.37.1 Parameters
5.37.2 Returns
Promise returns String - The current balance for the given address in wei.
See the A note on dealing with big numbers in JavaScript.
5.37.3 Example
web3.eth.getBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1")
.then(console.log);
> "1000000000000"
5.38 getStorageAt
40 Chapter 5. web3.eth
web3.js Documentation, Release 1.0.0
5.38.1 Parameters
5.38.2 Returns
5.38.3 Example
web3.eth.getStorageAt("0x407d73d8a49eeb85d32cf465507dd71d507100c1", 0)
.then(console.log);
> "0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234"
5.39 getCode
5.39.1 Parameters
5.39.2 Returns
5.39.3 Example
web3.eth.getCode("0xd5677cf67b5aa051bb40496e68ad359eb97cfbf8")
.then(console.log);
>
˓→"0x600160008035811a818181146012578301005b601b6001356025565b8060005260206000f25b60006007820290509190
˓→"
5.39. getCode 41
web3.js Documentation, Release 1.0.0
5.40 getBlock
5.40.1 Parameters
5.40.2 Returns
42 Chapter 5. web3.eth
web3.js Documentation, Release 1.0.0
5.40.3 Example
web3.eth.getBlock(3150)
.then(console.log);
> {
"number": 3,
"hash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46",
"parentHash": "0x2302e1c0b972d00932deb5dab9eb2982f570597d9d42504c05d9c2147eaf9c88
˓→",
"baseFeePerGas": 58713056622,
"nonce": "0xfb6e1a62d119228b",
"sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347
˓→",
"logsBloom":
˓→"0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
˓→",
"transactionsRoot":
˓→"0x3a1b03875115b79539e5bd33fb00d8f7b7cd61929d5a3c574f507b8acf415bee",
"stateRoot": "0xf1133199d44695dfa8fd1bcfe424d82854b5cebef75bddd7e40ea94cda515bcb",
"miner": "0x8888f1f195afa192cfee860698584c030f4c9db1",
"difficulty": '21345678965432',
"totalDifficulty": '324567845321',
"size": 616,
"extraData": "0x",
"gasLimit": 3141592,
"gasUsed": 21662,
"timestamp": 1429287689,
"transactions": [
"0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b"
],
"uncles": []
}
5.41 getBlockTransactionCount
web3.eth.getBlockTransactionCount(blockHashOrBlockNumber [, callback])
5.41.1 Parameters
5.41.2 Returns
5.41. getBlockTransactionCount 43
web3.js Documentation, Release 1.0.0
5.41.3 Example
web3.eth.getBlockTransactionCount("0x407d73d8a49eeb85d32cf465507dd71d507100c1")
.then(console.log);
> 1
5.42 getBlockUncleCount
web3.eth.getBlockUncleCount(blockHashOrBlockNumber [, callback])
Returns the number of uncles in a block from a block matching the given block hash.
5.42.1 Parameters
5.42.2 Returns
5.42.3 Example
web3.eth.getBlockUncleCount("0x407d73d8a49eeb85d32cf465507dd71d507100c1")
.then(console.log);
> 1
5.43 getUncle
5.43.1 Parameters
44 Chapter 5. web3.eth
web3.js Documentation, Release 1.0.0
3. Boolean - (optional, default false) If specified true, the returned block will contain all transactions as
objects. By default it is false so, there is no need to explictly specify false. And, if false it will only
contains the transaction hashes.
4. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.
5.43.2 Returns
Promise returns Object - the returned uncle. For a return value see web3.eth.getBlock().
5.43.3 Example
web3.eth.getUncle(500, 0)
.then(console.log);
> // see web3.eth.getBlock
5.44 getTransaction
web3.eth.getTransaction(transactionHash [, callback])
5.44.1 Parameters
5.44.2 Returns
5.44. getTransaction 45
web3.js Documentation, Release 1.0.0
5.44.3 Example
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"
}
5.45 getPendingTransactions
web3.eth.getPendingTransactions([, callback])
5.45.1 Parameters
1. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.
5.45.2 Returns
46 Chapter 5. web3.eth
web3.js Documentation, Release 1.0.0
• gasPrice - String: The wei per unit of gas provided by the sender in wei.
• gas - Number: Gas provided by the sender.
• input - String: The data sent along with the transaction.
5.45.3 Example
web3.eth.getPendingTransactions().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'
v: '0x3d',
r: '0xaabc9ddafffb2ae0bac4107697547d22d9383667d9e97f5409dd6881ce08f13f',
s: '0x69e43116be8f842dcd4a0b2f760043737a59534430b762317db21d9ac8c5034'
},....,{
hash: '0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b',
nonce: 3,
blockHash:
˓→'0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46',
blockNumber: 4,
transactionIndex: 0,
from: '0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b',
to: '0x6295ee1b4f6dd65047762f924ecd367c17eabf8f',
value: '123450000000000000',
gas: 314159,
gasPrice: '2000000000000',
input: '0x57cb2fc4'
v: '0x3d',
r: '0xaabc9ddafffb2ae0bac4107697547d22d9383667d9e97f5409dd6881ce08f13f',
s: '0x69e43116be8f842dcd4a0b2f760043737a59534430b762317db21d9ac8c5034'
}
]
5.46 getTransactionFromBlock
Returns a transaction based on a block hash or number and the transaction’s index position.
5.46. getTransactionFromBlock 47
web3.js Documentation, Release 1.0.0
5.46.1 Parameters
5.46.2 Returns
5.46.3 Example
5.47 getTransactionReceipt
web3.eth.getTransactionReceipt(hash [, callback])
Note: The receipt is not available for pending transactions and returns null.
5.47.1 Parameters
5.47.2 Returns
Promise returns Object - A transaction receipt object, or null if no receipt was found:
• status - Boolean: TRUE if the transaction was successful, FALSE if the EVM reverted the transaction.
• blockHash 32 Bytes - String: Hash of the block where this transaction was in.
• blockNumber - Number (or hex String): Block number where this transaction was in.
• transactionHash 32 Bytes - String: Hash of the transaction.
• transactionIndex- Number (or hex String): Integer of the transactions index position in the block.
48 Chapter 5. web3.eth
web3.js Documentation, Release 1.0.0
5.47.3 Example
.then(console.log);
> {
"status": true,
"transactionHash":
˓→"0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b",
"transactionIndex": 0,
"blockHash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46",
"blockNumber": 3,
"contractAddress": "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe",
"cumulativeGasUsed": 314159,
"gasUsed": 30234,
"logs": [{
// logs as returned by getPastLogs, etc.
}, ...]
}
.then(console.log);
> {
"status": true,
"transactionHash":
˓→"0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b",
"transactionIndex": '0x0',
"blockHash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46",
"blockNumber": '0x3',
"contractAddress": "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe",
"cumulativeGasUsed": '0x4cb2f',
"gasUsed": '0x761a',
"logs": [{
// logs as returned by getPastLogs, etc.
}, ...]
}
5.47. getTransactionReceipt 49
web3.js Documentation, Release 1.0.0
5.48 getTransactionCount
5.48.1 Parameters
5.48.2 Returns
Promise returns Number - The number of transactions sent from the given address.
5.48.3 Example
web3.eth.getTransactionCount("0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe")
.then(console.log);
> 1
5.49 sendTransaction
web3.eth.sendTransaction(transactionObject [, callback])
5.49.1 Parameters
50 Chapter 5. web3.eth
web3.js Documentation, Release 1.0.0
Note: The from property can also be an address or index from the web3.eth.accounts.wallet. It will then sign locally
using the private key of that account, and send the transaction via web3.eth.sendSignedTransaction(). If the properties
chain and hardfork or common are not set, Web3 will try to set appropriate values by querying the network for
its chainId and networkId.
5.49.2 Returns
5.49. sendTransaction 51
web3.js Documentation, Release 1.0.0
• "receipt" returns receipt: Object: Fired when the transaction receipt is available.
• "confirmation" returns confirmationNumber: Number, receipt: Object,
latestBlockHash: String: Fired for every confirmation up to the 12th confirmation. Receives
the confirmation number as the first and the receipt as the second argument. Fired from confirmation 0 on,
which is the block where it’s mined.
"error" returns error: Error: Fired if an error occurs during sending. If the transaction was rejected by the
network with a receipt, the receipt will be available as a property on the error object.
5.49.3 Example
˓→";
52 Chapter 5. web3.eth
web3.js Documentation, Release 1.0.0
5.50 sendSignedTransaction
web3.eth.sendSignedTransaction(signedTransactionData [, callback])
5.50.1 Parameters
5.50.2 Returns
PromiEvent: A promise combined event emitter. Resolves when the transaction receipt is available.
Please see the return values for web3.eth.sendTransaction for details.
5.50.3 Example
var Tx = require('@ethereumjs/tx').Transaction;
var privateKey = Buffer.from(
˓→'e331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109', 'hex');
var rawTx = {
nonce: '0x00',
gasPrice: '0x09184e72a000',
gasLimit: '0x2710',
to: '0x0000000000000000000000000000000000000000',
value: '0x00',
data: '0x7f7465737432000000000000000000000000000000000000000000000000000000600057'
}
// console.log(serializedTx.toString('hex'));
//
˓→0xf889808609184e72a00082271094000000000000000000000000000000000000000080a47f74657374320000000000000
web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'))
.on('receipt', console.log);
Note: When using ethereumjs-tx@2.0.0 if you don’t specify the parameter chain it will use mainnet by default.
5.50. sendSignedTransaction 53
web3.js Documentation, Release 1.0.0
5.51 sign
5.51.1 Parameters
5.51.2 Returns
5.51.3 Example
˓→"
.then(console.log);
>
˓→"0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd
˓→"
5.52 signTransaction
5.52.1 Parameters
54 Chapter 5. web3.eth
web3.js Documentation, Release 1.0.0
5.52.2 Returns
Promise returns Object - The RLP encoded transaction. The raw property can be used to send the transaction
using web3.eth.sendSignedTransaction.
5.52.3 Example
web3.eth.signTransaction({
from: "0xEB014f8c8B418Db6b45774c326A0E64C78914dC0",
gasPrice: "20000000000",
gas: "21000",
to: '0x3535353535353535353535353535353535353535',
value: "1000000000000000000",
data: ""
}).then(console.log);
> {
raw:
˓→'0xf86c808504a817c800825208943535353535353535353535353535353535353535880de0b6b3a76400008025a04f4c17
˓→',
tx: {
nonce: '0x0',
gasPrice: '0x4a817c800',
gas: '0x5208',
to: '0x3535353535353535353535353535353535353535',
value: '0xde0b6b3a7640000',
input: '0x',
v: '0x25',
r: '0x4f4c17305743700648bc4f6cd3038ec6f6af0df73e31757007b7f59df7bee88d',
s: '0x7e1941b264348e80c78c4027afc65a87b0a5e43e86742b8ca0823584c6788fd0',
hash: '0xda3be87732110de6c1354c83770aae630ede9ac308d9f7b399ecfba23d923384'
}
}
5.53 call
Executes a message call transaction, which is directly executed in the VM of the node, but never mined into the
blockchain.
5.53.1 Parameters
1. Object - A transaction object, see web3.eth.sendTransaction. For calls the from property is optional however
it is highly recommended to explicitly set it or it may default to address(0) depending on your node or provider.
2. Number|String|BN|BigNumber - (optional) If you pass this parameter it will not use the default block
set with web3.eth.defaultBlock. Pre-defined block numbers as "earliest", "latest" , "pending",
"safe" or "finalized" can also be used.
3. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.
5.53. call 55
web3.js Documentation, Release 1.0.0
5.53.2 Returns
Promise returns String: The returned data of the call, e.g. a smart contract functions return value.
5.53.3 Example
web3.eth.call({
to: "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", // contract address
data: "0xc6888fa10000000000000000000000000000000000000000000000000000000000000003"
})
.then(console.log);
> "0x000000000000000000000000000000000000000000000000000000000000000a"
5.54 estimateGas
web3.eth.estimateGas(callObject [, callback])
Executes a message call or transaction and returns the amount of the gas used. Note: You must specify a from address
otherwise you may experience odd behavior.
5.54.1 Parameters
1. Object - A transaction object, see web3.eth.sendTransaction with the difference that for calls the from prop-
erty is optional as well.
2. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.
5.54.2 Returns
Promise returns Number - the used gas for the simulated call/transaction.
5.54.3 Example
web3.eth.estimateGas({
to: "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe",
data: "0xc6888fa10000000000000000000000000000000000000000000000000000000000000003"
})
.then(console.log);
> "0x0000000000000000000000000000000000000000000000000000000000000015"
5.55 getPastLogs
56 Chapter 5. web3.eth
web3.js Documentation, Release 1.0.0
web3.eth.getPastLogs(options [, callback])
5.55.1 Parameters
5.55.2 Returns
5.55.3 Example
web3.eth.getPastLogs({
address: "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe",
topics: ["0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234"]
})
.then(console.log);
> [{
data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
˓→'0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385']
logIndex: 0,
transactionIndex: 0,
transactionHash:
˓→'0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
(continues on next page)
5.55. getPastLogs 57
web3.js Documentation, Release 1.0.0
5.56 getWork
web3.eth.getWork([callback])
Gets work for miners to mine on. Returns the hash of the current block, the seedHash, and the boundary condition to
be met (“target”).
5.56.1 Parameters
1. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.
5.56.2 Returns
Promise returns Array - the mining work with the following structure:
• String 32 Bytes - at index 0: current block header pow-hash
• String 32 Bytes - at index 1: the seed hash used for the DAG.
• String 32 Bytes - at index 2: the boundary condition (“target”), 2^256 / difficulty.
5.56.3 Example
web3.eth.getWork()
.then(console.log);
> [
"0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
"0x5EED00000000000000000000000000005EED0000000000000000000000000000",
"0xd1ff1c01710000000000000000000000d1ff1c01710000000000000000000000"
]
5.57 submitWork
58 Chapter 5. web3.eth
web3.js Documentation, Release 1.0.0
5.57.1 Parameters
5.57.2 Returns
Promise returns Boolean - Returns TRUE if the provided solution is valid, otherwise FALSE.
5.57.3 Example
web3.eth.submitWork([
"0x0000000000000001",
"0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
"0xD1FE5700000000000000000000000000D1FE5700000000000000000000000000"
])
.then(console.log);
> true
5.58 requestAccounts
web3.eth.requestAccounts([callback])
This method will request/enable the accounts from the current environment. This method will only work if you’re using
the injected provider from a application like Metamask, Status or TrustWallet. It doesn’t work if you’re connected to
a node with a default Web3.js provider (WebsocketProvider, HttpProvider and IpcProvider).
For more information about the behavior of this method please read EIP-1102: Opt-in account exposure.
5.58.1 Parameters
1. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.
5.58.2 Returns
5.58.3 Example
web3.eth.requestAccounts().then(console.log);
> ['0aae0B295369a9FD31d5F28D9Ec85E40f4cb692BAf',
˓→'0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe']
5.58. requestAccounts 59
web3.js Documentation, Release 1.0.0
5.59 getChainId
web3.eth.getChainId([callback])
Returns the chain ID of the current connected node as described in the EIP-695.
5.59.1 Returns
5.59.2 Example
web3.eth.getChainId().then(console.log);
> 61
5.60 getNodeInfo
web3.eth.getNodeInfo([callback])
5.60.1 Returns
5.60.2 Example
web3.eth.getNodeInfo().then(console.log);
> "Mist/v0.9.3/darwin/go1.4.1"
5.61 getProof
Returns the account and storage-values of the specified account including the Merkle-proof as described in EIP-1186.
5.61.1 Parameters
60 Chapter 5. web3.eth
web3.js Documentation, Release 1.0.0
5.61.2 Returns
5.61.3 Example
web3.eth.getProof(
"0x1234567890123456789012345678901234567890",
["0x0000000000000000000000000000000000000000000000000000000000000000",
˓→"0x0000000000000000000000000000000000000000000000000000000000000001"],
"latest"
).then(console.log);
> {
"address": "0x1234567890123456789012345678901234567890",
"accountProof": [
˓→ "0xf90211a090dcaf88c40c7bbc95a912cbdde67c175767b31173df9ee4b0d733bfdd511c43a0babe369f6b12092f49181a
˓→ ",
˓→ "0xf90211a0395d87a95873cd98c21cf1df9421af03f7247880a2554e20738eec2c7507a494a0bcf6546339a1e7e14eb8fb
˓→ ",
˓→ "0xf90171a04ad705ea7bf04339fa36b124fa221379bd5a38ffe9a6112cb2d94be3a437b879a08e45b5f72e8149c01efcb7
˓→ ",
˓→"0xf851808080a009833150c367df138f1538689984b8a84fc55692d3d41fe4d1e5720ff5483a6980808080808080808080
˓→"
],
"balance": 0,
"codeHash": "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470",
"nonce": 0,
"storageHash": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421
˓→",
(continues on next page)
5.61. getProof 61
web3.js Documentation, Release 1.0.0
"value": '0',
"proof": []
},
{
"key": "0x0000000000000000000000000000000000000000000000000000000000000001
˓→",
"value": '0',
"proof": []
}
]
}
5.62 createAccessList
web3.eth.createAccessList(callObject [, callback])
Will call to create an access list a method execution will access when executed in the EVM. Note: Cur-
rently eth_createAccessList seems to only be supported by Geth. Note: You must specify a from address
and gas if it’s not specified in options when instantiating parent contract object (e.g. new web3.eth.
Contract(jsonInterface[, address][, options])).
5.62.1 Parameters
1. A transaction object, see web3.eth.sendTransaction with the difference that this method is specifically for con-
tract method executions.
2. block - String|Number|BN|BigNumber (optional): The block number or hash. Or the string
"earliest", "latest" , "pending", "safe" or "finalized" as in the default block parameter.
3. callback - Function (optional): This callback will be fired with the result of the access list generation as
the second argument, or with an error object as the first argument.
5.62.2 Returns
62 Chapter 5. web3.eth
web3.js Documentation, Release 1.0.0
5.62.3 Example
web3.eth.createAccessList({
from: '0x3bc5885c2941c5cda454bdb4a8c88aa7f248e312',
data: '0x20965255',
gasPrice: '0x3b9aca00',
gas: '0x3d0900',
to: '0x00f5f5f3a25f142fafd0af24a754fafa340f32c7'
})
.then(console.log);
5.62. createAccessList 63
web3.js Documentation, Release 1.0.0
64 Chapter 5. web3.eth
CHAPTER 6
web3.eth.subscribe
The web3.eth.subscribe function lets you subscribe to specific events in the blockchain.
6.1 subscribe
6.1.1 Parameters
6.1.2 Returns
65
web3.js Documentation, Release 1.0.0
• Mixed - depends on the subscription, see the different subscriptions for more.
6.1.4 Example
6.2 clearSubscriptions
web3.eth.clearSubscriptions()
Resets subscriptions.
Note: This will not reset subscriptions from other packages like web3-shh, as they use their own requestManager.
6.2.1 Parameters
6.2.2 Returns
Boolean
6.2.3 Example
66 Chapter 6. web3.eth.subscribe
web3.js Documentation, Release 1.0.0
...
web3.eth.clearSubscriptions();
6.3 subscribe(“pendingTransactions”)
web3.eth.subscribe('pendingTransactions' [, callback]);
6.3.1 Parameters
6.3.2 Returns
6.3.4 Example
6.3. subscribe(“pendingTransactions”) 67
web3.js Documentation, Release 1.0.0
6.4 subscribe(“newBlockHeaders”)
web3.eth.subscribe('newBlockHeaders' [, callback]);
Subscribes to incoming block headers. This can be used as timer to check for changes on the blockchain.
6.4.1 Parameters
6.4.2 Returns
68 Chapter 6. web3.eth.subscribe
web3.js Documentation, Release 1.0.0
6.4.4 Example
return;
}
console.error(error);
})
.on("connected", function(subscriptionId){
console.log(subscriptionId);
})
.on("data", function(blockHeader){
console.log(blockHeader);
})
.on("error", console.error);
6.5 subscribe(“syncing”)
web3.eth.subscribe('syncing' [, callback]);
Subscribe to syncing events. This will return an object when the node is syncing and when it’s finished syncing will
return FALSE.
6.5.1 Parameters
6.5.2 Returns
6.5. subscribe(“syncing”) 69
web3.js Documentation, Release 1.0.0
6.5.4 Example
6.6 subscribe(“logs”)
Subscribes to incoming logs, filtered by the given options. If a valid numerical fromBlock options property is set,
Web3 will retrieve logs beginning from this point, backfilling the response as necessary.
6.6.1 Parameters
70 Chapter 6. web3.eth.subscribe
web3.js Documentation, Release 1.0.0
3. callback - Function: (optional) Optional callback, returns an error object as first parameter and the result
as second. Will be called for each incoming subscription.
6.6.2 Returns
6.6.4 Example
6.6. subscribe(“logs”) 71
web3.js Documentation, Release 1.0.0
72 Chapter 6. web3.eth.subscribe
CHAPTER 7
web3.eth.Contract
The web3.eth.Contract object makes it easy to interact with smart contracts on the ethereum blockchain. When
you create a new contract object you give it the json interface of the respective smart contract and web3 will auto
convert all calls into low level ABI calls over RPC for you.
This allows you to interact with smart contracts as if they were JavaScript objects.
To use it standalone:
contract.methods.somFunc().send({from: ....})
.on('receipt', function(){
...
});
Creates a new contract instance with all its methods and events defined in its json interface object.
7.1.1 Parameters
73
web3.js Documentation, Release 1.0.0
7.1.2 Returns
Object: The contract instance with all its methods and events.
7.1.3 Example
7.2 = Properties =
7.3 defaultAccount
web3.eth.Contract.defaultAccount
contract.defaultAccount // on contract instance
This default address is used as the default "from" property, if no "from" property is specified in for the following
methods:
• web3.eth.sendTransaction()
• web3.eth.call()
• new web3.eth.Contract() -> myContract.methods.myMethod().call()
• new web3.eth.Contract() -> myContract.methods.myMethod().send()
7.3.1 Property
String - 20 Bytes: Any ethereum address. You should have the private key for that address in your node or keystore.
(Default is undefined)
74 Chapter 7. web3.eth.Contract
web3.js Documentation, Release 1.0.0
7.3.2 Example
web3.eth.defaultAccount;
> undefined
7.4 defaultBlock
web3.eth.Contract.defaultBlock
contract.defaultBlock // on contract instance
The default block is used for certain methods. You can override it by passing in the defaultBlock as last parameter.
The default value is "latest".
7.4.1 Property
7.4.2 Example
contract.defaultBlock;
> "latest"
7.4. defaultBlock 75
web3.js Documentation, Release 1.0.0
7.5 defaultHardfork
contract.defaultHardfork
7.5.1 Property
7.5.2 Example
contract.defaultHardfork;
> "petersburg"
7.6 defaultChain
contract.defaultChain
7.6.1 Property
76 Chapter 7. web3.eth.Contract
web3.js Documentation, Release 1.0.0
• "rinkeby" - String
• "ropsten" - String
Default is "mainnet"
7.6.2 Example
contract.defaultChain;
> "mainnet"
7.7 defaultCommon
contract.defaultCommon
7.7.1 Property
The default common property does contain the following Common object:
• customChain - Object: The custom chain properties
– name - string: (optional) The name of the chain
– networkId - number: Network ID of the custom chain
– chainId - number: Chain ID of the custom chain
• baseChain - string: (optional) mainnet, goerli, kovan, rinkeby, or ropsten
• hardfork - string: (optional) chainstart, homestead, dao, tangerineWhistle,
spuriousDragon, byzantium, constantinople, petersburg, or istanbul
Default is undefined.
7.7.2 Example
contract.defaultCommon;
> {customChain: {name: 'custom-network', chainId: 1, networkId: 1}, baseChain:
˓→'mainnet', hardfork: 'petersburg'}
7.7. defaultCommon 77
web3.js Documentation, Release 1.0.0
7.8 transactionBlockTimeout
web3.eth.Contract.transcationBlockTimeout
contract.transactionBlockTimeout // on contract instance
The transactionBlockTimeout is used over socket-based connections. This option defines the amount of new
blocks it should wait until the first confirmation happens, otherwise the PromiEvent rejects with a timeout error.
7.8.1 Returns
7.9 blockHeaderTimeout
web3.eth.Contract.blockHeaderTimeout
contract.blockHeaderTimeout // on contract instance
The blockHeaderTimeout is used over socket-based connections. This option defines the amount seconds it
should wait for “newBlockHeaders” event before falling back to polling to fetch transaction receipt.
7.9.1 Returns
7.10 transactionConfirmationBlocks
web3.eth.Contract.transactionConfirmationBlocks
contract.transactionConfirmationBlocks // on contract instance
This defines the number of blocks it requires until a transaction is considered confirmed.
7.10.1 Returns
7.11 transactionPollingTimeout
web3.eth.Contract.transactionPollingTimeout
contract.transactionPollingTimeout // on contract instance
The transactionPollingTimeout is used over HTTP connections. This option defines the number of seconds
Web3 will wait for a receipt which confirms that a transaction was mined by the network. Note: If this method times
out, the transaction may still be pending.
78 Chapter 7. web3.eth.Contract
web3.js Documentation, Release 1.0.0
7.11.1 Returns
7.12 transactionPollingInterval
web3.eth.Contract.transactionPollingInterval
contract.transactionPollingInterval // on contract instance
The transactionPollingInterval is used over HTTP connections. This option defines the number of seconds
between Web3 calls for a receipt which confirms that a transaction was mined by the network.
7.12.1 Returns
7.13 handleRevert
web3.eth.Contract.handleRevert
contract.handleRevert // on contract instance
The handleRevert options property defaults to false and returns the revert reason string if enabled on send or
call of a contract method.
Note: The revert reason string and signature are properties on the returned error.
7.13.1 Returns
7.14 options
myContract.options
The options object for the contract instance. from, gas and gasPrice are used as fallback values when sending
transactions.
7.12. transactionPollingInterval 79
web3.js Documentation, Release 1.0.0
7.14.1 Properties
Object - options:
• address - String: The address where the contract is deployed. See options.address.
• jsonInterface - Array: The json interface of the contract. See options.jsonInterface.
• data - String: The byte code of the contract. Used when the contract gets deployed.
• from - String: The address transactions should be made from.
• gasPrice - String: The gas price in wei to use for transactions.
• gas - Number: The maximum gas provided for a transaction (gas limit).
• handleRevert - Boolean: It will otherwise use the default value provided from the Eth module. See
handleRevert.
• transactionBlockTimeout - Number: It will otherwise use the default value provided from the Eth
module. See transactionBlockTimeout.
• transactionConfirmationBlocks - Number: It will otherwise use the default value provided from
the Eth module. See transactionConfirmationBlocks.
• transactionPollingTimeout - Number: It will otherwise use the default value provided from the Eth
module. See transactionPollingTimeout.
• chain - Number: It will otherwise use the default value provided from the Eth module. See defaultChain.
• hardfork - Number: It will otherwise use the default value provided from the Eth module. See defaultHard-
fork.
• common - Number: It will otherwise use the default value provided from the Eth module. See defaultCommon.
7.14.2 Example
myContract.options;
> {
address: '0x1234567890123456789012345678901234567891',
jsonInterface: [...],
from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe',
gasPrice: '10000000000000',
gas: 1000000
}
7.15 options.address
myContract.options.address
80 Chapter 7. web3.eth.Contract
web3.js Documentation, Release 1.0.0
The address used for this contract instance. All transactions generated by web3.js from this contract will contain this
address as the "to".
The address will be stored in lowercase.
7.15.1 Property
address - String|null: The address for this contract, or null if not yet set.
7.15.2 Example
myContract.options.address;
> '0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae'
7.16 options.jsonInterface
myContract.options.jsonInterface
The json interface object derived from the ABI of this contract.
7.16.1 Property
jsonInterface - Array: The json interface for this contract. Re-setting this will regenerate the methods and
events of the contract instance.
7.16.2 Example
myContract.options.jsonInterface;
> [{
"type":"function",
"name":"foo",
"inputs": [{"name":"a","type":"uint256"}],
"outputs": [{"name":"b","type":"address"}]
},{
"type":"event",
"name":"Event",
"inputs": [{"name":"a","type":"uint256","indexed":true},{"name":"b","type":
˓→"bytes32","indexed":false}],
}]
7.16. options.jsonInterface 81
web3.js Documentation, Release 1.0.0
7.17 = Methods =
7.18 clone
myContract.clone()
7.18.1 Parameters
none
7.18.2 Returns
7.18.3 Example
7.19 deploy
myContract.deploy(options)
Call this function to deploy the contract to the blockchain. After successful deployment the promise will resolve with
a new contract instance.
7.19.1 Parameters
82 Chapter 7. web3.eth.Contract
web3.js Documentation, Release 1.0.0
7.19.2 Returns
7.19.3 Example
myContract.deploy({
data: '0x12345...',
arguments: [123, 'My String']
})
.send({
from: '0x1234567890123456789012345678901234567891',
gas: 1500000,
gasPrice: '30000000000000'
}, function(error, transactionHash){ ... })
.on('error', function(error){ ... })
.on('transactionHash', function(transactionHash){ ... })
.on('receipt', function(receipt){
console.log(receipt.contractAddress) // contains the new contract address
})
.on('confirmation', function(confirmationNumber, receipt){ ... })
.then(function(newContractInstance){
console.log(newContractInstance.options.address) // instance with the new
˓→contract address
});
myContract.deploy({
arguments: [123, 'My String']
})
.send({
from: '0x1234567890123456789012345678901234567891',
gas: 1500000,
gasPrice: '30000000000000'
})
.then(function(newContractInstance){
console.log(newContractInstance.options.address) // instance with the new
˓→contract address
});
// Simply encoding
(continues on next page)
7.19. deploy 83
web3.js Documentation, Release 1.0.0
// Gas estimation
myContract.deploy({
data: '0x12345...',
arguments: [123, 'My String']
})
.estimateGas(function(err, gas){
console.log(gas);
});
7.20 methods
Creates a transaction object for that method, which then can be called, send, estimated, createAccessList , or ABI
encoded.
The methods of this smart contract are available through:
• The name: myContract.methods.myMethod(123)
• The name with parameters: myContract.methods['myMethod(uint256)'](123)
• The signature: myContract.methods['0x58cf5f10'](123)
This allows calling functions with same name but different parameters from the JavaScript contract object.
7.20.1 Parameters
Parameters of any method depend on the smart contracts methods, defined in the JSON interface.
7.20.2 Returns
84 Chapter 7. web3.eth.Contract
web3.js Documentation, Release 1.0.0
• Function - encodeABI: Encodes the ABI for this method. This can be send using a transaction, call the
method or passing into another smart contracts method as argument.
• Function - createAccessList: Returns an EIP-2930 access list for specified contract method Note: You must
specify a from address and gas if it’s not specified in options when instantiating parent contract object (e.g.
new web3.eth.Contract(jsonInterface[, address][, options])).
7.20.3 Example
// calling a method
myContract.methods.myMethod(123).call({from:
˓→'0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}, function(error, result){
...
});
.then(function(receipt){
// receipt can also be a new contract instance, when coming from a "contract.
˓→deploy({...}).send()"
});
myContract.methods.myMethod(123).send({from:
˓→'0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'})
.on('transactionHash', function(hash){
...
})
.on('receipt', function(receipt){
...
})
.on('confirmation', function(confirmationNumber, receipt){
...
})
.on('error', function(error, receipt) {
...
});
7.21 methods.myMethod.call
Will call a “constant” method and execute its smart contract method in the EVM without sending any transaction.
Note calling cannot alter the smart contract state.
7.21.1 Parameters
7.21. methods.myMethod.call 85
web3.js Documentation, Release 1.0.0
• from - String (optional): The address the call “transaction” should be made from. For calls the
from property is optional however it is highly recommended to explicitly set it or it may default to
address(0) depending on your node or provider.
• gasPrice - String (optional): The gas price in wei to use for this call “transaction”.
• gas - Number (optional): The maximum gas provided for this call “transaction” (gas limit).
2. defaultBlock - Number|String|BN|BigNumber (optional): If you pass this parameter it will not use
the default block set with contract.defaultBlock. Pre-defined block numbers as "earliest", "latest",
"pending", "safe" or "finalized" can also be used. Useful for requesting data from or replaying
transactions in past blocks.
3. callback - Function (optional): This callback will be fired with the result of the smart contract method
execution as the second argument, or with an error object as the first argument.
7.21.2 Returns
Promise returns Mixed: The return value(s) of the smart contract method. If it returns a single value, it’s returned
as is. If it has multiple return values they are returned as an object with properties and indices:
7.21.3 Example
...
});
.then(function(result){
...
});
// MULTI-ARGUMENT RETURN:
// Solidity
contract MyContract {
function myFunction() returns(uint256 myNumber, string myString) {
return (23456, "Hello!%");
}
}
// web3.js
var MyContract = new web3.eth.Contract(abi, address);
MyContract.methods.myFunction().call()
.then(console.log);
> Result {
myNumber: '23456',
myString: 'Hello!%',
0: '23456', // these are here as fallbacks if the name is not know or given
1: 'Hello!%'
}
(continues on next page)
86 Chapter 7. web3.eth.Contract
web3.js Documentation, Release 1.0.0
// SINGLE-ARGUMENT RETURN:
// Solidity
contract MyContract {
function myFunction() returns(string myString) {
return "Hello!%";
}
}
// web3.js
var MyContract = new web3.eth.Contract(abi, address);
MyContract.methods.myFunction().call()
.then(console.log);
> "Hello!%"
7.22 methods.myMethod.send
Will send a transaction to the smart contract and execute its method. Note this can alter the smart contract state.
7.22.1 Parameters
7.22.2 Returns
7.22. methods.myMethod.send 87
web3.js Documentation, Release 1.0.0
• "transactionHash" returns transactionHash: String: Fired when the transaction hash is avail-
able.
• "receipt" returns receipt: Object: Fired when the transaction receipt is available. Receipts from
contracts will have no logs property, but instead an events property with event names as keys and events as
properties. See getPastEvents return values for details about the returned event object.
• "confirmation" returns confirmation: Number, receipt: Object, latestBlockHash:
String: Fired for every confirmation up to the 24th confirmation.
• "error" returns error: Error: Fired if an error occurs during sending. If the transaction was rejected
by the network with a receipt, the receipt will be available as a property on the error object.
7.22.3 Example
...
});
.then(function(receipt){
// receipt can also be a new contract instance, when coming from a "contract.
˓→deploy({...}).send()"
});
.on('transactionHash', function(hash){
...
})
.on('confirmation', function(confirmationNumber, receipt){
...
})
.on('receipt', function(receipt){
// receipt example
console.log(receipt);
> {
"transactionHash":
˓→"0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b",
"transactionIndex": 0,
"blockHash":
˓→"0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46",
"blockNumber": 3,
"contractAddress": "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe",
"cumulativeGasUsed": 314159,
"gasUsed": 30234,
"events": {
"MyEvent": {
returnValues: {
myIndexedParam: 20,
myOtherIndexedParam: '0x123456789...',
(continues on next page)
88 Chapter 7. web3.eth.Contract
web3.js Documentation, Release 1.0.0
topics: [
˓→'0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
˓→'0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385']
},
event: 'MyEvent',
signature:
˓→'0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
logIndex: 0,
transactionIndex: 0,
transactionHash:
˓→'0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
blockHash:
˓→'0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
blockNumber: 1234,
address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'
},
"MyOtherEvent": {
...
},
"MyMultipleEvent":[{...}, {...}] // If there are multiple of the same
˓→event, they will be in an array
}
}
})
.on('error', function(error, receipt) { // If the transaction was rejected by the
˓→network with a receipt, the second parameter will be the receipt.
...
});
7.23 methods.myMethod.estimateGas
Returns the amount of gas consumed by executing the method locally without creating a new transaction on the
blockchain. The returned amount can be used as a gas estimate for executing the transaction publicly. The actual gas
used can be different when sending the transaction later, as the state of the smart contract can be different at that time.
Note: You must specify a from address otherwise you may experience odd behavior.
7.23.1 Parameters
7.23. methods.myMethod.estimateGas 89
web3.js Documentation, Release 1.0.0
• value - Number|String|BN|BigNumber (optional): The value transferred for the call “trans-
action” in wei.
2. callback - Function (optional): This callback will be fired with the result of the gas estimation as the
second argument, or with an error object as the first argument.
7.23.2 Returns
7.23.3 Example
if(gasAmount == 5000000)
console.log('Method ran out of gas');
});
.then(function(gasAmount){
...
})
.catch(function(error){
...
});
7.24 methods.myMethod.encodeABI
Encodes the ABI for this method. The resulting hex string is 32-bit function signature hash plus the passed parameters
in Solidity tightly packed format. This can be used to send a transaction, call a method, or pass it into another smart
contract’s method as arguments. Set the data field on web3.eth.sendTransaction options as the encodeABI() result and
it is the same as calling the contract method with contract.myMethod.send().
Some use cases for encodeABI() include: preparing a smart contract transaction for a multisignature wallet, working
with offline wallets and cold storage and creating transaction payload for complex smart contract proxy calls.
7.24.1 Parameters
none
7.24.2 Returns
String: The encoded ABI byte code to send via a transaction or call.
90 Chapter 7. web3.eth.Contract
web3.js Documentation, Release 1.0.0
7.24.3 Example
myContract.methods.myMethod(123).encodeABI();
> '0x58cf5f1000000000000000000000000000000000000000000000000000000000000007B'
7.25 methods.myMethod.createAccessList
Will call to create an access list a method execution will access when executed in the EVM. Note: Cur-
rently eth_createAccessList seems to only be supported by Geth. Note: You must specify a from address
and gas if it’s not specified in options when instantiating parent contract object (e.g. new web3.eth.
Contract(jsonInterface[, address][, options])).
7.25.1 Parameters
7.25.2 Returns
{
"accessList": [
{
"address": "0x00f5f5f3a25f142fafd0af24a754fafa340f32c7",
"storageKeys": [
"0x0000000000000000000000000000000000000000000000000000000000000000"
]
}
],
"gasUsed": "0x644e"
}
7.25.3 Example
7.25. methods.myMethod.createAccessList 91
web3.js Documentation, Release 1.0.0
˓→accessList){
...
});
.then(function(accessList){
...
})
.catch(function(error){
...
});
7.26 = Events =
7.27 once
Subscribes to an event and unsubscribes immediately after the first event or error. Will only fire for a single event.
7.27.1 Parameters
1. event - String: The name of the event in the contract, or "allEvents" to get all events.
2. options - Object (optional): The options used for deployment.
• filter - Object (optional): Lets you filter events by indexed parameters, e.g. {filter:
{myNumber: [12,13]}} means all events where “myNumber” is 12 or 13.
• topics - Array (optional): This allows you to manually set the topics for the event filter. If given
the filter property and event signature, (topic[0]) will not be set automatically. Each topic can also
be a nested array of topics that behaves as “or” operation between the given nested topics.
3. callback - Function: This callback will be fired for the first event as the second argument, or an error as
the first argument. See getPastEvents return values for details about the event structure.
7.27.2 Returns
undefined
92 Chapter 7. web3.eth.Contract
web3.js Documentation, Release 1.0.0
7.27.3 Example
myContract.once('MyEvent', {
filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, //
˓→Using an array means OR: e.g. 20 or 23
fromBlock: 0
}, function(error, event){ console.log(event); });
},
event: 'MyEvent',
signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
logIndex: 0,
transactionIndex: 0,
transactionHash:
˓→'0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
blockNumber: 1234,
address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'
}
7.28 events
myContract.events.MyEvent([options][, callback])
Subscribe to an event.
7.28.1 Parameters
7.28. events 93
web3.js Documentation, Release 1.0.0
7.28.2 Returns
7.28.3 Example
myContract.events.MyEvent({
filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, //
˓→Using an array means OR: e.g. 20 or 23
fromBlock: 0
}, function(error, event){ console.log(event); })
.on("connected", function(subscriptionId){
console.log(subscriptionId);
})
.on('data', function(event){
console.log(event); // same results as the optional callback above
})
.on('changed', function(event){
// remove event from local database
})
.on('error', function(error, receipt) { // If the transaction was rejected by the
˓→network with a receipt, the second parameter will be the receipt.
...
});
94 Chapter 7. web3.eth.Contract
web3.js Documentation, Release 1.0.0
},
event: 'MyEvent',
signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
logIndex: 0,
transactionIndex: 0,
transactionHash:
˓→'0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
blockNumber: 1234,
address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'
}
7.29 events.allEvents
myContract.events.allEvents([options][, callback])
Same as events but receives all events from this smart contract. Optionally the filter property can filter those events.
7.30 getPastEvents
7.30.1 Parameters
1. event - String: The name of the event in the contract, or "allEvents" to get all events.
2. options - Object (optional): The options used for deployment.
• filter - Object (optional): Lets you filter events by indexed parameters, e.g. {filter:
{myNumber: [12,13]}} means all events where “myNumber” is 12 or 13.
• fromBlock - Number|String|BN|BigNumber (optional): The block number (greater than
or equal to) from which to get events on. Pre-defined block numbers as "earliest", "latest"
, "pending" , "safe" or "finalized" can also be used.
7.29. events.allEvents 95
web3.js Documentation, Release 1.0.0
7.30.2 Returns
Promise returns Array: An array with the past event Objects, matching the given event name and filter.
For the structure of a returned event Object see getPastEvents return values.
7.30.3 Example
myContract.getPastEvents('MyEvent', {
filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, //
˓→Using an array means OR: e.g. 20 or 23
fromBlock: 0,
toBlock: 'latest'
}, function(error, events){ console.log(events); })
.then(function(events){
console.log(events) // same results as the optional callback above
});
> [{
returnValues: {
myIndexedParam: 20,
myOtherIndexedParam: '0x123456789...',
myNonIndexParam: 'My String'
},
raw: {
data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7
˓→', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385']
},
event: 'MyEvent',
signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
logIndex: 0,
transactionIndex: 0,
transactionHash:
˓→'0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
blockNumber: 1234,
address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'
},{
...
}]
96 Chapter 7. web3.eth.Contract
CHAPTER 8
web3.eth.accounts
The web3.eth.accounts contains functions to generate Ethereum accounts and sign transactions and data.
Note: This package has NOT been audited and might potentially be unsafe. Take precautions to clear memory
properly, store the private keys safely, and test transaction receiving and sending functionality properly before using
in production!
// for accounts.signTransaction().
var accounts = new Accounts('ws://localhost:8546');
8.1 create
web3.eth.accounts.create([entropy]);
8.1.1 Parameters
1. entropy - String (optional): A random string to increase entropy. If given it should be at least 32 characters.
If none is given a random string will be generated using randomhex.
97
web3.js Documentation, Release 1.0.0
8.1.2 Returns
8.1.3 Example
web3.eth.accounts.create();
> {
address: "0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01",
privateKey: "0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709",
signTransaction: function(tx){...},
sign: function(data){...},
encrypt: function(password){...}
}
web3.eth.accounts.create('2435@#@#@±±±±!!!!
˓→678543213456764321§34567543213456785432134567');
> {
address: "0xF2CD2AA0c7926743B1D4310b2BC984a0a453c3d4",
privateKey: "0xd7325de5c2c1cf0009fac77d3d04a9c004b038883446b065871bc3e831dcd098",
signTransaction: function(tx){...},
sign: function(data){...},
encrypt: function(password){...}
}
web3.eth.accounts.create(web3.utils.randomHex(32));
> {
address: "0xe78150FaCD36E8EB00291e251424a0515AA1FF05",
privateKey: "0xcc505ee6067fba3f6fc2050643379e190e087aeffe5d958ab9f2f3ed3800fa4e",
signTransaction: function(tx){...},
sign: function(data){...},
encrypt: function(password){...}
}
8.2 privateKeyToAccount
98 Chapter 8. web3.eth.accounts
web3.js Documentation, Release 1.0.0
8.2.1 Parameters
1. privateKey - String: The private key to import. This is 32 bytes of random data. If you are supplying a
hexadecimal number, it must have 0x prefix in order to be in line with other Ethereum libraries. 2. ignoreLength
- Boolean: If set to true does the privateKey length not get validated.
8.2.2 Returns
8.2.3 Example
web3.eth.accounts.privateKeyToAccount(
˓→'0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709');
> {
address: '0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01',
privateKey: '0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709',
signTransaction: function(tx){...},
sign: function(data){...},
encrypt: function(password){...}
}
8.3 signTransaction
8.3.1 Parameters
8.3. signTransaction 99
web3.js Documentation, Release 1.0.0
8.3.2 Returns
Promise returning Object: The signed data RLP encoded transaction, or if returnSignature is true the signature value
8.3.3 Example
web3.eth.accounts.signTransaction({
to: '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55',
value: '1000000000',
gas: '2000000',
}, '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318')
.then(console.log);
> {
messageHash: '0x31c2f03766b36f0346a850e78d4f7db2d9f4d7d54d5f272a750ba44271e370b1',
v: '0x25',
(continues on next page)
˓→'
transactionHash:
˓→'0xde8db924885b0803d2edc335f745b2b8750c8848744905684c20b987443a9593'
web3.eth.accounts.signTransaction({
to: '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55',
value: '1000000000',
gas: '2000000',
gasPrice: '234567897654321',
nonce: 0,
chainId: 1
}, '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318')
.then(console.log);
> {
messageHash: '0x6893a6ee8df79b0f5d64a180cd1ef35d030f3e296a5361cf04d02ce720d32ec5',
r: '0x9ebb6ca057a0535d6186462bc0b465b561c94a295bdb0621fc19208ab149a9c',
s: '0x440ffd775ce91a833ab410777204d5341a6f9fa91216a6f3ee2c051fea6a0428',
v: '0x25',
rawTransaction:
˓→'0xf86a8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a009ebb6ca05
˓→'
transactionHash:
˓→'0xd8f64a42b57be0d565f385378db2f6bf324ce14a594afc05de90436e9ce01f60'
// or with a common
web3.eth.accounts.signTransaction({
to: '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55',
value: '1000000000',
gas: '2000000',
common: {
baseChain: 'mainnet',
hardfork: 'petersburg',
customChain: {
name: 'custom-chain',
chainId: 1,
networkId: 1
}
}
}, '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318')
.then(console.log);
8.4 recoverTransaction
web3.eth.accounts.recoverTransaction(rawTransaction);
Recovers the Ethereum address which was used to sign the given RLP encoded transaction.
8.4.1 Parameters
8.4.2 Returns
8.4.3 Example
web3.eth.accounts.recoverTransaction(
˓→'0xf86180808401ef364594f0109fc8df283027b6285cc889f5aa624eac1f5580801ca031573280d608f75137e33fc14655
˓→');
> "0xF0109fC8DF283027b6285cc889F5aA624EaC1F55"
8.5 hashMessage
web3.eth.accounts.hashMessage(message);
Hashes the given message to be passed web3.eth.accounts.recover() function. The data will be UTF-8 HEX decoded
and enveloped as follows: "\x19Ethereum Signed Message:\n" + message.length + message
and hashed using keccak256.
8.5.1 Parameters
1. message - String: A message to hash, if its HEX it will be UTF8 decoded before.
8.5.2 Returns
8.5.3 Example
web3.eth.accounts.hashMessage("Hello World")
> "0xa1de988600a42c4b4ab089b619297c17d53cffae5d5120d82d8a92d0bb3b78f2"
8.6 sign
web3.eth.accounts.sign(data, privateKey);
8.6.1 Parameters
Note: The value passed as the data parameter will be UTF-8 HEX decoded and wrapped as follows:
"\x19Ethereum Signed Message:\n" + message.length + message.
8.6.2 Returns
8.6.3 Example
web3.eth.accounts.sign('Some data',
˓→'0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318');
> {
message: 'Some data',
messageHash: '0x1da44b586eb0729ff70a73c326926f6ed5a25f5b056e7f47fbc6e58d86871655',
v: '0x1c',
r: '0xb91467e570a6466aa9e9876cbcd013baba02900b8979d43fe208a4a4f339f5fd',
s: '0x6007e74cd82e037b800186422fc2da167c747ef045e5d18a5f5d4300f8e1a029',
signature:
˓→'0xb91467e570a6466aa9e9876cbcd013baba02900b8979d43fe208a4a4f339f5fd6007e74cd82e037b800186422fc2da16
˓→'
8.7 recover
web3.eth.accounts.recover(signatureObject);
web3.eth.accounts.recover(message, signature [, preFixed]);
web3.eth.accounts.recover(message, v, r, s [, preFixed]);
Recovers the Ethereum address which was used to sign the given data.
8.7.1 Parameters
1. message|signatureObject - String|Object: Either signed message or hash, or the signature object as following v
• messageHash - String: The hash of the given message already prefixed with
"\x19Ethereum Signed Message:\n" + message.length + message.
• r - String: First 32 bytes of the signature
• s - String: Next 32 bytes of the signature
• v - String: Recovery value + 27
2. signature - String: The raw RLP encoded signature, OR parameter 2-4 as v, r, s values.
3. preFixed - Boolean (optional, default: false): If the last parameter is true, the given message will
NOT automatically be prefixed with "\x19Ethereum Signed Message:\n" + message.length
+ message, and assumed to be already prefixed.
8.7.2 Returns
8.7.3 Example
web3.eth.accounts.recover({
messageHash: '0x1da44b586eb0729ff70a73c326926f6ed5a25f5b056e7f47fbc6e58d86871655',
v: '0x1c',
r: '0xb91467e570a6466aa9e9876cbcd013baba02900b8979d43fe208a4a4f339f5fd',
s: '0x6007e74cd82e037b800186422fc2da167c747ef045e5d18a5f5d4300f8e1a029'
})
> "0x2c7536E3605D9C16a7a3D7b1898e529396a65c23"
// message, signature
web3.eth.accounts.recover('Some data',
˓→'0xb91467e570a6466aa9e9876cbcd013baba02900b8979d43fe208a4a4f339f5fd6007e74cd82e037b800186422fc2da16
˓→');
> "0x2c7536E3605D9C16a7a3D7b1898e529396a65c23"
// message, v, r, s
web3.eth.accounts.recover('Some data', '0x1c',
˓→'0xb91467e570a6466aa9e9876cbcd013baba02900b8979d43fe208a4a4f339f5fd',
˓→'0x6007e74cd82e037b800186422fc2da167c747ef045e5d18a5f5d4300f8e1a029');
> "0x2c7536E3605D9C16a7a3D7b1898e529396a65c23"
8.8 encrypt
web3.eth.accounts.encrypt(privateKey, password);
8.8.1 Parameters
8.8.2 Returns
8.8.3 Example
web3.eth.accounts.encrypt(
˓→'0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318', 'test!')
> {
version: 3,
id: '04e9bcbb-96fa-497b-94d1-14df4cd20af6',
address: '2c7536e3605d9c16a7a3d7b1898e529396a65c23',
crypto: {
ciphertext: 'a1c25da3ecde4e6a24f3697251dd15d6208520efc84ad97397e906e6df24d251
˓→',
8.9 decrypt
web3.eth.accounts.decrypt(keystoreJsonV3, password);
8.9.1 Parameters
8.9.2 Returns
8.9.3 Example
web3.eth.accounts.decrypt({
version: 3,
id: '04e9bcbb-96fa-497b-94d1-14df4cd20af6',
address: '2c7536e3605d9c16a7a3d7b1898e529396a65c23',
crypto: {
ciphertext: 'a1c25da3ecde4e6a24f3697251dd15d6208520efc84ad97397e906e6df24d251
˓→',
8.10 wallet
web3.eth.accounts.wallet;
Contains an in memory wallet with multiple accounts. These accounts can be used when using
web3.eth.sendTransaction().
8.10.1 Example
web3.eth.accounts.wallet;
> Wallet {
0: {...}, // account by index
"0xF0109fC8DF283027b6285cc889F5aA624EaC1F55": {...}, // same account by address
"0xf0109fc8df283027b6285cc889f5aa624eac1f55": {...}, // same account by address
˓→lowercase
1: {...},
"0xD0122fC8DF283027b6285cc889F5aA624EaC1d23": {...},
"0xd0122fc8df283027b6285cc889f5aa624eac1d23": {...},
add: function(){},
remove: function(){},
save: function(){},
load: function(){},
(continues on next page)
length: 2,
}
8.11 wallet.create
web3.eth.accounts.wallet.create(numberOfAccounts [, entropy]);
Generates one or more accounts in the wallet. If wallets already exist they will not be overridden.
8.11.1 Parameters
1. numberOfAccounts - Number: Number of accounts to create. Leave empty to create an empty wallet.
2. entropy - String (optional): A string with random characters as additional entropy when generating ac-
counts. If given it should be at least 32 characters.
8.11.2 Returns
8.11.3 Example
web3.eth.accounts.wallet.create(2, '54674321§3456764321§345674321§3453647544±±±§±±±!
˓→!!43534534534534');
> Wallet {
0: {...},
"0xF0109fC8DF283027b6285cc889F5aA624EaC1F55": {...},
"0xf0109fc8df283027b6285cc889f5aa624eac1f55": {...},
...
}
8.12 wallet.add
web3.eth.accounts.wallet.add(account);
8.12.1 Parameters
8.12.2 Returns
8.12.3 Example
web3.eth.accounts.wallet.add(
˓→'0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318');
> {
index: 0,
address: '0x2c7536E3605D9C16a7a3D7b1898e529396a65c23',
privateKey: '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318',
signTransaction: function(tx){...},
sign: function(data){...},
encrypt: function(password){...}
}
web3.eth.accounts.wallet.add({
privateKey: '0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709',
address: '0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01'
});
> {
index: 0,
address: '0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01',
privateKey: '0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709',
signTransaction: function(tx){...},
sign: function(data){...},
encrypt: function(password){...}
}
8.13 wallet.remove
web3.eth.accounts.wallet.remove(account);
8.13.1 Parameters
8.13.2 Returns
8.13.3 Example
web3.eth.accounts.wallet;
> Wallet {
0: {...},
"0xF0109fC8DF283027b6285cc889F5aA624EaC1F55": {...}
1: {...},
"0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01": {...}
...
}
web3.eth.accounts.wallet.remove('0xF0109fC8DF283027b6285cc889F5aA624EaC1F55');
> true
web3.eth.accounts.wallet.remove(3);
> false
8.14 wallet.clear
web3.eth.accounts.wallet.clear();
8.14.1 Parameters
none
8.14.2 Returns
8.14.3 Example
web3.eth.accounts.wallet.clear();
> Wallet {
add: function(){},
remove: function(){},
save: function(){},
load: function(){},
clear: function(){},
length: 0
}
8.15 wallet.encrypt
web3.eth.accounts.wallet.encrypt(password);
8.15.1 Parameters
8.15.2 Returns
8.15.3 Example
web3.eth.accounts.wallet.encrypt('test');
> [ { version: 3,
id: 'dcf8ab05-a314-4e37-b972-bf9b86f91372',
address: '06f702337909c06c82b09b7a22f0a2f0855d1f68',
crypto:
{ ciphertext: '0de804dc63940820f6b3334e5a4bfc8214e27fb30bb7e9b7b74b25cd7eb5c604',
cipherparams: [Object],
cipher: 'aes-128-ctr',
kdf: 'scrypt',
kdfparams: [Object],
mac: 'b2aac1485bd6ee1928665642bf8eae9ddfbc039c3a673658933d320bac6952e3' } },
{ version: 3,
id: '9e1c7d24-b919-4428-b10e-0f3ef79f7cf0',
address: 'b5d89661b59a9af0b34f58d19138baa2de48baaf',
crypto:
{ ciphertext: 'd705ebed2a136d9e4db7e5ae70ed1f69d6a57370d5fbe06281eb07615f404410',
cipherparams: [Object],
cipher: 'aes-128-ctr',
kdf: 'scrypt',
kdfparams: [Object],
mac: 'af9eca5eb01b0f70e909f824f0e7cdb90c350a802f04a9f6afe056602b92272b' } }
]
8.16 wallet.decrypt
web3.eth.accounts.wallet.decrypt(keystoreArray, password);
8.16.1 Parameters
8.16.2 Returns
8.16.3 Example
web3.eth.accounts.wallet.decrypt([
{ version: 3,
id: '83191a81-aaca-451f-b63d-0c5f3b849289',
address: '06f702337909c06c82b09b7a22f0a2f0855d1f68',
crypto:
{ ciphertext: '7d34deae112841fba86e3e6cf08f5398dda323a8e4d29332621534e2c4069e8d',
cipherparams: { iv: '497f4d26997a84d570778eae874b2333' },
cipher: 'aes-128-ctr',
kdf: 'scrypt',
kdfparams:
{ dklen: 32,
salt: '208dd732a27aa4803bb760228dff18515d5313fd085bbce60594a3919ae2d88d',
n: 262144,
r: 8,
p: 1 },
mac: '0062a853de302513c57bfe3108ab493733034bf3cb313326f42cf26ea2619cf9' } },
{ version: 3,
id: '7d6b91fa-3611-407b-b16b-396efb28f97e',
address: 'b5d89661b59a9af0b34f58d19138baa2de48baaf',
crypto:
{ ciphertext: 'cb9712d1982ff89f571fa5dbef447f14b7e5f142232bd2a913aac833730eeb43',
cipherparams: { iv: '8cccb91cb84e435437f7282ec2ffd2db' },
cipher: 'aes-128-ctr',
kdf: 'scrypt',
kdfparams:
{ dklen: 32,
salt: '08ba6736363c5586434cd5b895e6fe41ea7db4785bd9b901dedce77a1514e8b8',
n: 262144,
r: 8,
p: 1 },
mac: 'd2eb068b37e2df55f56fa97a2bf4f55e072bef0dd703bfd917717d9dc54510f0' } }
], 'test');
> Wallet {
0: {...},
1: {...},
"0xF0109fC8DF283027b6285cc889F5aA624EaC1F55": {...},
"0xD0122fC8DF283027b6285cc889F5aA624EaC1d23": {...}
...
}
8.17 wallet.save
web3.eth.accounts.wallet.save(password [, keyName]);
8.17.1 Parameters
8.17.2 Returns
Boolean
8.17.3 Example
web3.eth.accounts.wallet.save('test#!$');
> true
8.18 wallet.load
web3.eth.accounts.wallet.load(password [, keyName]);
8.18.1 Parameters
8.18.2 Returns
8.18.3 Example
web3.eth.accounts.wallet.load('test#!$', 'myWalletKey');
> Wallet {
0: {...},
1: {...},
"0xF0109fC8DF283027b6285cc889F5aA624EaC1F55": {...},
"0xD0122fC8DF283027b6285cc889F5aA624EaC1d23": {...}
...
}
web3.eth.personal
The web3-eth-personal package allows you to interact with the Ethereum node’s accounts.
Note: Many of these functions send sensitive information like passwords. Never call these functions over a unsecured
Websocket or HTTP provider, as your password will be sent in plain text!
// -> web3.eth.personal
9.1 setProvider
web3.setProvider(myProvider)
web3.eth.setProvider(myProvider)
web3.shh.setProvider(myProvider)
web3.bzz.setProvider(myProvider)
...
115
web3.js Documentation, Release 1.0.0
Note: When called on the umbrella package web3 it will also set the provider for all sub modules web3.eth,
web3.shh, etc. EXCEPT web3.bzz which needs a separate provider at all times.
9.1.1 Parameters
9.1.2 Returns
Boolean
// change provider
web3.setProvider('ws://localhost:8546');
// or
web3.setProvider(new Web3.providers.WebsocketProvider('ws://localhost:8546'));
9.2 providers
web3.providers
web3.eth.providers
web3.shh.providers
web3.bzz.providers
...
9.2.1 Value
9.2.2 Example
9.2.3 Configuration
// ====
// Http
// ====
var options = {
keepAlive: true,
withCredentials: false,
timeout: 20000, // ms
headers: [
{
name: 'Access-Control-Allow-Origin',
value: '*'
},
{
...
}
],
agent: {
(continues on next page)
// ==========
// Websockets
// ==========
var options = {
timeout: 30000, // ms
clientConfig: {
// Useful if requests are large
maxReceivedFrameSize: 100000000, // bytes - default: 1MiB
maxReceivedMessageSize: 100000000, // bytes - default: 8MiB
More information for the Http and Websocket provider modules can be found here:
• HttpProvider
• WebsocketProvider
9.3 givenProvider
web3.givenProvider
web3.eth.givenProvider
web3.shh.givenProvider
(continues on next page)
When using web3.js in an Ethereum compatible browser, it will set with the current native provider by that browser.
Will return the given provider by the (browser) environment, otherwise null.
9.3.1 Returns
9.3.2 Example
9.4 currentProvider
web3.currentProvider
web3.eth.currentProvider
web3.shh.currentProvider
web3.bzz.currentProvider
...
9.4.1 Returns
9.4.2 Example
9.5 BatchRequest
new web3.BatchRequest()
new web3.eth.BatchRequest()
new web3.shh.BatchRequest()
new web3.bzz.BatchRequest()
9.5.1 Parameters
none
9.5.2 Returns
9.5.3 Example
batch.add(contract.methods.balance(address).call.request({from:
˓→'0x0000000000000000000000000000000000000000'}, callback2));
batch.execute();
9.6 extend
web3.extend(methods)
web3.eth.extend(methods)
web3.shh.extend(methods)
web3.bzz.extend(methods)
...
Note: You also have *.extend.formatters as additional formatter functions to be used for input and output
formatting. Please see the source file for function details.
9.6.1 Parameters
1. methods - Object: Extension object with array of methods description objects as follows:
• property - String: (optional) The name of the property to add to the module. If no property is
set it will be added to the module directly.
• methods - Array: The array of method descriptions:
– name - String: Name of the method to add.
– call - String: The RPC method name.
– params - Number: (optional) The number of parameters for that function. Default 0.
– inputFormatter - Array: (optional) Array of inputformatter functions. Each array
item responds to a function parameter, so if you want some parameters not to be formatted,
add a null instead.
– outputFormatter - ``Function: (optional) Can be used to format the output of
the method.
9.6.2 Returns
9.6.3 Example
web3.extend({
property: 'myModule',
methods: [{
name: 'getBalance',
call: 'eth_getBalance',
params: 2,
inputFormatter: [web3.extend.formatters.inputAddressFormatter, web3.extend.
˓→formatters.inputDefaultBlockNumberFormatter],
outputFormatter: web3.utils.hexToNumberString
},{
name: 'getGasPriceSuperFunction',
call: 'eth_gasPriceSuper',
params: 2,
inputFormatter: [null, web3.utils.numberToHex]
}]
});
web3.extend({
methods: [{
name: 'directCall',
call: 'eth_callForFun',
}]
});
console.log(web3);
> Web3 {
myModule: {
getBalance: function(){},
getGasPriceSuperFunction: function(){}
},
directCall: function(){},
eth: Eth {...},
bzz: Bzz {...},
...
}
9.7 newAccount
web3.eth.personal.newAccount(password, [callback])
Note: Never call this function over a unsecured Websocket or HTTP provider, as your password will be sent in plain
text!
9.7.1 Parameters
9.7.2 Returns
9.7.3 Example
web3.eth.personal.newAccount('!@superpassword')
.then(console.log);
> '0x1234567891011121314151617181920212223456'
9.8 sign
Adding a prefix to the message makes the calculated signature recognisable as an Ethereum specific signature.
If you have the original message and the signed message, you can discover the signing account address using
web3.eth.personal.ecRecover. See example below.
Note: Sending your account password over an unsecured HTTP RPC connection is highly unsecure.
9.8.1 Parameters
9.8.2 Returns
9.8.3 Example
.then(console.log);
>
˓→"0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd
˓→"
.then(console.log);
>
˓→"0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd
˓→"
// recover the signing account address using original message and signed message
web3.eth.personal.ecRecover("Hello world", "0x30755ed65396...etc...")
.then(console.log);
> "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe"
9.9 ecRecover
9.9.1 Parameters
1. String - Data that was signed. If String it will be converted using web3.utils.utf8ToHex.
2. String - The signature.
3. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.
9.9.2 Returns
9.9.3 Example
web3.eth.personal.ecRecover("Hello world",
˓→"0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd
˓→").then(console.log);
> "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe"
9.10 signTransaction
Note: Sending your account password over an unsecured HTTP RPC connection is highly unsecure.
9.10.1 Parameters
9.10.2 Returns
Promise returns Object - The RLP encoded transaction. The raw property can be used to send the transaction
using web3.eth.sendSignedTransaction.
9.10.3 Example
web3.eth.signTransaction({
from: "0xEB014f8c8B418Db6b45774c326A0E64C78914dC0",
gasPrice: "20000000000",
gas: "21000",
to: '0x3535353535353535353535353535353535353535',
value: "1000000000000000000",
data: ""
}, 'MyPassword!').then(console.log);
> {
raw:
˓→'0xf86c808504a817c800825208943535353535353535353535353535353535353535880de0b6b3a76400008025a04f4c17
˓→',
tx: {
nonce: '0x0',
gasPrice: '0x4a817c800',
gas: '0x5208',
to: '0x3535353535353535353535353535353535353535',
value: '0xde0b6b3a7640000',
input: '0x',
v: '0x25',
r: '0x4f4c17305743700648bc4f6cd3038ec6f6af0df73e31757007b7f59df7bee88d',
s: '0x7e1941b264348e80c78c4027afc65a87b0a5e43e86742b8ca0823584c6788fd0',
hash: '0xda3be87732110de6c1354c83770aae630ede9ac308d9f7b399ecfba23d923384'
}
}
9.11 sendTransaction
Note: Sending your account password over an unsecured HTTP RPC connection is highly unsecure.
9.11.1 Parameters
9.11.2 Returns
9.11.3 Example
web3.eth.personal.sendTransaction({
from: "0xEB014f8c8B418Db6b45774c326A0E64C78914dC0",
gasPrice: "20000000000",
gas: "21000",
to: '0x3535353535353535353535353535353535353535',
value: "1000000000000000000",
data: ""
}, 'MyPassword!').then(console.log);
> '0xda3be87732110de6c1354c83770aae630ede9ac308d9f7b399ecfba23d923384'
9.12 unlockAccount
Note: Sending your account password over an unsecured HTTP RPC connection is highly unsecure.
9.12.1 Parameters
9.12.2 Example
web3.eth.personal.unlockAccount("0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", "test
˓→password!", 600)
.then(console.log('Account unlocked!'));
> "Account unlocked!"
9.13 lockAccount
web3.eth.personal.lockAccount(address [, callback])
Note: Sending your account password over an unsecured HTTP RPC connection is highly unsecure.
9.13.1 Parameters
1. address - String: The account address. 4. Function - (optional) Optional callback, returns an error object
as first parameter and the result as second.
9.13.2 Returns
Promise<boolean>
9.13.3 Example
web3.eth.personal.lockAccount("0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe")
.then(console.log('Account locked!'));
> "Account locked!"
9.14 getAccounts
web3.eth.personal.getAccounts([callback])
Returns a list of accounts the node controls by using the provider and calling the RPC method
personal_listAccounts. Using web3.eth.accounts.create() will not add accounts into this list. For that use
web3.eth.personal.newAccount().
The results are the same as web3.eth.getAccounts() except that calls the RPC method eth_accounts.
9.14.1 Returns
9.14.2 Example
web3.eth.personal.getAccounts()
.then(console.log);
> ["0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe",
˓→"0xDCc6960376d6C6dEa93647383FfB245CfCed97Cf"]
9.15 importRawKey
web3.eth.personal.importRawKey(privateKey, password)
Imports the given private key into the key store, encrypting it with the passphrase.
Returns the address of the new account.
Note: Sending your account password over an unsecured HTTP RPC connection is highly unsecure.
9.15.1 Parameters
9.15.2 Returns
9.15.3 Example
web3.eth.personal.importRawKey(
˓→"cd3376bb711cb332ee3fb2ca04c6a8b9f70c316fcdf7a1f44ef4c7999483295e", "password1234")
.then(console.log);
> "0x8f337bf484b2fc75e4b0436645dcc226ee2ac531"
web3.eth.ens
The web3.eth.ens functions let you interact with ENS. We recommend reading the ENS documentation to get
deeper insights about the internals of the name service.
10.1 registryAddress
web3.eth.ens.registryAddress;
The registryAddress property can be used to define a custom registry address when you are connected to an
unknown chain.
Note: If no address is defined will it try to detect the registry on the chain you are currently connected with and on
the call of setProvider in the Eth module will it keep the defined address and use it for the ENS module.
10.1.1 Returns
10.1.2 Example
web3.eth.ens.registryAddress;
> "0x314159265dD8dbb310642f98f50C066173C1259b"
129
web3.js Documentation, Release 1.0.0
10.2 registry
web3.eth.ens.registry;
10.2.1 Returns
10.2.2 Example
web3.eth.ens.registry;
> {
contract: Contract,
owner: Function(name, callback), // Deprecated
getOwner: Function(name, callback),
setOwner: Function(name, address, txConfig, callback),
resolver: Function(name, callback), // Deprecated
getResolver: Function(name, callback),
setResolver: Function(name, address, txConfig, callback),
getTTL: Function(name, callback),
setTTL: Function(name, ttl, txConfig, callback),
setSubnodeOwner: Function(name, label, address, txConfig, callback),
setRecord(name, owner, resolver, ttl, txConfig, callback),
setSubnodeRecord(name, label, owner, resolver, ttl, txConfig, callback),
setApprovalForAll(operator, approved, txConfig, callback),
isApprovedForAll(owner, operator, txConfig, callback),
(continues on next page)
10.3 resolver
web3.eth.ens.resolver(name [, callback]);
10.3.1 Parameters
10.3.2 Returns
10.3.3 Example
web3.eth.ens.resolver('ethereum.eth').then(function (contract) {
console.log(contract);
});
> Contract<Resolver>
10.4 getResolver
web3.eth.ens.getResolver(name [, callback]);
10.4.1 Parameters
10.4.2 Returns
10.4.3 Example
web3.eth.ens.getResolver('ethereum.eth').then(function (contract) {
console.log(contract);
});
> Contract<Resolver>
10.5 setResolver
10.5.1 Parameters
10.5.2 Returns
PromiEvent<TransactionReceipt | TransactionRevertInstructionError>
10.5.3 Example
10.6 getOwner
web3.eth.ens.getOwner(name [, callback]);
10.6.1 Parameters
10.6.2 Returns
10.6.3 Example
web3.eth.ens.getOwner('ethereum.eth').then(function (owner) {
console.log(owner);
});
> '0x...'
10.7 setOwner
10.7.1 Parameters
10.7.2 Returns
PromiEvent<TransactionReceipt | TransactionRevertInstructionError>
10.7.3 Example
10.8 getTTL
web3.eth.ens.getTTL(name [, callback]);
10.8.1 Parameters
10.8.2 Returns
Promise<Number>
10.8.3 Example
web3.eth.ens.getTTL('ethereum.eth').then(function (ttl) {
console.log(ttl);
});
> 100000
10.9 setTTL
10.9.1 Parameters
10.9.2 Returns
PromiEvent<TransactionReceipt | TransactionRevertInstructionError>
10.9.3 Example
10.10 setSubnodeOwner
Creates a new subdomain of the given node, assigning ownership of it to the specified owner.
10.10.1 Parameters
10.10.2 Returns
PromiEvent<TransactionReceipt | TransactionRevertInstructionError>
10.10.3 Example
10.11 setRecord
Sets the owner, resolver, and TTL for an ENS record in a single operation.
10.11.1 Parameters
10.11.2 Returns
PromiEvent<TransactionReceipt | TransactionRevertInstructionError>
10.11.3 Example
10.12 setSubnodeRecord
Sets the owner, resolver and TTL for a subdomain, creating it if necessary.
10.12.1 Parameters
10.12.2 Returns
PromiEvent<TransactionReceipt | TransactionRevertInstructionError>
10.12.3 Example
10.13 setApprovalForAll
Sets or clears an approval. Approved accounts can execute all ENS registry operations on behalf of the caller.
10.13.1 Parameters
10.13.2 Returns
PromiEvent<TransactionReceipt | TransactionRevertInstructionError>
10.13.3 Example
10.14 isApprovedForAll
Returns true if the operator is approved to make ENS registry operations on behalf of the owner.
10.14.1 Parameters
10.14.2 Returns
Promise<Boolean>
10.14.3 Example
10.15 recordExists
web3.eth.ens.recordExists(name [, callback]);
Returns true if node exists in this ENS registry. This will return false for records that are in the legacy ENS
registry but have not yet been migrated to the new one.
10.15.1 Parameters
10.15.2 Returns
Promise<Boolean>
10.15.3 Example
10.16 getAddress
web3.eth.ens.getAddress(ENSName [, callback]);
10.16.1 Parameters
10.16.2 Returns
10.16.3 Example
web3.eth.ens.getAddress('ethereum.eth').then(function (address) {
console.log(address);
})
> 0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359
10.17 setAddress
10.17.1 Parameters
10.17.2 Returns
PromiEvent<TransactionReceipt | TransactionRevertInstructionError>
10.17.3 Example
web3.eth.ens.setAddress(
'ethereum.eth',
'0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359',
{
from: '0x9CC9a2c777605Af16872E0997b3Aeb91d96D5D8c'
}
).then(function (result) {
console.log(result.events);
});
> AddrChanged(...)
web3.eth.ens.setAddress(
'ethereum.eth',
'0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359',
{
from: '0x9CC9a2c777605Af16872E0997b3Aeb91d96D5D8c'
}
)
.on('transactionHash', function(hash){
...
})
.on('confirmation', function(confirmationNumber, receipt){
...
})
.on('receipt', function(receipt){
...
})
.on('error', console.error);
web3.eth.ens.resolver('ethereum.eth').then(function (resolver) {
resolver.events.AddrChanged({fromBlock: 0}, function(error, event) {
console.log(event);
})
.on('data', function(event){
console.log(event);
})
.on('changed', function(event){
// remove event from local database
})
.on('error', console.error);
});
For further information on the handling of contract events please see here.
10.18 getPubkey
web3.eth.ens.getPubkey(ENSName [, callback]);
Returns the X and Y coordinates of the curve point for the public key.
10.18.1 Parameters
10.18.2 Returns
10.18.3 Example
web3.eth.ens.getPubkey('ethereum.eth').then(function (result) {
console.log(result)
});
> {
"0": "0x0000000000000000000000000000000000000000000000000000000000000000",
"1": "0x0000000000000000000000000000000000000000000000000000000000000000",
"x": "0x0000000000000000000000000000000000000000000000000000000000000000",
"y": "0x0000000000000000000000000000000000000000000000000000000000000000"
}
10.19 setPubkey
10.19.1 Parameters
10.19.2 Returns
PromiEvent<TransactionReceipt | TransactionRevertInstructionError>
10.19.3 Example
web3.eth.ens.setPubkey(
'ethereum.eth',
'0x0000000000000000000000000000000000000000000000000000000000000000',
'0x0000000000000000000000000000000000000000000000000000000000000000',
{
from: '0x9CC9a2c777605Af16872E0997b3Aeb91d96D5D8c'
}
).then(function (result) {
console.log(result.events);
});
> PubkeyChanged(...)
web3.eth.ens.setPubkey(
'ethereum.eth',
'0x0000000000000000000000000000000000000000000000000000000000000000',
'0x0000000000000000000000000000000000000000000000000000000000000000',
{
from: '0x9CC9a2c777605Af16872E0997b3Aeb91d96D5D8c'
}
)
.on('transactionHash', function(hash){
...
})
.on('confirmation', function(confirmationNumber, receipt){
...
})
.on('receipt', function(receipt){
...
})
.on('error', console.error);
web3.eth.ens.resolver('ethereum.eth').then(function (resolver) {
resolver.events.PubkeyChanged({fromBlock: 0}, function(error, event) {
console.log(event);
})
.on('data', function(event){
console.log(event);
})
.on('changed', function(event){
// remove event from local database
})
.on('error', console.error);
});
For further information on the handling of contract events please see here.
10.20 getContent
web3.eth.ens.getContent(ENSName [, callback]);
10.20.1 Parameters
10.20.2 Returns
10.20.3 Example
web3.eth.ens.getContent('ethereum.eth').then(function (result) {
console.log(result);
});
> "0x0000000000000000000000000000000000000000000000000000000000000000"
10.21 setContent
10.21.1 Parameters
10.21.2 Returns
PromiEvent<TransactionReceipt | TransactionRevertInstructionError>
10.21.3 Example
web3.eth.ens.setContent(
'ethereum.eth',
'0x0000000000000000000000000000000000000000000000000000000000000000',
{
from: '0x9CC9a2c777605Af16872E0997b3Aeb91d96D5D8c'
}
).then(function (result) {
console.log(result.events);
});
> ContentChanged(...)
web3.eth.ens.setContent(
'ethereum.eth',
'0x0000000000000000000000000000000000000000000000000000000000000000',
{
from: '0x9CC9a2c777605Af16872E0997b3Aeb91d96D5D8c'
}
)
.on('transactionHash', function(hash){
...
})
.on('confirmation', function(confirmationNumber, receipt){
...
})
.on('receipt', function(receipt){
...
})
.on('error', console.error);
web3.eth.ens.resolver('ethereum.eth').then(function (resolver) {
resolver.events.ContentChanged({fromBlock: 0}, function(error, event) {
console.log(event);
})
.on('data', function(event){
console.log(event);
})
.on('changed', function(event){
// remove event from local database
})
.on('error', console.error);
});
For further information on the handling of contract events please see here.
10.22 getContenthash
web3.eth.ens.getContenthash(ENSName [, callback]);
10.22.1 Parameters
10.22.2 Returns
10.22.3 Example
web3.eth.ens.getContenthash('ethereum.eth').then(function (result) {
console.log(result);
});
> {
"protocolType": "ipfs",
"decoded": "QmaEBknbGT4bTQiQoe2VNgBJbRfygQGktnaW5TbuKixjYL"
}
10.23 setContenthash
10.23.1 Parameters
10.23.2 Returns
PromiEvent<TransactionReceipt | TransactionRevertInstructionError>
10.23.3 Example
web3.eth.ens.setContenthash(
'ethereum.eth',
'ipfs://QmaEBknbGT4bTQiQoe2VNgBJbRfygQGktnaW5TbuKixjYL',
{
from: '0x9CC9a2c777605Af16872E0997b3Aeb91d96D5D8c'
}
).then(function (result) {
console.log(result.events);
});
> ContenthashChanged(...)
web3.eth.ens.setContenthash(
'ethereum.eth',
'ipfs://QmaEBknbGT4bTQiQoe2VNgBJbRfygQGktnaW5TbuKixjYL',
{
from: '0x9CC9a2c777605Af16872E0997b3Aeb91d96D5D8c'
}
)
.on('transactionHash', function(hash){
...
})
.on('confirmation', function(confirmationNumber, receipt){
...
})
.on('receipt', function(receipt){
...
})
.on('error', console.error);
web3.eth.ens.resolver('ethereum.eth').then(function (resolver) {
resolver.events.ContenthashChanged({fromBlock: 0}, function(error, event) {
console.log(event);
})
.on('data', function(event){
console.log(event);
})
.on('changed', function(event){
// remove event from local database
})
.on('error', console.error);
});
For further information on the handling of contract events please see here.
10.24 getMultihash
web3.eth.ens.getMultihash(ENSName [, callback]);
10.24.1 Parameters
10.24.2 Returns
10.24.3 Example
web3.eth.ens.getMultihash('ethereum.eth').then(function (result) {
console.log(result);
});
> 'QmXpSwxdmgWaYrgMUzuDWCnjsZo5RxphE3oW7VhTMSCoKK'
10.25 supportsInterface
Returns true if the related Resolver does support the given signature or interfaceId.
10.25.1 Parameters
10.25.2 Returns
Promise<Boolean>
10.25.3 Example
console.log(result);
});
> true
10.26 setMultihash
10.26.1 Parameters
10.26.2 Returns
PromiEvent<TransactionReceipt | TransactionRevertInstructionError>
10.26.3 Example
web3.eth.ens.setMultihash(
'ethereum.eth',
'QmXpSwxdmgWaYrgMUzuDWCnjsZo5RxphE3oW7VhTMSCoKK',
{
from: '0x9CC9a2c777605Af16872E0997b3Aeb91d96D5D8c'
}
).then(function (result) {
console.log(result.events);
});
> MultihashChanged(...)
web3.eth.ens.setMultihash(
'ethereum.eth',
'QmXpSwxdmgWaYrgMUzuDWCnjsZo5RxphE3oW7VhTMSCoKK',
{
from: '0x9CC9a2c777605Af16872E0997b3Aeb91d96D5D8c'
}
)
.on('transactionHash', function(hash){
...
})
.on('confirmation', function(confirmationNumber, receipt){
...
})
.on('receipt', function(receipt){
...
})
.on('error', console.error);
For further information on the handling of contract events please see here.
The ENS API provides the possibility for listening to all ENS related events.
10.27.2 Returns
PromiEvent<TransactionReceipt | TransactionRevertInstructionError>
10.27.3 Example
web3.eth.ens.resolver('ethereum.eth').then(function (resolver) {
resolver.events.AddrChanged({fromBlock: 0}, function(error, event) {
console.log(event);
})
.on('data', function(event){
console.log(event);
})
.on('changed', function(event){
// remove event from local database
})
.on('error', console.error);
});
> {
returnValues: {
node: '0x123456789...',
a: '0x123456789...',
},
raw: {
data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
topics: [
'0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
'0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'
]
},
event: 'AddrChanged',
signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
logIndex: 0,
transactionIndex: 0,
transactionHash:
˓→'0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
blockNumber: 1234,
(continues on next page)
1. Transfer(node bytes32, owner address) 1. NewOwner(node bytes32, label bytes32, owner address) 1. NewRe-
solver(node bytes32, resolver address) 1. NewTTL(node bytes32, ttl uint64)
10.27.5 Example
web3.eth.ens.resistry.then(function (registry) {
registry.events.Transfer({fromBlock: 0}, , function(error, event) {
console.log(event);
})
.on('data', function(event){
console.log(event);
})
.on('changed', function(event){
// remove event from local database
})
.on('error', console.error);
});
> {
returnValues: {
node: '0x123456789...',
owner: '0x123456789...',
},
raw: {
data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
topics: [
'0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
'0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'
]
},
event: 'Transfer',
signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
logIndex: 0,
transactionIndex: 0,
transactionHash:
˓→'0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
blockNumber: 1234,
address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'
}
For further information on the handling of contract events please see here.
web3.eth.Iban
The web3.eth.Iban function converts Ethereum addresses from and to IBAN and BBAN.
new web3.eth.Iban(ibanAddress)
151
web3.js Documentation, Release 1.0.0
11.2.1 Parameters
11.2.2 Returns
11.2.3 Example
11.3 toAddress
Static function.
web3.eth.Iban.toAddress(ibanAddress)
11.3.1 Parameters
11.3.2 Returns
11.3.3 Example
web3.eth.Iban.toAddress("XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS");
> "0x00c5496aEe77C1bA1f0854206A26DdA82a81D6D8"
11.4 toIban
Static function.
web3.eth.Iban.toIban(address)
11.4.1 Parameters
11.4.2 Returns
11.4.3 Example
web3.eth.Iban.toIban("0x00c5496aEe77C1bA1f0854206A26DdA82a81D6D8");
> "XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"
11.5 fromAddress
web3.eth.Iban.fromAddress(address)
11.5.1 Parameters
11.5.2 Returns
11.5.3 Example
web3.eth.Iban.fromAddress("0x00c5496aEe77C1bA1f0854206A26DdA82a81D6D8");
> Iban {_iban: "XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"}
11.6 fromBban
web3.eth.Iban.fromBban(bbanAddress)
11.6.1 Parameters
11.6.2 Returns
11.6.3 Example
web3.eth.Iban.fromBban('ETHXREGGAVOFYORK');
> Iban {_iban: "XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"}
11.7 createIndirect
web3.eth.Iban.createIndirect(options)
11.7.1 Parameters
11.7.2 Returns
11.7.3 Example
web3.eth.Iban.createIndirect({
institution: "XREG",
identifier: "GAVOFYORK"
});
> Iban {_iban: "XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"}
11.8 isValid
web3.eth.Iban.isValid(ibanAddress)
11.8.1 Parameters
11.8.2 Returns
Boolean
11.8.3 Example
web3.eth.Iban.isValid("XE81ETHXREGGAVOFYORK");
> true
web3.eth.Iban.isValid("XE82ETHXREGGAVOFYORK");
> false // because the checksum is incorrect
11.9 prototype.isValid
web3.eth.Iban.prototype.isValid()
11.9.1 Parameters
11.9.2 Returns
Boolean
11.9.3 Example
11.10 prototype.isDirect
web3.eth.Iban.prototype.isDirect()
11.10.1 Parameters
none
11.10.2 Returns
Boolean
11.10.3 Example
11.11 prototype.isIndirect
web3.eth.Iban.prototype.isIndirect()
11.11.1 Parameters
none
11.11.2 Returns
Boolean
11.11.3 Example
11.12 prototype.checksum
web3.eth.Iban.prototype.checksum()
11.12.1 Parameters
none
11.12.2 Returns
11.12.3 Example
11.13 prototype.institution
web3.eth.Iban.prototype.institution()
11.13.1 Parameters
none
11.13.2 Returns
11.13.3 Example
11.14 prototype.client
web3.eth.Iban.prototype.client()
11.14.1 Parameters
none
11.14.2 Returns
11.14.3 Example
11.15 prototype.toAddress
web3.eth.Iban.prototype.toString()
11.15.1 Parameters
none
11.15.2 Returns
11.15.3 Example
11.16 prototype.toString
web3.eth.Iban.prototype.toString()
11.16.1 Parameters
none
11.16.2 Returns
11.16.3 Example
web3.eth.abi
The web3.eth.abi functions let you encode and decode parameters to ABI (Application Binary Interface) for
function calls to the EVM (Ethereum Virtual Machine).
12.1 encodeFunctionSignature
web3.eth.abi.encodeFunctionSignature(functionName);
Encodes the function name to its ABI signature, which are the first 4 bytes of the sha3 hash of the function name
including types.
12.1.1 Parameters
1. functionName - String|Object: The function name to encode. or the JSON interface object of the function.
If string it has to be in the form function(type,type,...), e.g: myFunction(uint256,uint32[],
bytes10,bytes)
12.1.2 Returns
12.1.3 Example
161
web3.js Documentation, Release 1.0.0
// Or string
web3.eth.abi.encodeFunctionSignature('myMethod(uint256,string)')
> '0x24ee0097'
12.2 encodeEventSignature
web3.eth.abi.encodeEventSignature(eventName);
Encodes the event name to its ABI signature, which are the sha3 hash of the event name including input types.
12.2.1 Parameters
1. eventName - String|Object: The event name to encode. or the JSON interface object of the event. If string
it has to be in the form event(type,type,...), e.g: myEvent(uint256,uint32[],bytes10,bytes)
12.2.2 Returns
12.2.3 Example
web3.eth.abi.encodeEventSignature('myEvent(uint256,bytes32)')
> 0xf2eeb729e636a8cb783be044acf6b7b1e2c5863735b60d6daae84c366ee87d97
12.3 encodeParameter
web3.eth.abi.encodeParameter(type, parameter);
12.3.1 Parameters
1. type - String|Object: The type of the parameter, see the solidity documentation for a list of types.
2. parameter - Mixed: The actual parameter to encode.
12.3.2 Returns
12.3.3 Example
web3.eth.abi.encodeParameter('uint256', '2345675643');
> "0x000000000000000000000000000000000000000000000000000000008bd02b7b"
web3.eth.abi.encodeParameter('uint256', '2345675643');
> "0x000000000000000000000000000000000000000000000000000000008bd02b7b"
web3.eth.abi.encodeParameter('bytes32', '0xdf3234');
> "0xdf32340000000000000000000000000000000000000000000000000000000000"
web3.eth.abi.encodeParameter('bytes', '0xdf3234');
>
˓→"0x000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000
˓→"
˓→"
web3.eth.abi.encodeParameter(
{
"ParentStruct": {
"propertyOne": 'uint256',
"propertyTwo": 'uint256',
"childStruct": {
"propertyOne": 'uint256',
"propertyTwo": 'uint256'
}
}
},
{
"propertyOne": 42,
"propertyTwo": 56,
"childStruct": {
"propertyOne": 45,
(continues on next page)
12.4 encodeParameters
web3.eth.abi.encodeParameters(typesArray, parameters);
12.4.1 Parameters
12.4.2 Returns
12.4.3 Example
˓→"
web3.eth.abi.encodeParameters(
[
'uint8[]',
{
"ParentStruct": {
"propertyOne": 'uint256',
"propertyTwo": 'uint256',
"ChildStruct": {
"propertyOne": 'uint256',
"propertyTwo": 'uint256'
}
}
}
(continues on next page)
12.5 encodeFunctionCall
web3.eth.abi.encodeFunctionCall(jsonInterface, parameters);
Encodes a function call using its JSON interface object and given parameters.
12.5.1 Parameters
12.5.2 Returns
String - The ABI encoded function call. Means function signature + parameters.
12.5.3 Example
web3.eth.abi.encodeFunctionCall({
name: 'myMethod',
type: 'function',
inputs: [{
type: 'uint256',
name: 'myNumber'
},{
type: 'string',
name: 'myString'
}]
}, ['2345675643', 'Hello!%']);
>
˓→"0x24ee0097000000000000000000000000000000000000000000000000000000008bd02b7b000000000000000000000000
˓→"
12.6 decodeParameter
web3.eth.abi.decodeParameter(type, hexString);
12.6.1 Parameters
1. type - String|Object: The type of the parameter, see the solidity documentation for a list of types.
2. hexString - String: The ABI byte code to decode.
12.6.2 Returns
12.6.3 Example
web3.eth.abi.decodeParameter('uint256',
˓→'0x0000000000000000000000000000000000000000000000000000000000000010');
> "16"
web3.eth.abi.decodeParameter('string',
˓→'0x000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000
˓→');
> "Hello!%!"
web3.eth.abi.decodeParameter('string',
˓→'0x000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000
˓→');
> "Hello!%!"
web3.eth.abi.decodeParameter(
{
"ParentStruct": {
"propertyOne": 'uint256',
"propertyTwo": 'uint256',
"childStruct": {
"propertyOne": 'uint256',
"propertyTwo": 'uint256'
}
}
},
,
˓→'0x000000000000000000000000000000000000000000000000000000000000002a00000000000000000000000000000000
˓→');
> {
'0': {
(continues on next page)
12.7 decodeParameters
web3.eth.abi.decodeParameters(typesArray, hexString);
12.7.1 Parameters
12.7.2 Returns
12.7.3 Example
web3.eth.abi.decodeParameters(['string', 'uint256'],
˓→'0x000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000
˓→');
web3.eth.abi.decodeParameters([{
type: 'string',
name: 'myString'
},{
type: 'uint256',
name: 'myNumber'
}],
˓→'0x000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000
˓→');
> Result {
'0': 'Hello!%!',
'1': '234',
myString: 'Hello!%!',
myNumber: '234'
}
web3.eth.abi.decodeParameters([
'uint8[]',
{
"ParentStruct": {
"propertyOne": 'uint256',
"propertyTwo": 'uint256',
"childStruct": {
"propertyOne": 'uint256',
"propertyTwo": 'uint256'
}
}
}
],
˓→'0x00000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000
˓→');
> Result {
'0': ['42', '24'],
'1': {
'0': '42',
'1': '56',
'2':
{
'0': '45',
'1': '78',
'propertyOne': '45',
'propertyTwo': '78'
},
'childStruct':
{
(continues on next page)
12.8 decodeLog
12.8.1 Parameters
1. inputs - Object: A JSON interface inputs array. See the solidity documentation for a list of types.
2. hexString - String: The ABI byte code in the data field of a log.
3. topics - Array: An array with the index parameter topics of the log, without the topic[0] if it’s a non-
anonymous event, otherwise with topic[0].
12.8.2 Returns
12.8.3 Example
web3.eth.abi.decodeLog([{
type: 'string',
name: 'myString'
},{
type: 'uint256',
name: 'myNumber',
indexed: true
},{
type: 'uint8',
name: 'mySmallNumber',
indexed: true
}],
˓→ '0x000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000
˓→ ',
['0x000000000000000000000000000000000000000000000000000000000000f310',
˓→'0x0000000000000000000000000000000000000000000000000000000000000010']);
> Result {
(continues on next page)
web3.*.net
The web3-net package allows you to interact with an Ethereum node’s network properties.
// -> web3.eth.net
// -> web3.bzz.net
// -> web3.shh.net
13.1 getId
web3.eth.net.getId([callback])
web3.bzz.net.getId([callback])
web3.shh.net.getId([callback])
13.1.1 Parameters
none
171
web3.js Documentation, Release 1.0.0
13.1.2 Returns
13.1.3 Example
web3.eth.net.getId()
.then(console.log);
> 1
13.2 isListening
web3.eth.net.isListening([callback])
web3.bzz.net.isListening([callback])
web3.shh.net.isListening([callback])
13.2.1 Parameters
none
13.2.2 Returns
13.2.3 Example
web3.eth.net.isListening()
.then(console.log);
> true
13.3 getPeerCount
web3.eth.net.getPeerCount([callback])
web3.bzz.net.getPeerCount([callback])
web3.shh.net.getPeerCount([callback])
13.3.1 Parameters
none
13.3.2 Returns
13.3.3 Example
web3.eth.net.getPeerCount()
.then(console.log);
> 25
web3.bzz
The web3-bzz package allows you to interact with swarm, the decentralized file store. For more see the Swarm
Docs.
// will autodetect if the "ethereum" object is present and will either connect to the
˓→local swarm node, or the swarm-gateways.net.
// Optional you can give your own provider URL; If no provider URL is given it will
˓→use "http://swarm-gateways.net"
14.1 setProvider
175
web3.js Documentation, Release 1.0.0
web3.bzz.setProvider(myProvider)
Note: When called on the umbrella package web3 it will also set the provider for all sub modules web3.eth,
web3.shh, etc. EXCEPT web3.bzz which needs a separate provider at all times.
14.1.1 Parameters
14.1.2 Returns
Boolean
14.1.3 Example
// change provider
bzz.setProvider('http://swarm-gateways.net');
14.2 givenProvider
web3.bzz.givenProvider
When using web3.js in an Ethereum compatible browser, it will set with the current native provider by that browser.
Returns the given provider by the (browser) environment, otherwise null.
14.2.1 Returns
14.2.2 Example
bzz.givenProvider;
> {
send: function(),
on: function(),
bzz: "http://localhost:8500",
shh: true,
...
(continues on next page)
bzz.setProvider(bzz.givenProvider || "http://swarm-gateways.net");
14.3 currentProvider
bzz.currentProvider
14.3.1 Returns
14.3.2 Example
bzz.currentProvider;
> "http://localhost:8500"
if(!bzz.currentProvider) {
bzz.setProvider("http://swarm-gateways.net");
}
14.4 upload
web3.bzz.upload(mixed)
14.4.1 Parameters
1. mixed - String|Buffer|Uint8Array|Object: The data to upload, can be a file content, file Buffer/Uint8Array, mu
14.4.2 Returns
14.4.3 Example
// raw data
bzz.upload("test file").then(function(hash) {
console.log("Uploaded file. Address:", hash);
})
// raw directory
var dir = {
"/foo.txt": {type: "text/plain", data: "sample file"},
"/bar.txt": {type: "text/plain", data: "another file"}
};
bzz.upload(dir).then(function(hash) {
console.log("Uploaded directory. Address:", hash);
});
14.5 download
web3.bzz.download(bzzHash [, localpath])
Downloads files and folders from swarm as buffer or to disk (only node.js).
14.5.1 Parameters
1. bzzHash - String: The file or directory to download. If the hash is a raw file it will return a Buffer, if a
manifest file, it will return the directory structure. If the localpath is given, it will return that path where it
downloaded the files to.
2. localpath - String: The local folder to download the content into. (only node.js)
14.5.2 Returns
Promise returning Buffer|Object|String: The Buffer of the file downloaded, an object with the directory
structure, or the path where it was downloaded to.
14.5.3 Example
}
});
14.6 pick
web3.bzz.pick.file()
web3.bzz.pick.directory()
web3.bzz.pick.data()
14.6.1 Parameters
none
14.6.2 Returns
14.6.3 Example
web3.bzz.pick.file()
.then(console.log);
> {
...
}
web3.shh
The web3-shh package allows you to interact with the whisper protocol for broadcasting. For more see Whisper
Overview.
// -> web3.shh
15.1 setProvider
web3.setProvider(myProvider)
web3.eth.setProvider(myProvider)
web3.shh.setProvider(myProvider)
web3.bzz.setProvider(myProvider)
...
Note: When called on the umbrella package web3 it will also set the provider for all sub modules web3.eth,
web3.shh, etc. EXCEPT web3.bzz which needs a separate provider at all times.
181
web3.js Documentation, Release 1.0.0
15.1.1 Parameters
15.1.2 Returns
Boolean
// change provider
web3.setProvider('ws://localhost:8546');
// or
web3.setProvider(new Web3.providers.WebsocketProvider('ws://localhost:8546'));
15.2 providers
web3.providers
web3.eth.providers
web3.shh.providers
web3.bzz.providers
...
15.2.1 Value
15.2.2 Example
15.2.3 Configuration
// ====
// Http
// ====
var options = {
keepAlive: true,
withCredentials: false,
timeout: 20000, // ms
headers: [
{
name: 'Access-Control-Allow-Origin',
value: '*'
},
{
...
}
],
agent: {
http: http.Agent(...),
baseUrl: ''
}
(continues on next page)
// ==========
// Websockets
// ==========
var options = {
timeout: 30000, // ms
clientConfig: {
// Useful if requests are large
maxReceivedFrameSize: 100000000, // bytes - default: 1MiB
maxReceivedMessageSize: 100000000, // bytes - default: 8MiB
More information for the Http and Websocket provider modules can be found here:
• HttpProvider
• WebsocketProvider
15.3 givenProvider
web3.givenProvider
web3.eth.givenProvider
web3.shh.givenProvider
web3.bzz.givenProvider
...
When using web3.js in an Ethereum compatible browser, it will set with the current native provider by that browser.
Will return the given provider by the (browser) environment, otherwise null.
15.3.1 Returns
15.3.2 Example
15.4 currentProvider
web3.currentProvider
web3.eth.currentProvider
web3.shh.currentProvider
web3.bzz.currentProvider
...
15.4.1 Returns
15.4.2 Example
15.5 BatchRequest
new web3.BatchRequest()
new web3.eth.BatchRequest()
new web3.shh.BatchRequest()
new web3.bzz.BatchRequest()
15.5.1 Parameters
none
15.5.2 Returns
15.5.3 Example
batch.add(contract.methods.balance(address).call.request({from:
˓→'0x0000000000000000000000000000000000000000'}, callback2));
batch.execute();
15.6 extend
web3.extend(methods)
web3.eth.extend(methods)
web3.shh.extend(methods)
web3.bzz.extend(methods)
...
Note: You also have *.extend.formatters as additional formatter functions to be used for input and output
formatting. Please see the source file for function details.
15.6.1 Parameters
1. methods - Object: Extension object with array of methods description objects as follows:
• property - String: (optional) The name of the property to add to the module. If no property is
set it will be added to the module directly.
• methods - Array: The array of method descriptions:
– name - String: Name of the method to add.
– call - String: The RPC method name.
– params - Number: (optional) The number of parameters for that function. Default 0.
– inputFormatter - Array: (optional) Array of inputformatter functions. Each ar-
ray item responds to a function parameter, so if you want some parameters not to be
formatted, add a null instead.
– outputFormatter - ``Function: (optional) Can be used to format the output
of the method.
15.6.2 Returns
15.6.3 Example
web3.extend({
property: 'myModule',
methods: [{
name: 'getBalance',
call: 'eth_getBalance',
params: 2,
inputFormatter: [web3.extend.formatters.inputAddressFormatter, web3.extend.
˓→formatters.inputDefaultBlockNumberFormatter],
outputFormatter: web3.utils.hexToNumberString
},{
name: 'getGasPriceSuperFunction',
call: 'eth_gasPriceSuper',
params: 2,
inputFormatter: [null, web3.utils.numberToHex]
}]
});
web3.extend({
methods: [{
name: 'directCall',
call: 'eth_callForFun',
}]
});
console.log(web3);
> Web3 {
myModule: {
getBalance: function(){},
getGasPriceSuperFunction: function(){}
},
directCall: function(){},
eth: Eth {...},
bzz: Bzz {...},
...
}
15.7 getId
web3.eth.net.getId([callback])
web3.bzz.net.getId([callback])
web3.shh.net.getId([callback])
15.7.1 Parameters
none
15.7.2 Returns
15.7.3 Example
web3.eth.net.getId()
.then(console.log);
> 1
15.8 isListening
web3.eth.net.isListening([callback])
web3.bzz.net.isListening([callback])
web3.shh.net.isListening([callback])
15.8.1 Parameters
none
15.8.2 Returns
15.8.3 Example
web3.eth.net.isListening()
.then(console.log);
> true
15.9 getPeerCount
web3.eth.net.getPeerCount([callback])
web3.bzz.net.getPeerCount([callback])
web3.shh.net.getPeerCount([callback])
15.9.1 Parameters
none
15.9.2 Returns
15.9.3 Example
web3.eth.net.getPeerCount()
.then(console.log);
> 25
15.10 getVersion
web3.shh.getVersion([callback])
15.10.1 Parameters
1. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.
15.10.2 Returns
15.10.3 Example
web3.shh.getVersion()
.then(console.log);
> "5.0"
15.11 getInfo
web3.shh.getInfo([callback])
15.11.1 Parameters
1. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.
15.11.2 Returns
15.11.3 Example
web3.shh.getInfo()
.then(console.log);
> {
"minPow": 0.8,
"maxMessageSize": 12345,
"memory": 1234335,
"messages": 20
}
15.12 setMaxMessageSize
web3.shh.setMaxMessageSize(size, [callback])
Sets the maximal message size allowed by this node. Incoming and outgoing messages with a larger size will be
rejected. Whisper message size can never exceed the limit imposed by the underlying P2P protocol (10 Mb).
15.12.1 Parameters
15.12.2 Returns
15.12.3 Example
web3.shh.setMaxMessageSize(1234565)
.then(console.log);
> true
15.13 setMinPoW
web3.shh.setMinPoW(pow, [callback])
15.13.1 Parameters
15.13.2 Returns
15.13.3 Example
web3.shh.setMinPoW(0.9)
.then(console.log);
> true
15.14 markTrustedPeer
web3.shh.markTrustedPeer(enode, [callback])
Marks specific peer trusted, which will allow it to send historic (expired) messages.
Note: This function is not adding new nodes, the node needs to be an existing peer.
15.14.1 Parameters
15.14.2 Returns
15.14.3 Example
web3.shh.markTrustedPeer()
.then(console.log);
> true
15.15 newKeyPair
web3.shh.newKeyPair([callback])
Generates a new public and private key pair for message decryption and encryption.
15.15.1 Parameters
1. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.
15.15.2 Returns
15.15.3 Example
web3.shh.newKeyPair()
.then(console.log);
> "5e57b9ffc2387e18636e0a3d0c56b023264c16e78a2adcba1303cefc685e610f"
15.16 addPrivateKey
web3.shh.addPrivateKey(privateKey, [callback])
Stores a key pair derived from a private key, and returns its ID.
15.16.1 Parameters
15.16.2 Returns
15.16.3 Example
web3.shh.addPrivateKey(
˓→'0x8bda3abeb454847b515fa9b404cede50b1cc63cfdeddd4999d074284b4c21e15')
.then(console.log);
> "3e22b9ffc2387e18636e0a3d0c56b023264c16e78a2adcba1303cefc685e610f"
15.17 deleteKeyPair
web3.shh.deleteKeyPair(id, [callback])
15.17.1 Parameters
1. String - The key pair ID, returned by the creation functions (shh.newKeyPair and shh.
addPrivateKey).
2. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.
15.17.2 Returns
15.17.3 Example
web3.shh.deleteKeyPair(
˓→'3e22b9ffc2387e18636e0a3d0c56b023264c16e78a2adcba1303cefc685e610f')
.then(console.log);
> true
15.18 hasKeyPair
web3.shh.hasKeyPair(id, [callback])
Checks if the whisper node has a private key of a key pair matching the given ID.
15.18.1 Parameters
1. String - The key pair ID, returned by the creation functions (shh.newKeyPair and shh.
addPrivateKey).
2. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.
15.18.2 Returns
Boolean - true on if the key pair exist in the node, false if not. Error on failure.
15.18.3 Example
web3.shh.hasKeyPair('fe22b9ffc2387e18636e0a3d0c56b023264c16e78a2adcba1303cefc685e610f
˓→')
.then(console.log);
> true
15.19 getPublicKey
web3.shh.getPublicKey(id, [callback])
15.19.1 Parameters
1. String - The key pair ID, returned by the creation functions (shh.newKeyPair and shh.
addPrivateKey).
2. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.
15.19.2 Returns
15.19.3 Example
web3.shh.getPublicKey(
˓→'3e22b9ffc2387e18636e0a3d0c56b023264c16e78a2adcba1303cefc685e610f')
.then(console.log);
>
˓→"0x04d1574d4eab8f3dde4d2dc7ed2c4d699d77cbbdd09167b8fffa099652ce4df00c4c6e0263eafe05007a46fdf0c8d32b
˓→"
15.20 getPrivateKey
web3.shh.getPrivateKey(id, [callback])
15.20.1 Parameters
1. String - The key pair ID, returned by the creation functions (shh.newKeyPair and shh.
addPrivateKey).
2. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.
15.20.2 Returns
15.20.3 Example
web3.shh.getPrivateKey(
˓→'3e22b9ffc2387e18636e0a3d0c56b023264c16e78a2adcba1303cefc685e610f')
.then(console.log);
> "0x234234e22b9ffc2387e18636e0534534a3d0c56b0243567432453264c16e78a2adc"
15.21 newSymKey
web3.shh.newSymKey([callback])
Generates a random symmetric key and stores it under an ID, which is then returned. Will be used for encrypting and
decrypting of messages where the sym key is known to both parties.
15.21.1 Parameters
1. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.
15.21.2 Returns
15.21.3 Example
web3.shh.newSymKey()
.then(console.log);
> "cec94d139ff51d7df1d228812b90c23ec1f909afa0840ed80f1e04030bb681e4"
15.22 addSymKey
web3.shh.addSymKey(symKey, [callback])
15.22.1 Parameters
15.22.2 Returns
15.22.3 Example
web3.shh.addSymKey('0x5e11b9ffc2387e18636e0a3d0c56b023264c16e78a2adcba1303cefc685e610f
˓→')
.then(console.log);
> "fea94d139ff51d7df1d228812b90c23ec1f909afa0840ed80f1e04030bb681e4"
15.23 generateSymKeyFromPassword
web3.shh.generateSymKeyFromPassword(password, [callback])
Generates the key from password, stores it, and returns its ID.
15.23.1 Parameters
15.23.2 Returns
15.23.3 Example
15.24 hasSymKey
web3.shh.hasSymKey(id, [callback])
15.24.1 Parameters
1. String - The key pair ID, returned by the creation functions (shh.newSymKey, shh.addSymKey or
shh.generateSymKeyFromPassword).
2. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.
15.24.2 Returns
Boolean - true on if the symmetric key exist in the node, false if not. Error on failure.
15.24.3 Example
web3.shh.hasSymKey('f6dcf21ed6a17bd78d8c4c63195ab997b3b65ea683705501eae82d32667adc92')
.then(console.log);
> true
15.25 getSymKey
web3.shh.getSymKey(id, [callback])
15.25.1 Parameters
1. String - The key pair ID, returned by the creation functions (shh.newKeyPair and shh.
addPrivateKey).
2. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.
15.25.2 Returns
15.25.3 Example
web3.shh.getSymKey('af33b9ffc2387e18636e0a3d0c56b023264c16e78a2adcba1303cefc685e610f')
.then(console.log);
> "0xa82a520aff70f7a989098376e48ec128f25f767085e84d7fb995a9815eebff0a"
15.26 deleteSymKey
web3.shh.deleteSymKey(id, [callback])
15.26.1 Parameters
1. String - The key pair ID, returned by the creation functions (shh.newKeyPair and shh.
addPrivateKey).
2. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.
15.26.2 Returns
15.26.3 Example
web3.shh.deleteSymKey(
˓→'bf31b9ffc2387e18636e0a3d0c56b023264c16e78a2adcba1303cefc685e610f')
.then(console.log);
> true
15.27 post
web3.shh.post(object [, callback])
This method should be called, when we want to post whisper a message to the network.
15.27.1 Parameters
15.27.2 Returns
Promise - returns a promise. Upon success, the then function will be passed a string representing the hash of the
sent message. On error, the catch function will be passed a string containing the reason for the error.
15.27.3 Example
Promise.all([
web3.shh.newSymKey().then((id) => {identities.symKey = id;}),
web3.shh.newKeyPair().then((id) => {identities.keyPair = id;})
]).then(() => {
}).then(() => {
web3.shh.post({
symKeyID: identities.symKey, // encrypts using the sym key ID
sig: identities.keyPair, // signs the message using the keyPair ID
ttl: 10,
topic: '0xffaadd11',
payload: '0xffffffdddddd1122',
powTime: 3,
powTarget: 0.5
}).then(h => console.log(`Message with hash ${h} was successfuly sent`))
.catch(err => console.log("Error: ", err));
});
15.28 subscribe
15.28.1 Parameters
15.28.3 Example
web3.shh.subscribe('messages', {
symKeyID: 'bf31b9ffc2387e18636e0a3d0c56b023264c16e78a2adcba1303cefc685e610f',
sig:
˓→'0x04d1574d4eab8f3dde4d2dc7ed2c4d699d77cbbdd09167b8fffa099652ce4df00c4c6e0263eafe05007a46fdf0c8d32b
˓→',
(continues on next page)
console.log(message);
> {
"hash": "0x4158eb81ad8e30cfcee67f20b1372983d388f1243a96e39f94fd2797b1e9c78e",
"padding":
˓→"0xc15f786f34e5cef0fef6ce7c1185d799ecdb5ebca72b3310648c5588db2e99a0d73301c7a8d90115a91213f0bc9c7229
˓→",
"payload": "0xdeadbeaf",
"pow": 0.5371803278688525,
"recipientPublicKey": null,
"sig": null,
"timestamp": 1496991876,
"topic": "0x01020304",
"ttl": 50
}
})
// or
.on('data', function(message){ ... });
15.29 clearSubscriptions
web3.shh.clearSubscriptions()
Resets subscriptions.
Note: This will not reset subscriptions from other packages like web3-eth, as they use their own requestManager.
15.29.1 Parameters
15.29.2 Returns
Boolean
15.29.3 Example
...
web3.shh.clearSubscriptions();
15.30 newMessageFilter
web3.shh.newMessageFilter(options)
Create a new filter within the node. This filter can be used to poll for new messages that match the set of criteria.
15.30.1 Parameters
15.30.2 Returns
15.30.3 Example
web3.shh.newMessageFilter()
.then(console.log);
> "2b47fbafb3cce24570812a82e6e93cd9e2551bbc4823f6548ff0d82d2206b326"
15.31 deleteMessageFilter
web3.shh.deleteMessageFilter(id)
15.31.1 Parameters
15.31.2 Returns
15.31.3 Example
web3.shh.deleteMessageFilter(
˓→'2b47fbafb3cce24570812a82e6e93cd9e2551bbc4823f6548ff0d82d2206b326')
.then(console.log);
> true
15.32 getFilterMessages
web3.shh.getFilterMessages(id)
Retrieve messages that match the filter criteria and are received between the last time this function was called and now.
15.32.1 Parameters
15.32.2 Returns
15.32.3 Example
web3.shh.getFilterMessages(
˓→'2b47fbafb3cce24570812a82e6e93cd9e2551bbc4823f6548ff0d82d2206b326')
.then(console.log);
> [{
"hash": "0x4158eb81ad8e30cfcee67f20b1372983d388f1243a96e39f94fd2797b1e9c78e",
"padding":
˓→"0xc15f786f34e5cef0fef6ce7c1185d799ecdb5ebca72b3310648c5588db2e99a0d73301c7a8d90115a91213f0bc9c7229
˓→",
"payload": "0xdeadbeaf",
"pow": 0.5371803278688525,
"recipientPublicKey": null,
"sig": null,
"timestamp": 1496991876,
"topic": "0x01020304",
"ttl": 50
},{...}]
web3.utils
This package provides utility functions for Ethereum dapps and other web3.js packages.
A Bloom filter is a probabilistic, space-efficient data structure used for fast checks of set membership. That probably
doesn’t mean much to you yet, and so let’s explore how bloom filters might be used.
Imagine that we have some large set of data, and we want to be able to quickly test if some element is currently in that
set. The naive way of checking might be to query the set to see if our element is in there. That’s probably fine if our
data set is relatively small. Unfortunately, if our data set is really big, this search might take a while. Luckily, we have
tricks to speed things up in the ethereum world!
A bloom filter is one of these tricks. The basic idea behind the Bloom filter is to hash each new element that goes into
the data set, take certain bits from this hash, and then use those bits to fill in parts of a fixed-size bit array (e.g. set
certain bits to 1). This bit array is called a bloom filter.
Later, when we want to check if an element is in the set, we simply hash the element and check that the right bits are
in the bloom filter. If at least one of the bits is 0, then the element definitely isn’t in our data set! If all of the bits are
1, then the element might be in the data set, but we need to actually query the database to be sure. So we might have
false positives, but we’ll never have false negatives. This can greatly reduce the number of database queries we have
to make.
Real Life Example
An ethereum real life example in where this is useful is if you want to update a users balance on every new block
so it stays as close to real time as possible. Without using a bloom filter on every new block you would have to
force the balances even if that user may not of had any activity within that block. But if you use the logBlooms from
the block you can test the bloom filter against the users ethereum address before you do any more slow operations,
this will dramatically decrease the amount of calls you do as you will only be doing those extra operations if that
205
web3.js Documentation, Release 1.0.0
ethereum address is within that block (minus the false positives outcome which will be negligible). This will be highly
performant for your app.
16.1.2 Functions
• web3.utils.isBloom
• web3.utils.isUserEthereumAddressInBloom
• web3.utils.isContractAddressInBloom
• web3.utils.isTopic
• web3.utils.isTopicInBloom
• web3.utils.isInBloom
16.2 randomHex
web3.utils.randomHex(size)
The randomHex library to generate cryptographically strong pseudo-random HEX strings from a given byte size.
16.2.1 Parameters
1. size - Number: The byte size for the HEX string, e.g. 32 will result in a 32 bytes HEX string with 64
characters prefixed with “0x”.
16.2.2 Returns
16.2.3 Example
web3.utils.randomHex(32)
> "0xa5b9d60f32436310afebcfda832817a68921beb782fabf7915cc0460b443116a"
web3.utils.randomHex(4)
> "0x6892ffc6"
web3.utils.randomHex(2)
> "0x99d6"
web3.utils.randomHex(1)
> "0x9a"
16.3 BN
web3.utils.BN(mixed)
The BN.js library for calculating with big numbers in JavaScript. See the BN.js documentation for details.
Note: For safe conversion of many types, incl BigNumber.js use utils.toBN
16.3.1 Parameters
16.3.2 Returns
16.3.3 Example
var BN = web3.utils.BN;
new BN(1234).toString();
> "1234"
new BN('0xea').toString();
> "234"
16.4 isBN
web3.utils.isBN(bn)
16.4.1 Parameters
16.3. BN 207
web3.js Documentation, Release 1.0.0
16.4.2 Returns
Boolean
16.4.3 Example
web3.utils.isBN(number);
> true
16.5 isBigNumber
web3.utils.isBigNumber(bignumber)
16.5.1 Parameters
16.5.2 Returns
Boolean
16.5.3 Example
web3.utils.isBigNumber(number);
> true
16.6 sha3
web3.utils.sha3(string | BN | Buffer)
web3.utils.keccak256(string | BN | Buffer) // ALIAS
16.6.1 Parameters
16.6.2 Returns
16.6.3 Example
web3.utils.sha3(new BN('234'));
> "0xbc36789e7a1e281436464229828f817d6612f7b477d66591ff96a9e064bcc98a"
web3.utils.sha3(234);
> null // can't calculate the hash of a number
16.7 sha3Raw
web3.utils.sha3Raw(string)
Will calculate the sha3 of the input but does return the hash value instead of null if for example an empty string is
passed.
Note: Further details about this function can be seen here sha3
16.8 soliditySha3
Will calculate the sha3 of given input parameters in the same way solidity would. This means arguments will be ABI
converted and tightly packed before being hashed.
Warning: This method poses a security risk where multiple inputs can compute to the same hash. Provided in
the example code are multiple cases of this security risk
16.8.1 Parameters
1. paramX - Mixed: Any type, or an object with {type: 'uint', value: '123456'} or {t:
'bytes', v: '0xfff456'}. Basic types are autodetected as follows:
• String non numerical UTF-8 string is interpreted as string.
• String|Number|BN|HEX positive number is interpreted as uint256.
• String|Number|BN negative number is interpreted as int256.
• Boolean as bool.
• String HEX string with leading 0x is interpreted as bytes.
• HEX HEX number representation is interpreted as uint256.
16.8.2 Returns
16.8.3 Example
// "0xfb0a9d38c4dc568cbd105866540986fabf3c08c1bfb78299ce21aa0e5c0c586b"
web3.utils.soliditySha3({type: 'string', value: 'hell'},{type: 'string', value:
˓→'oworld'},{type: 'uint16', value: 0x3031})
// "0xfb0a9d38c4dc568cbd105866540986fabf3c08c1bfb78299ce21aa0e5c0c586b"
web3.utils.soliditySha3({type: 'uint96', value: '32309054545061485574011236401'})
// "0xfb0a9d38c4dc568cbd105866540986fabf3c08c1bfb78299ce21aa0e5c0c586b"
web3.utils.soliditySha3('0x407D73d8a49eeb85D32Cf465507dd71d507100c1');
> "0x4e8ebbefa452077428f93c9520d3edd60594ff452a29ac7d2ccc11d47f3ab95b"
> "0xa13b31627c1ed7aaded5aecec71baf02fe123797fffd45e662eac8e06fbe4955"
16.9 soliditySha3Raw
Will calculate the sha3 of given input parameters in the same way solidity would. This means arguments will be ABI
converted and tightly packed before being hashed. The difference between this function and the soliditySha3
function is that it will return the hash value instead of null if for example an empty string is given.
Note: Further details about this function can be seen here soliditySha3
16.10 isHex
web3.utils.isHex(hex)
16.10.1 Parameters
16.10.2 Returns
Boolean
16.10.3 Example
web3.utils.isHex('0xc1912');
> true
web3.utils.isHex(0xc1912);
> true
web3.utils.isHex('c1912');
> true
web3.utils.isHex(345);
> true // this is tricky, as 345 can be a a HEX representation or a number, be
˓→careful when not having a 0x in front!
web3.utils.isHex('0xZ1912');
> false
web3.utils.isHex('Hello');
> false
16.11 isHexStrict
web3.utils.isHexStrict(hex)
Checks if a given string is a HEX string. Difference to web3.utils.isHex() is that it expects HEX to be prefixed
with 0x.
16.11.1 Parameters
16.11.2 Returns
Boolean
16.11.3 Example
web3.utils.isHexStrict('0xc1912');
> true
web3.utils.isHexStrict(0xc1912);
> false
web3.utils.isHexStrict('c1912');
> false
web3.utils.isHexStrict(345);
> false // this is tricky, as 345 can be a a HEX representation or a number, be
˓→careful when not having a 0x in front!
web3.utils.isHexStrict('0xZ1912');
> false
web3.utils.isHex('Hello');
> false
16.12 isAddress
web3.utils.isAddress(address)
Checks if a given string is a valid Ethereum address. It will also check the checksum, if the address has upper and
lowercase letters.
16.12.1 Parameters
16.12.2 Returns
Boolean
16.12.3 Example
web3.utils.isAddress('0xc1912fee45d61c87cc5ea59dae31190fffff232d');
> true
web3.utils.isAddress('c1912fee45d61c87cc5ea59dae31190fffff232d');
> true
web3.utils.isAddress('0XC1912FEE45D61C87CC5EA59DAE31190FFFFF232D');
> true // as all is uppercase, no checksum will be checked
web3.utils.isAddress('0xc1912fEE45d61C87Cc5EA59DaE31190FFFFf232d');
> true
(continues on next page)
web3.utils.isAddress('0xC1912fEE45d61C87Cc5EA59DaE31190FFFFf232d');
> false // wrong checksum
16.13 toChecksumAddress
web3.utils.toChecksumAddress(address)
16.13.1 Parameters
16.13.2 Returns
16.13.3 Example
web3.utils.toChecksumAddress('0xc1912fee45d61c87cc5ea59dae31190fffff232d');
> "0xc1912fEE45d61C87Cc5EA59DaE31190FFFFf232d"
web3.utils.toChecksumAddress('0XC1912FEE45D61C87CC5EA59DAE31190FFFFF232D');
> "0xc1912fEE45d61C87Cc5EA59DaE31190FFFFf232d" // same as above
16.14 checkAddressChecksum
web3.utils.checkAddressChecksum(address)
Checks the checksum of a given address. Will also return false on non-checksum addresses.
16.14.1 Parameters
16.14.2 Returns
Boolean: true when the checksum of the address is valid, false if it’s not a checksum address, or the checksum
is invalid.
16.14.3 Example
web3.utils.checkAddressChecksum('0xc1912fEE45d61C87Cc5EA59DaE31190FFFFf232d');
> true
16.15 toHex
web3.utils.toHex(mixed)
Will auto convert any given value to HEX. Number strings will be interpreted as numbers. Text strings will be
interpreted as UTF-8 strings.
16.15.1 Parameters
16.15.2 Returns
16.15.3 Example
web3.utils.toHex('234');
> "0xea"
web3.utils.toHex(234);
> "0xea"
web3.utils.toHex(new BN('234'));
> "0xea"
web3.utils.toHex(new BigNumber('234'));
> "0xea"
16.16 stripHexPrefix
16.16.1 Parameters
16.16.2 Returns
16.16.3 Example
web3.utils.stripHexPrefix('234');
> "234"
web3.utils.stripHexPrefix('0x234');
> "234"
web3.utils.stripHexPrefix(42);
> 42
16.17 toBN
web3.utils.toBN(number)
Will safely convert any given value (including BigNumber.js instances) into a BN.js instance, for handling big numbers
in JavaScript.
16.17.1 Parameters
16.17.2 Returns
16.17.3 Example
web3.utils.toBN(1234).toString();
> "1234"
web3.utils.toBN('1234').add(web3.utils.toBN('1')).toString();
> "1235"
web3.utils.toBN('0xea').toString();
> "234"
16.18 hexToNumberString
web3.utils.hexToNumberString(hex)
16.18.1 Parameters
16.18.2 Returns
16.18.3 Example
web3.utils.hexToNumberString('0xea');
> "234"
16.19 hexToNumber
Returns the number representation of a given HEX value. And only if the second parameter is passed as true and the
number is very big (unsafe number), it will return the value as a BigInt.
Note: To handle for big numbers, either use utils.toBN to return as BN. Or, pass true to the second parameter to return
the value as BigInt, in case of an overflow.
16.19.1 Parameters
16.19.2 Returns
Number
16.19.3 Example
web3.utils.hexToNumber('0xea');
> 234
16.20 numberToHex
web3.utils.numberToHex(number)
web3.utils.fromDecimal(number) // ALIAS, deprecated
16.20.1 Parameters
16.20.2 Returns
16.20.3 Example
web3.utils.numberToHex('234');
> '0xea'
16.21 hexToUtf8
web3.utils.hexToUtf8(hex)
web3.utils.hexToString(hex) // ALIAS
web3.utils.toUtf8(hex) // ALIAS, deprecated
16.21.1 Parameters
16.21.2 Returns
16.21.3 Example
web3.utils.hexToUtf8('0x49206861766520313030e282ac');
> "I have 100C"
16.22 hexToAscii
web3.utils.hexToAscii(hex)
web3.utils.toAscii(hex) // ALIAS, deprecated
16.22.1 Parameters
16.22.2 Returns
16.22.3 Example
web3.utils.hexToAscii('0x4920686176652031303021');
> "I have 100!"
16.23 utf8ToHex
web3.utils.utf8ToHex(string)
web3.utils.stringToHex(string) // ALIAS
web3.utils.fromUtf8(string) // ALIAS, deprecated
16.23.1 Parameters
16.23.2 Returns
16.23.3 Example
16.24 asciiToHex
web3.utils.asciiToHex(string)
web3.utils.fromAscii(string) // ALIAS, deprecated
16.24.1 Parameters
16.24.2 Returns
16.24.3 Example
16.25 hexToBytes
web3.utils.hexToBytes(hex)
16.25.1 Parameters
16.25.2 Returns
16.25.3 Example
web3.utils.hexToBytes('0x000000ea');
> [ 0, 0, 0, 234 ]
web3.utils.hexToBytes(0x000000ea);
> [ 234 ]
16.26 bytesToHex
web3.utils.bytesToHex(byteArray)
16.26.1 Parameters
16.26.2 Returns
16.26.3 Example
16.27 toWei
web3.utils.toWei(number [, unit])
Note: “wei” are the smallest ether unit, and you should always make calculations in wei and convert only for display
reasons.
16.27.1 Parameters
16.27.2 Returns
16.27.3 Example
web3.utils.toWei('1', 'ether');
> "1000000000000000000"
web3.utils.toWei('1', 'finney');
> "1000000000000000"
web3.utils.toWei('1', 'szabo');
> "1000000000000"
web3.utils.toWei('1', 'shannon');
> "1000000000"
16.28 fromWei
web3.utils.fromWei(number [, unit])
Note: “wei” are the smallest ether unit, and you should always make calculations in wei and convert only for display
reasons.
16.28.1 Parameters
• 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’
16.28.2 Returns
16.28.3 Example
web3.utils.fromWei('1', 'ether');
> "0.000000000000000001"
web3.utils.fromWei('1', 'finney');
> "0.000000000000001"
web3.utils.fromWei('1', 'szabo');
> "0.000000000001"
web3.utils.fromWei('1', 'shannon');
> "0.000000001"
16.29 unitMap
web3.utils.unitMap
16.29.2 Example
web3.utils.unitMap
> {
noether: '0',
wei: '1',
kwei: '1000',
Kwei: '1000',
(continues on next page)
16.30 padLeft
Adds a padding on the left of a string, Useful for adding paddings to HEX strings.
16.30.1 Parameters
16.30.2 Returns
16.30.3 Example
web3.utils.padLeft('0x3456ff', 20);
> "0x000000000000003456ff"
web3.utils.padLeft(0x3456ff, 20);
> "0x000000000000003456ff"
16.31 padRight
Adds a padding on the right of a string, Useful for adding paddings to HEX strings.
16.31.1 Parameters
16.31.2 Returns
16.31.3 Example
web3.utils.padRight('0x3456ff', 20);
> "0x3456ff00000000000000"
web3.utils.padRight(0x3456ff, 20);
> "0x3456ff00000000000000"
16.32 toTwosComplement
web3.utils.toTwosComplement(number)
16.32.1 Parameters
16.32.2 Returns
16.32.3 Example
web3.utils.toTwosComplement('-1');
> "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
web3.utils.toTwosComplement(-1);
> "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
web3.utils.toTwosComplement('0x1');
> "0x0000000000000000000000000000000000000000000000000000000000000001"
web3.utils.toTwosComplement(-15);
> "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1"
web3.utils.toTwosComplement('-0x1');
> "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
Special thanks to Netlify for providing build and deploy services for our end-to-end integration tests.
C
contract deploy, 82
J
JSON interface, 73
N
npm, 3
Y
yarn, 3
229